<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();
        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.csv("cooccurrenceMatrixData.csv", function(data){

  selectedList = ['pm','school','mandarin','up','chinese','strike','new'];
  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);

  };
  drawGraph(graphDict);

  function drawGraph(graph){
    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;
    }

  }
  }

});

/*
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>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();

    }
    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.csv("cooccurrenceMatrixData.csv", function(data){

  selectedList = ['pm','school','mandarin','up','chinese','strike','new'];
  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);

  };
  drawGraph(graphDict);

  function drawGraph(graph){
    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;
    }

  }
  }

});

/*
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>function copyVals(){
	var text = $("#inputText").val();
	$("#outputText").val(text.trim());
	$("#outputText").removeClass("btn-success btn-warning");
	$(".multioutput").removeClass("btn-success btn-warning");
}

function clickToCopy(text){
	$("#outputText").val(text);
	$("#outputText").removeClass("btn-success btn-warning");
	formValidate($("#outputText"),text);
}

function recordLog(){
}

function formValidate(obj,text){
	var ret = validate(text,keywords);
	if(ret.length>0){
		if(ret[0][1]=="full"){
			classstring="btn-success";
		}
		else{
			classstring="btn-warning";
		}
	}
	else{
		classstring="";
	}
	if(obj){
		$(obj).addClass(classstring);
	}
	else{
		return classstring;
	}
	return;
}

function formAtbash(){
	text = atbash($("#outputText").val());
	$("#outputText").val(text);
	formValidate($("#outputText"),text);
}

function formReverse(){
	text = reverse($("#outputText").val());
	$("#outputText").val(text);
	formValidate($("#outputText"),text);
}

function formOddEven(){
	var text = $("#outputText").val();
	$(".multioutput").remove();
	$("#outputText").removeClass("btn-success btn-warning");
	$("#multioutput").append("

Odd

");
	$("#multioutput").append("

Even

");

	ret = extractAlternatingChars(text,0);
	$("#multioutput #odd").append("
"+ret+"
");
	$("#multioutput #odd .multioutput:last-child").addClass(formValidate("",ret));
	$("#multioutput #odd .multioutput:last-child").attr("value",ret);
	$("#multioutput #odd .multioutput:last-child").attr("ondblclick","clickToCopy(\""+ret+"\")");

	ret = extractAlternatingChars(text,1);
	$("#multioutput #even").append("
"+ret+"
");
	$("#multioutput #even .multioutput:last-child").addClass(formValidate("",ret));
	$("#multioutput #even .multioutput:last-child").attr("value",ret);
	$("#multioutput #even .multioutput:last-child").attr("ondblclick","clickToCopy(\""+ret+"\")");
}

function formRotN(){
	var text = $("#outputText").val();
	$(".multioutput").remove();
	for(i=1;i<=25;i++){
		ret = caesar(text,i,0);
		$("#multioutput").append("
"+ret+" rot:"+i+"
");
		$("#multioutput .multioutput:last-child").attr("ondblclick","clickToCopy(\""+ret+"\")");
	}
	formValidate();
}

function formColumnar(){
	var text = $("#outputText").val();
	var fac = factors(text);
	$(".multioutput").remove();
	$("#outputText").removeClass("btn-success btn-warning");
	$("#multioutput").append("

Top to Bottom: Left to Right

");
	$("#multioutput").append("

Top to Bottom: Right to Left

");
	$("#multioutput").append("

Bottom to Top: Left to Right

");
	$("#multioutput").append("

Bottom to Top: Right to Left

");
	$("#multioutput").append("

Right to Left: Top to Bottom

");
	$("#multioutput").append("

Right to Left: Bottom to Top

");
	$("#multioutput").append("

Left to Right: Top to Bottom

");
	$("#multioutput").append("

Left to Right: Bottom to Top

");

	for(i=0;i<fac.length;i++){
		ret = columnar_transposition(text,fac[i],0);
		$("#multioutput #column0").append("
"+ret+" (columns:"+fac[i]+")
");
		$("#multioutput #column0 .multioutput:last-child").addClass(formValidate("",ret));
		$("#multioutput #column0 .multioutput:last-child").attr("value",ret);
		$("#multioutput #column0 .multioutput:last-child").attr("ondblclick","clickToCopy(\""+ret+"\")");

		ret = columnar_transposition(text,fac[i],1);
		$("#multioutput #column1").append("
"+ret+"(columns:"+fac[i]+")
");
		$("#multioutput #column1 .multioutput:last-child").addClass(formValidate("",ret));
		$("#multioutput #column1 .multioutput:last-child").attr("value",ret);
		$("#multioutput #column1 .multioutput:last-child").attr("ondblclick","clickToCopy(\""+ret+"\")");

		ret = columnar_transposition(text,fac[i],2);
		$("#multioutput #column2").append("
"+ret+"(columns:"+fac[i]+")
");
		$("#multioutput #column2 .multioutput:last-child").addClass(formValidate("",ret));
		$("#multioutput #column2 .multioutput:last-child").attr("value",ret);
		$("#multioutput #column2 .multioutput:last-child").attr("ondblclick","clickToCopy(\""+ret+"\")");

		ret = columnar_transposition(text,fac[i],3);
		$("#multioutput #column3").append("
"+ret+"(columns:"+fac[i]+")
");
		$("#multioutput #column3 .multioutput:last-child").addClass(formValidate("",ret));
		$("#multioutput #column3 .multioutput:last-child").attr("value",ret);
		$("#multioutput #column3 .multioutput:last-child").attr("ondblclick","clickToCopy(\""+ret+"\")");

		ret = columnar_transposition(text,fac[i],4);
		$("#multioutput #column4").append("
"+ret+"(columns:"+fac[i]+")
");
		$("#multioutput #column4 .multioutput:last-child").addClass(formValidate("",ret));
		$("#multioutput #column4 .multioutput:last-child").attr("value",ret);
		$("#multioutput #column4 .multioutput:last-child").attr("ondblclick","clickToCopy(\""+ret+"\")");

		ret = columnar_transposition(text,fac[i],5);
		$("#multioutput #column5").append("
"+ret+"(columns:"+fac[i]+")
");
		$("#multioutput #column5 .multioutput:last-child").addClass(formValidate("",ret));
		$("#multioutput #column5 .multioutput:last-child").attr("value",ret);
		$("#multioutput #column5 .multioutput:last-child").attr("ondblclick","clickToCopy(\""+ret+"\")");

		ret = columnar_transposition(text,fac[i],6);
		$("#multioutput #column6").append("
"+ret+"(columns:"+fac[i]+")
");
		$("#multioutput #column6 .multioutput:last-child").addClass(formValidate("",ret));
		$("#multioutput #column6 .multioutput:last-child").attr("value",ret);
		$("#multioutput #column6 .multioutput:last-child").attr("ondblclick","clickToCopy(\""+ret+"\")");

		ret = columnar_transposition(text,fac[i],7);
		$("#multioutput #column7").append("
"+ret+"(columns:"+fac[i]+")
");
		$("#multioutput #column7 .multioutput:last-child").addClass(formValidate("",ret));
		$("#multioutput #column7 .multioutput:last-child").attr("value",ret);
		$("#multioutput #column7 .multioutput:last-child").attr("ondblclick","clickToCopy(\""+ret+"\")");

	}

}

function formLettersNum(flag){
	text = $("#outputText").val();
	text = numText(text,flag);
	$("#outputText").removeClass("btn-success btn-warning");
	$("#outputText").val(text);
	formValidate($("#outputText"),text);
}

function formCaseSwitch(){
	text = caseSwitch($("#outputText").val());
	$("#outputText").val(text);
	formValidate($("#outputText"),text);
}

function formGroup(n){
	text = $("#outputText").val();
	output = "";
	for(i=0;i<text.length;i++){
		output = output+ text.charAt(i);
		if((i+1)%n==0){
			output = output + " ";
		}
	}
	$("#outputText").val(output);
}
<commit_msg>Update formhelper.js<commit_after>function copyVals(){
	var text = $("#inputText").val();
	$("#outputText").val(text.trim());
	$("#outputText").removeClass("btn-success btn-warning");
	$(".multioutput").removeClass("btn-success btn-warning");
}

function clickToCopy(text){
	$("#outputText").val(text);
	$("#outputText").removeClass("btn-success btn-warning");
	formValidate($("#outputText"),text);
}

function recordLog(){
}

function formValidate(obj,text){
	var ret = validate(text,keywords);
	if(ret.length>0){
		if(ret[0][1]=="full"){
			classstring="btn-success";
		}
		else if(ret[0][1]=="pattern"){
			classstring="btn-warning";
		}
		else if(ret[0][1]=="partial"){
			classstring="btn-info";
		}
	}
	else{
		classstring="";
	}
	if(obj){
		$(obj).addClass(classstring);
	}
	else{
		return classstring;
	}
	return;
}

function formAtbash(){
	text = atbash($("#outputText").val());
	$("#outputText").val(text);
	formValidate($("#outputText"),text);
}

function formReverse(){
	text = reverse($("#outputText").val());
	$("#outputText").val(text);
	formValidate($("#outputText"),text);
}

function formOddEven(){
	var text = $("#outputText").val();
	$(".multioutput").remove();
	$("#outputText").removeClass("btn-success btn-warning");
	$("#multioutput").append("

Odd

");
	$("#multioutput").append("

Even

");

	ret = extractAlternatingChars(text,0);
	$("#multioutput #odd").append("
"+ret+"
");
	$("#multioutput #odd .multioutput:last-child").addClass(formValidate("",ret));
	$("#multioutput #odd .multioutput:last-child").attr("value",ret);
	$("#multioutput #odd .multioutput:last-child").attr("ondblclick","clickToCopy(\""+ret+"\")");

	ret = extractAlternatingChars(text,1);
	$("#multioutput #even").append("
"+ret+"
");
	$("#multioutput #even .multioutput:last-child").addClass(formValidate("",ret));
	$("#multioutput #even .multioutput:last-child").attr("value",ret);
	$("#multioutput #even .multioutput:last-child").attr("ondblclick","clickToCopy(\""+ret+"\")");
}

function formRotN(){
	var text = $("#outputText").val();
	$(".multioutput").remove();
	for(i=1;i<=25;i++){
		ret = caesar(text,i,0);
		$("#multioutput").append("
"+ret+" rot:"+i+"
");
		$("#multioutput .multioutput:last-child").attr("ondblclick","clickToCopy(\""+ret+"\")");
	}
	formValidate();
}

function formColumnar(){
	var text = $("#outputText").val();
	var fac = factors(text);
	$(".multioutput").remove();
	$("#outputText").removeClass("btn-success btn-warning");
	$("#multioutput").append("

Top to Bottom: Left to Right

");
	$("#multioutput").append("

Top to Bottom: Right to Left

");
	$("#multioutput").append("

Bottom to Top: Left to Right

");
	$("#multioutput").append("

Bottom to Top: Right to Left

");
	$("#multioutput").append("

Right to Left: Top to Bottom

");
	$("#multioutput").append("

Right to Left: Bottom to Top

");
	$("#multioutput").append("

Left to Right: Top to Bottom

");
	$("#multioutput").append("

Left to Right: Bottom to Top

");

	for(i=0;i<fac.length;i++){
		ret = columnar_transposition(text,fac[i],0);
		$("#multioutput #column0").append("
"+ret+" (columns:"+fac[i]+")
");
		$("#multioutput #column0 .multioutput:last-child").addClass(formValidate("",ret));
		$("#multioutput #column0 .multioutput:last-child").attr("value",ret);
		$("#multioutput #column0 .multioutput:last-child").attr("ondblclick","clickToCopy(\""+ret+"\")");

		ret = columnar_transposition(text,fac[i],1);
		$("#multioutput #column1").append("
"+ret+"(columns:"+fac[i]+")
");
		$("#multioutput #column1 .multioutput:last-child").addClass(formValidate("",ret));
		$("#multioutput #column1 .multioutput:last-child").attr("value",ret);
		$("#multioutput #column1 .multioutput:last-child").attr("ondblclick","clickToCopy(\""+ret+"\")");

		ret = columnar_transposition(text,fac[i],2);
		$("#multioutput #column2").append("
"+ret+"(columns:"+fac[i]+")
");
		$("#multioutput #column2 .multioutput:last-child").addClass(formValidate("",ret));
		$("#multioutput #column2 .multioutput:last-child").attr("value",ret);
		$("#multioutput #column2 .multioutput:last-child").attr("ondblclick","clickToCopy(\""+ret+"\")");

		ret = columnar_transposition(text,fac[i],3);
		$("#multioutput #column3").append("
"+ret+"(columns:"+fac[i]+")
");
		$("#multioutput #column3 .multioutput:last-child").addClass(formValidate("",ret));
		$("#multioutput #column3 .multioutput:last-child").attr("value",ret);
		$("#multioutput #column3 .multioutput:last-child").attr("ondblclick","clickToCopy(\""+ret+"\")");

		ret = columnar_transposition(text,fac[i],4);
		$("#multioutput #column4").append("
"+ret+"(columns:"+fac[i]+")
");
		$("#multioutput #column4 .multioutput:last-child").addClass(formValidate("",ret));
		$("#multioutput #column4 .multioutput:last-child").attr("value",ret);
		$("#multioutput #column4 .multioutput:last-child").attr("ondblclick","clickToCopy(\""+ret+"\")");

		ret = columnar_transposition(text,fac[i],5);
		$("#multioutput #column5").append("
"+ret+"(columns:"+fac[i]+")
");
		$("#multioutput #column5 .multioutput:last-child").addClass(formValidate("",ret));
		$("#multioutput #column5 .multioutput:last-child").attr("value",ret);
		$("#multioutput #column5 .multioutput:last-child").attr("ondblclick","clickToCopy(\""+ret+"\")");

		ret = columnar_transposition(text,fac[i],6);
		$("#multioutput #column6").append("
"+ret+"(columns:"+fac[i]+")
");
		$("#multioutput #column6 .multioutput:last-child").addClass(formValidate("",ret));
		$("#multioutput #column6 .multioutput:last-child").attr("value",ret);
		$("#multioutput #column6 .multioutput:last-child").attr("ondblclick","clickToCopy(\""+ret+"\")");

		ret = columnar_transposition(text,fac[i],7);
		$("#multioutput #column7").append("
"+ret+"(columns:"+fac[i]+")
");
		$("#multioutput #column7 .multioutput:last-child").addClass(formValidate("",ret));
		$("#multioutput #column7 .multioutput:last-child").attr("value",ret);
		$("#multioutput #column7 .multioutput:last-child").attr("ondblclick","clickToCopy(\""+ret+"\")");

	}

}

function formLettersNum(flag){
	text = $("#outputText").val();
	text = numText(text,flag);
	$("#outputText").removeClass("btn-success btn-warning");
	$("#outputText").val(text);
	formValidate($("#outputText"),text);
}

function formCaseSwitch(){
	text = caseSwitch($("#outputText").val());
	$("#outputText").val(text);
	formValidate($("#outputText"),text);
}

function formGroup(n){
	text = $("#outputText").val();
	output = "";
	for(i=0;i<text.length;i++){
		output = output+ text.charAt(i);
		if((i+1)%n==0){
			output = output + " ";
		}
	}
	$("#outputText").val(output);
}
<|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:not(.dropdown-toggle)').click(function() {
    $('.navbar-toggle:visible').click();
});

$(function() {
  var stage = new createjs.Stage("viewport");

  base_image = new Image();
  base_image.src = 'img/map/map.png';

  base_image.onload = function(){
    var bitmap = new createjs.Bitmap(base_image);
    stage.addChild(bitmap);
    bitmap.addEventListener("click", function(event) {
       $(".myObj").popover('hide');
    });

    marker = new Image();
    marker.src = 'img/map/marker.png';

    marker.onload = function(){
      var bitmap_marker = [];
      $.getJSON("http://vicsurv.cloudapp.net:5780/api/get_daily_levels", function( data ) {
        $.each(data, function(i, item) {
          bitmap_marker[i] = new createjs.Bitmap(marker);
          bitmap_marker[i].x = item.x - 25;
          bitmap_marker[i].y = item.y - 25;
          bitmap_marker[i].addEventListener("click", function(event) {
            ni = (item.ni_p50/13.4*100).toFixed(1);
            ox = (item.ox_p50/11*100).toFixed(1);
            ph = (item.ph_p50/2.4*100).toFixed(1);
            ts = (item.ts_p50/47*100).toFixed(1);
            content = "
" + item.region + "
Nitrogen: " + ni + "%
Oxygen: " + ox + "%
Phosphorus: " + ph + "%
Total suspended solids: " + ts + "%"
            $(".myObj").attr('data-content', content)
            $(".myObj").attr('data-original-title', item.area);
            $(".myObj").css({'position':'absolute','top':item.y,'left':item.x + 15}).popover({
                html : true,
                trigger: 'click',
                placement:'top'
            }).popover('show');
          });
          stage.addChild(bitmap_marker[i]);
        });

        stage.update();
      });
    };
  };
});<commit_msg>add hover animation<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:not(.dropdown-toggle)').click(function() {
    $('.navbar-toggle:visible').click();
});

$(function() {
  var stage = new createjs.Stage("viewport");

  base_image = new Image();
  base_image.src = 'img/map/map.png';

  base_image.onload = function(){
    var bitmap = new createjs.Bitmap(base_image);
    stage.enableMouseOver(10);
    stage.addChild(bitmap);
    bitmap.addEventListener("click", function(event) {
       $(".myObj").popover('hide');
    });

    marker = new Image();
    marker.src = 'img/map/marker.png';

    marker.onload = function(){
      var bitmap_marker = [];
      $.getJSON("http://vicsurv.cloudapp.net:5780/api/get_daily_levels", function( data ) {
        $.each(data, function(i, item) {
          bitmap_marker[i] = new createjs.Bitmap(marker);
          bitmap_marker[i].alpha = 0.5;
          bitmap_marker[i].x = item.x - 25;
          bitmap_marker[i].y = item.y - 25;
          bitmap_marker[i].on("mouseover", handleInteraction);
          bitmap_marker[i].on("mouseout", handleInteraction);
          bitmap_marker[i].addEventListener("click", function(event) {
            ni = (item.ni_p50/13.4*100).toFixed(1);
            ox = (item.ox_p50/11*100).toFixed(1);
            ph = (item.ph_p50/2.4*100).toFixed(1);
            ts = (item.ts_p50/47*100).toFixed(1);
            content = "
" + item.region + "
Nitrogen: " + ni + "%
Oxygen: " + ox + "%
Phosphorus: " + ph + "%
Total suspended solids: " + ts + "%"
            $(".myObj").attr('data-content', content);
            $(".myObj").attr('data-original-title', item.area);
            $(".myObj").css({'position':'absolute','top':item.y,'left':item.x + 15}).popover({
                html : true,
                trigger: 'click',
                placement:'top'
            }).popover('show');
          });
          stage.addChild(bitmap_marker[i]);
        });

        stage.update();
        createjs.Ticker.addEventListener("tick", stage);
      });
    };
  };

  function handleInteraction(event) {
    event.target.alpha = (event.type == "mouseover") ? 1 : 0.5;
  }
});<|endoftext|>


<commit_before>function alternate(URL) {
  var newURL = null;
  if (URL.endsWith(".h")) {
    newURL = URL.replaceLast("m");
  } else if (URL.endsWith(".m")) {
    newURL = URL.replaceLast("h");
  }

  if (newURL) {
    window.location.href = newURL;
  }
}

String.prototype.replaceLast = function(character) {
  return this.substr(0, this.length - 1) + character;
};

$(document).ready(function() {
  $(".file > .meta > .actions").each(function() {
    var diff = $(this).parent().parent();
    var link = $("Hide");
    $(this).prepend(link);
    link.click(function() {
      var codeArea = $(diff).find('[class$="wrapper"]');
      $(this).html() == 'Hide' ? codeArea.hide() : codeArea.show()
      $(this).html($(this).html() == 'Show' ? 'Hide' : 'Show');
      return false;
    });
  });
});

$(document).keypress(function(e) {
  // Exit early if we're in an input field
  // This wasn't needed in Chrome but is in Safari
  if (document.activeElement.nodeName === "INPUT") {
    return;
  }

  // The letter 'a'
  var aPressed = (e.which == 97 ? true : false);
  if (aPressed) {
    alternate(window.location.href);
  }
});

function selectElements(_this) {
  _this.actions = commentForm().querySelector('.form-actions');
  _this.bubblesContent = document.querySelectorAll('.timeline-new-comment.js-comment-container');
  _this.bubble = _this.bubblesContent[_this.bubblesContent.length - 1];
  _this.close = _this.actions.querySelector('.js-comment-and-button');
  _this.comment = _this.actions.querySelector('.primary');
  return _this.textarea = commentForm().querySelector('textarea');
}

function commentForm() {
  return document.querySelector('.js-new-comment-form');
}

function button(text, innerHTML, closable) {
  if (closable === null) {
    closable = true;
  }

  var btn;
  btn = document.createElement('button');
  btn.innerHTML = text;
  btn.className = 'button';
  btn.setAttribute('tabindex', '1');
  btn.setAttribute('type', 'submit');
  btn.setAttribute('title', innerHTML);
  btn.addEventListener('click', function(event) {
    event.preventDefault();
    selectElements(this);
    this.textarea.value += " " + innerHTML;
    if (closable) {
      this.close.click();
    } else {
      this.comment.click();
    }
    return this.textarea.value = '';
  });

  return btn;
}

function insertButtons(elem) {
  var btn, closeButtonGroup, openButtonGroup;
  closeButtonGroup = document.createElement('div');
  closeButtonGroup.className = 'button-group';
  closeButtonGroup.setAttribute('style', 'margin: 10px 0 0 0;');
  openButtonGroup = document.createElement('div');
  openButtonGroup.className = 'button-group';
  openButtonGroup.setAttribute('style', 'margin: 10px 0 0 25px;');
  btn = button("Unver", "We cannot update unversioned specs (specs that point to a commit). If you'd like to add a new version the repository would have to be tagged. If you would like to use a different commit in your own project you can use some flags in your `Podfile` documented [here](http://guides.cocoapods.org/syntax/podfile.html#pod)");
  closeButtonGroup.appendChild(btn);
  btn = button("Trunk", "We have just launched 'Trunk', which is the new way for you to submit your Pods. For more information on this have a read through the post at http://blog.cocoapods.org/CocoaPods-Trunk/ If you have previously had your Pod merged into the master repository, please ensure you claim your Pod http://blog.cocoapods.org/Claim-Your-Pods/");
  closeButtonGroup.appendChild(btn);
  btn = button("Structure", "The folder structure of this spec should be `name/version/name.podspec` where `name` is the same as `s.name` in the spec file.", false);
  openButtonGroup.appendChild(btn);
  btn = button("Tags", "`git push --tags`", false);
  openButtonGroup.appendChild(btn);
  btn = button("", ":beers:", false);
  openButtonGroup.appendChild(btn);
  btn = button("", ":+1:", false);
  openButtonGroup.appendChild(btn);
  elem.appendChild(closeButtonGroup);
  elem.appendChild(openButtonGroup);
}

(function() {
  if (!commentForm()) {
    return;
  }

  var mutationObserver, observer;
  selectElements(this);
  mutationObserver = typeof WebKitMutationObserver !== "undefined" && WebKitMutationObserver !== null ? WebKitMutationObserver : MutationObserver;
  observer = new mutationObserver(function(mutations) {
    return mutations.forEach(function(mutation) {
      return selectElements(this);
    });
  });

  observer.observe(this.actions, {
    childList: true
  });

  if (this.close) {
    insertButtons(this.bubble);
  }
}).call();
<commit_msg>Update for GitHub html changes<commit_after>function alternate(URL) {
  var newURL = null;
  if (URL.endsWith(".h")) {
    newURL = URL.replaceLast("m");
  } else if (URL.endsWith(".m")) {
    newURL = URL.replaceLast("h");
  }

  if (newURL) {
    window.location.href = newURL;
  }
}

String.prototype.replaceLast = function(character) {
  return this.substr(0, this.length - 1) + character;
};

$(document).ready(function() {
  $(".file > .meta > .actions").each(function() {
    var diff = $(this).parent().parent();
    var link = $("Hide");
    $(this).prepend(link);
    link.click(function() {
      var codeArea = $(diff).find('[class$="wrapper"]');
      $(this).html() == 'Hide' ? codeArea.hide() : codeArea.show()
      $(this).html($(this).html() == 'Show' ? 'Hide' : 'Show');
      return false;
    });
  });
});

$(document).keypress(function(e) {
  // Exit early if we're in an input field
  // This wasn't needed in Chrome but is in Safari
  if (document.activeElement.nodeName === "INPUT") {
    return;
  }

  // The letter 'a'
  var aPressed = (e.which == 97 ? true : false);
  if (aPressed) {
    alternate(window.location.href);
  }
});

function selectElements(_this) {
  _this.actions = commentForm().querySelector('.form-actions');
  _this.bubblesContent = document.querySelectorAll('.timeline-new-comment.js-comment-container');
  _this.bubble = _this.bubblesContent[_this.bubblesContent.length - 1];
  _this.close = _this.actions.querySelector('.js-comment-and-button');
  _this.comment = _this.actions.querySelector('.primary');
  return _this.textarea = commentForm().querySelector('textarea');
}

function commentForm() {
  return document.querySelector('.js-new-comment-form');
}

function button(text, innerHTML, closable) {
  if (closable === null) {
    closable = true;
  }

  var btn;
  btn = document.createElement('button');
  btn.innerHTML = text;
  btn.className = 'btn';
  btn.setAttribute('tabindex', '1');
  btn.setAttribute('type', 'submit');
  btn.setAttribute('title', innerHTML);
  btn.addEventListener('click', function(event) {
    event.preventDefault();
    selectElements(this);
    this.textarea.value += " " + innerHTML;
    if (closable) {
      this.close.click();
    } else {
      this.comment.click();
    }
    return this.textarea.value = '';
  });

  return btn;
}

function insertButtons(elem) {
  var btn, buttonGroup;
  buttonGroup = document.createElement('div');
  buttonGroup.className = 'button-group';
  buttonGroup.setAttribute('style', 'margin: 10px 0 0 0;');
  btn = button("Unver", "We cannot update unversioned specs (specs that point to a commit). If you'd like to add a new version the repository would have to be tagged. If you would like to use a different commit in your own project you can use some flags in your `Podfile` documented [here](http://guides.cocoapods.org/syntax/podfile.html#pod)");
  buttonGroup.appendChild(btn);
  btn = button("Trunk", "We have just launched 'Trunk', which is the new way for you to submit your Pods. For more information on this have a read through the post at http://blog.cocoapods.org/CocoaPods-Trunk/ If you have previously had your Pod merged into the master repository, please ensure you claim your Pod http://blog.cocoapods.org/Claim-Your-Pods/");
  buttonGroup.appendChild(btn);
  btn = button("Structure", "The folder structure of this spec should be `name/version/name.podspec` where `name` is the same as `s.name` in the spec file.", false);
  buttonGroup.appendChild(btn);
  btn = button("Tags", "`git push --tags`", false);
  buttonGroup.appendChild(btn);
  btn = button("", ":beers:", false);
  buttonGroup.appendChild(btn);
  btn = button("", ":+1:", false);
  buttonGroup.appendChild(btn);
  elem.appendChild(buttonGroup);
}

(function() {
  if (!commentForm()) {
    return;
  }

  var mutationObserver, observer;
  selectElements(this);
  mutationObserver = typeof WebKitMutationObserver !== "undefined" && WebKitMutationObserver !== null ? WebKitMutationObserver : MutationObserver;
  observer = new mutationObserver(function(mutations) {
    return mutations.forEach(function(mutation) {
      return selectElements(this);
    });
  });

  observer.observe(this.actions, {
    childList: true
  });

  if (this.close) {
    insertButtons(this.bubble);
  }
}).call();
<|endoftext|>


<commit_before>(function (factory) {
    'use strict';
    if (typeof define === 'function' && define.amd) {
        // AMD is used - Register as an anonymous module.
        define(['jquery'], factory);
    } else if (typeof exports === 'object') {
        factory(require('jquery'));
    } else {
        // Neither AMD nor CommonJS used. Use global variables.
        if (typeof jQuery === 'undefined') {
            throw 'Gonrin Ref requires jQuery to be loaded first';
        }
        factory(jQuery);
    }
}(function ($) {
	'use strict';
	var GonrinRef = function (element, options) {

		var grexport = {},
		value,
		text,
		data, //datalist
		dataBound = false,
		textElement = false,
		unset = true,
        input,
        menuTemplate = '

',
        itemTemplate =  '

',
        component = false,
        widget = false,  //dialogView
        refView,
        keyMap = {
                'up': 38,
                38: 'up',
                'down': 40,
                40: 'down',
                'left': 37,
                37: 'left',
                'right': 39,
                39: 'right',
                'tab': 9,
                9: 'tab',
                'escape': 27,
                27: 'escape',
                'enter': 13,
                13: 'enter',
                //'pageUp': 33,
                //33: 'pageUp',
                //'pageDown': 34,
                //34: 'pageDown',
                //'shift': 16,
                //16: 'shift',
                //'control': 17,
                //17: 'control',
                'space': 32,
                32: 'space',
                //'t': 84,
                //84: 't',
                'delete': 46,
                46: 'delete'
        },
        keyState = {},

        /********************************************************************************
        *
        * Private functions
        *
        ********************************************************************************/
        isBackBoneDataSource = function(source){
        	var key, _i, _len, _ref;
            _ref = ["dialog"];
            for (_i = 0, _len = _ref.length; _i < _len; _i++) {
              key = _ref[_i];
              if (!source[key]) {
            	  return false;
              }
            }
            return true;
        },
        setupWidget = function () {
			//var RefView = options.dataSource
        	if(typeof options.dataSource == "function"){
        		var View = options.dataSource;
        		widget = new View();
        	}else{
        		widget = options.dataSource || null;
        	}

			//check is gonrin dialog
			if ((!!widget) && isBackBoneDataSource(widget)) {

				//require([ options.dataSource ], function ( RefView ) {
					//widget = new RefView();

					options.textField = options.textField || widget.textField;
					//options.valueField = options.valueField || widget.valueField;
					widget.uiControl.selectedItems = options.selectedItems || [];
					widget.uiControl.selectionMode = options.selectionMode || "single";

					if(!!input.val()){
						if(options.selectionMode === "single"){
							try{
								value = $.parseJSON(input.val());
								if(value){
									textElement.text(value[options.textField]);
								}
							} catch (error) {
								//console.log(error);
							}
						}
						if(options.selectionMode === "multiple"){
							try{
								value = $.parseJSON(input.val());
				            	if(value){
				            		$.each(value, function(key, item){
				            			var txt = item[options.textField];
				            			$(itemTemplate).html(txt).appendTo(textElement.find("ul"));
				            		});
				            	}
								if(value){
									textElement.text(value[options.textField]);
								}
							} catch (error) {
								//console.log(error);
							}
						}
		            }else{
		            	console.log(input.val() + " val");
		            	//widget.uiControl.applyRowSelections();
		            }
		    	//});
			};
			return grexport;
		},
		show = function () {
        	if (input.prop('disabled') || (!options.ignoreReadonly && input.prop('readonly'))) {
                return grexport;
            };
            if(widget){
            	//widget.uiControl.selectedItems = options.selectedItems || [];
            	widget.dialog();
            	widget.on("onSelected", function(){
            		if((!!widget) && (!!widget.uiControl) && (!!widget.uiControl.selectedItems)){
            			options.selectedItems = widget.uiControl.selectedItems;

        				var seleted = widget.uiControl.selectedItems;
        				if(options.selectionMode === "single"){
        					var txt = seleted.length > 0 ? seleted[0][options.textField]: "";
        					textElement.text(txt);

            				if(options.valueField){
            					value = seleted.length > 0 ? seleted[0][options.valueField]: null;
            					var inputtxt = seleted.length > 0 ? seleted[0][options.valueField]: "";
            					input.val(inputtxt);
            				}else{
            					//console.log(seleted[0]);
            					value = seleted.length > 0 ? seleted[0]: null;
            					input.val(JSON.stringify(value));
            				}
            				notifyEvent({
            					type:"change.gonrin",
            					value : value
            				});
        				}
        				if(options.selectionMode === "multiple"){
        					//textElement.html(JSON.stringify(seleted));
        					textElement.find("ul").empty();
        					var valArray = [];
			            	$.each(seleted, function(key, item){
			            		var txt = item[options.textField];
			            		$(itemTemplate).html(txt).appendTo(textElement.find("ul"));

			            		if(options.valueField){
			            			var val = item[options.valueField];
			            			valArray.push(val);
			            		}else{
			            			valArray.push(item);
			            		}
			            	});
			            	//input.val(JSON.stringify(seleted));
			            	input.val(JSON.stringify(valArray));
			            	value = valArray;
			            	notifyEvent({
            					type:"change.gonrin",
            					value : value
            				});
        				}
            		}
            	});
            }
            /*notifyEvent({
                type: 'show.gonui'
            });*/
            return grexport;
        },
        notifyEvent = function (e) {
            //if ((e.type === 'change.gonrin')  && ((e.value && (e.value === e.oldValue)) || (!e.value && !e.oldValue))) {
            //    return;
            //}
            element.trigger(e);
        },
        hide = function(){
            return grexport;
        },

        toggle = function () {
            /// Shows or hides the widget
            //return (widget.is(':hidden') ? show() : hide());
        	return show();
        },
		attachElementEvents = function () {
        	if(options.onChange){
        		element.bind("change.gonrin", options.context !== null ? $.proxy(options.onChange, options.context ) : options.onChange);
        	}

            /*input.on({
                'change': change,
                'blur': options.debug ? '' : hide,
                'keydown': keydown,
                'keyup': keyup,
                'focus': options.allowInputToggle ? show : ''
            });*/

            /*if (element.is('input')) {
                input.on({
                    'focus': show
                });
            };*/

            if (component) {
                component.on('click', toggle);
                component.on('mousedown', false);
            }

        },
        detachElementEvents = function () {
            /*input.off({
                'change': change,
                'blur': blur,
                'keydown': keydown,
                'keyup': keyup,
                'focus': options.allowInputToggle ? hide : ''
            });*/

            if (element.is('input')) {
                input.off({
                    'focus': show
                });
            }

            if (component) {
                component.off('click', toggle);
                component.off('mousedown', false);
            }
            if(widget){

            }
        },
        getValue = function(){
        	return value;
        },
        clearFilters = function(){
        	options.filters = null;
        	if(widget){
        		var colEl = widget.getCollectionElement();
        		if(colEl){
        			colEl.filter(null);
        		}
        		//widget.filters = null;
        	}
        },
		setFilters = function(filters){
        	options.filters = filters;
        	if(widget){
        		var colEl = widget.getCollectionElement();
        		if(colEl){
        			colEl.filter(options.filters);
        		}
        	}
        },
        getFilters = function(){
        	return options.filters;
        },
        clearValue = function(){
        	value = null;
        	text = null;
        	if(widget){
        		if(widget.selectionMode === "single"){
        			textElement.text("");
        			input.val("");
        		}
        		if(widget.selectionMode === "multiple"){
        			textElement.find("ul").empty();
        			input.val("");
        		}
        	}

        	notifyEvent({
				type:"change.gonrin",
				value : value
			});
        	return;
        };

		/********************************************************************************
        *
        * Public API functions
        * =====================
        ********************************************************************************/
		grexport.disable = function () {
            ///Disables the input element, the component is attached to, by adding a disabled="true" attribute to it.
            ///If the widget was visible before that call it is hidden. Possibly emits dp.hide
            hide();
            if (component && component.hasClass('btn')) {
                component.addClass('disabled');
            }
            if (textElement){
            	textElement.prop('disabled', true);
            }
            input.prop('disabled', true);
            return grexport;
        };
        grexport.getValue = getValue;
        grexport.clearValue = clearValue;
        grexport.setFilters = setFilters;
        grexport.getFilters = getFilters;
        grexport.clearFilters = clearFilters;

		// initializing element and component attributes
        if (element.is('input') ) {
            input = element;
            //value = input.val().length > 0 ? ;

            element.wrap( '');
            var inputGroupSpan = element.parent();
            //inputGroupSpan.css("width", element.outerWidth());
            var componentButton = $('').html('');
            inputGroupSpan.append(componentButton);
            component = componentButton;
            textElement = $('');
            if(options.selectionMode === "multiple"){
            	var selectRender = $(menuTemplate).appendTo(textElement);

            }
            element.before(textElement);
            element.css("display", "none");
        } else {
            throw new Error('Cannot apply to non input element');
        }

    	if (input.is('input'))  {
        	setupWidget();
        	if(!options.placeholder){
        		options.placeholder = input.attr("placeholder");
        	}
        	if(textElement && !!options.placeholder){
        		textElement.attr("placeholder", options.placeholder);
        	}

        };

        attachElementEvents();

		return grexport;
	};

	$.fn.ref = function (options) {

        return this.each(function () {
            var $this = $(this);
            if (!$this.data('gonrin')) {
                // create a private copy of the defaults object
                options = $.extend(true, {}, $.fn.ref.defaults, options);
                $this.data('gonrin', GonrinRef($this, options));
            }
        });
    };

    $.fn.ref.defaults = {
    	context: null,
    	//template: null,
    	//height: null,
    	/*placeholder: null,
    	ignore_readonly: false,*/
    	readonly : false,
    	placeholder: null,
    	selectionMode: "single",
    	selectedItems:[],
    	debug: false,
    	filters: false,
    	textField: null,
        valueField: null,
        dataSource: null,
        //value: null,
        onChange : function(){}
    };
}));<commit_msg>update readonly ref<commit_after>(function (factory) {
    'use strict';
    if (typeof define === 'function' && define.amd) {
        // AMD is used - Register as an anonymous module.
        define(['jquery'], factory);
    } else if (typeof exports === 'object') {
        factory(require('jquery'));
    } else {
        // Neither AMD nor CommonJS used. Use global variables.
        if (typeof jQuery === 'undefined') {
            throw 'Gonrin Ref requires jQuery to be loaded first';
        }
        factory(jQuery);
    }
}(function ($) {
	'use strict';
	var GonrinRef = function (element, options) {

		var grexport = {},
		value,
		text,
		data, //datalist
		dataBound = false,
		textElement = false,
		unset = true,
        input,
        menuTemplate = '

',
        itemTemplate =  '

',
        component = false,
        widget = false,  //dialogView
        refView,
        keyMap = {
                'up': 38,
                38: 'up',
                'down': 40,
                40: 'down',
                'left': 37,
                37: 'left',
                'right': 39,
                39: 'right',
                'tab': 9,
                9: 'tab',
                'escape': 27,
                27: 'escape',
                'enter': 13,
                13: 'enter',
                //'pageUp': 33,
                //33: 'pageUp',
                //'pageDown': 34,
                //34: 'pageDown',
                //'shift': 16,
                //16: 'shift',
                //'control': 17,
                //17: 'control',
                'space': 32,
                32: 'space',
                //'t': 84,
                //84: 't',
                'delete': 46,
                46: 'delete'
        },
        keyState = {},

        /********************************************************************************
        *
        * Private functions
        *
        ********************************************************************************/
        isBackBoneDataSource = function(source){
        	var key, _i, _len, _ref;
            _ref = ["dialog"];
            for (_i = 0, _len = _ref.length; _i < _len; _i++) {
              key = _ref[_i];
              if (!source[key]) {
            	  return false;
              }
            }
            return true;
        },
        setupWidget = function () {
			//var RefView = options.dataSource
        	if(typeof options.dataSource == "function"){
        		var View = options.dataSource;
        		widget = new View();
        	}else{
        		widget = options.dataSource || null;
        	}

			//check is gonrin dialog
			if ((!!widget) && isBackBoneDataSource(widget)) {

				//require([ options.dataSource ], function ( RefView ) {
					//widget = new RefView();

					options.textField = options.textField || widget.textField;
					//options.valueField = options.valueField || widget.valueField;
					widget.uiControl.selectedItems = options.selectedItems || [];
					widget.uiControl.selectionMode = options.selectionMode || "single";

					if(!!input.val()){
						if(options.selectionMode === "single"){
							try{
								value = $.parseJSON(input.val());
								if(value){
									textElement.text(value[options.textField]);
								}
							} catch (error) {
								//console.log(error);
							}
						}
						if(options.selectionMode === "multiple"){
							try{
								value = $.parseJSON(input.val());
				            	if(value){
				            		$.each(value, function(key, item){
				            			var txt = item[options.textField];
				            			$(itemTemplate).html(txt).appendTo(textElement.find("ul"));
				            		});
				            	}
								if(value){
									textElement.text(value[options.textField]);
								}
							} catch (error) {
								//console.log(error);
							}
						}
		            }else{
		            	console.log(input.val() + " val");
		            	//widget.uiControl.applyRowSelections();
		            }
		    	//});
			};
			return grexport;
		},
		show = function () {
        	if (input.prop('disabled') || (!options.ignoreReadonly && input.prop('readonly')) || (!!options.readonly)) {
                return grexport;
            };
            if(widget){
            	//widget.uiControl.selectedItems = options.selectedItems || [];
            	widget.dialog();
            	widget.on("onSelected", function(){
            		if((!!widget) && (!!widget.uiControl) && (!!widget.uiControl.selectedItems)){
            			options.selectedItems = widget.uiControl.selectedItems;

        				var seleted = widget.uiControl.selectedItems;
        				if(options.selectionMode === "single"){
        					var txt = seleted.length > 0 ? seleted[0][options.textField]: "";
        					textElement.text(txt);

            				if(options.valueField){
            					value = seleted.length > 0 ? seleted[0][options.valueField]: null;
            					var inputtxt = seleted.length > 0 ? seleted[0][options.valueField]: "";
            					input.val(inputtxt);
            				}else{
            					//console.log(seleted[0]);
            					value = seleted.length > 0 ? seleted[0]: null;
            					input.val(JSON.stringify(value));
            				}
            				notifyEvent({
            					type:"change.gonrin",
            					value : value
            				});
        				}
        				if(options.selectionMode === "multiple"){
        					//textElement.html(JSON.stringify(seleted));
        					textElement.find("ul").empty();
        					var valArray = [];
			            	$.each(seleted, function(key, item){
			            		var txt = item[options.textField];
			            		$(itemTemplate).html(txt).appendTo(textElement.find("ul"));

			            		if(options.valueField){
			            			var val = item[options.valueField];
			            			valArray.push(val);
			            		}else{
			            			valArray.push(item);
			            		}
			            	});
			            	//input.val(JSON.stringify(seleted));
			            	input.val(JSON.stringify(valArray));
			            	value = valArray;
			            	notifyEvent({
            					type:"change.gonrin",
            					value : value
            				});
        				}
            		}
            	});
            }
            /*notifyEvent({
                type: 'show.gonui'
            });*/
            return grexport;
        },
        notifyEvent = function (e) {
            //if ((e.type === 'change.gonrin')  && ((e.value && (e.value === e.oldValue)) || (!e.value && !e.oldValue))) {
            //    return;
            //}
            element.trigger(e);
        },
        hide = function(){
            return grexport;
        },

        toggle = function () {
            /// Shows or hides the widget
            //return (widget.is(':hidden') ? show() : hide());
        	return show();
        },
		attachElementEvents = function () {
        	if(options.onChange){
        		element.bind("change.gonrin", options.context !== null ? $.proxy(options.onChange, options.context ) : options.onChange);
        	}

            /*input.on({
                'change': change,
                'blur': options.debug ? '' : hide,
                'keydown': keydown,
                'keyup': keyup,
                'focus': options.allowInputToggle ? show : ''
            });*/

            /*if (element.is('input')) {
                input.on({
                    'focus': show
                });
            };*/

            if (component) {
                component.on('click', toggle);
                component.on('mousedown', false);
            }

        },
        detachElementEvents = function () {
            /*input.off({
                'change': change,
                'blur': blur,
                'keydown': keydown,
                'keyup': keyup,
                'focus': options.allowInputToggle ? hide : ''
            });*/

            if (element.is('input')) {
                input.off({
                    'focus': show
                });
            }

            if (component) {
                component.off('click', toggle);
                component.off('mousedown', false);
            }
            if(widget){

            }
        },
        getValue = function(){
        	return value;
        },
        clearFilters = function(){
        	options.filters = null;
        	if(widget){
        		var colEl = widget.getCollectionElement();
        		if(colEl){
        			colEl.filter(null);
        		}
        		//widget.filters = null;
        	}
        },
		setFilters = function(filters){
        	options.filters = filters;
        	if(widget){
        		var colEl = widget.getCollectionElement();
        		if(colEl){
        			colEl.filter(options.filters);
        		}
        	}
        },
        getFilters = function(){
        	return options.filters;
        },
        clearValue = function(){
        	value = null;
        	text = null;
        	if(widget){
        		if(widget.selectionMode === "single"){
        			textElement.text("");
        			input.val("");
        		}
        		if(widget.selectionMode === "multiple"){
        			textElement.find("ul").empty();
        			input.val("");
        		}
        	}

        	notifyEvent({
				type:"change.gonrin",
				value : value
			});
        	return;
        };

		/********************************************************************************
        *
        * Public API functions
        * =====================
        ********************************************************************************/
		grexport.disable = function () {
            ///Disables the input element, the component is attached to, by adding a disabled="true" attribute to it.
            ///If the widget was visible before that call it is hidden. Possibly emits dp.hide
            hide();
            if (component && component.hasClass('btn')) {
                component.addClass('disabled');
            }
            if (textElement){
            	textElement.prop('disabled', true);
            }
            input.prop('disabled', true);
            return grexport;
        };
        grexport.getValue = getValue;
        grexport.clearValue = clearValue;
        grexport.setFilters = setFilters;
        grexport.getFilters = getFilters;
        grexport.clearFilters = clearFilters;

		// initializing element and component attributes
        if (element.is('input') ) {
            input = element;
            //value = input.val().length > 0 ? ;

            element.wrap( '');
            var inputGroupSpan = element.parent();
            //inputGroupSpan.css("width", element.outerWidth());
            var componentButton = $('').html('');
            inputGroupSpan.append(componentButton);
            component = componentButton;
            textElement = $('');
            if(options.selectionMode === "multiple"){
            	var selectRender = $(menuTemplate).appendTo(textElement);

            }
            element.before(textElement);
            element.css("display", "none");
        } else {
            throw new Error('Cannot apply to non input element');
        }

    	if (input.is('input'))  {
        	setupWidget();
        	if(!options.placeholder){
        		options.placeholder = input.attr("placeholder");
        	}
        	if(textElement && !!options.placeholder){
        		textElement.attr("placeholder", options.placeholder);
        	}

        };

        attachElementEvents();

		return grexport;
	};

	$.fn.ref = function (options) {

        return this.each(function () {
            var $this = $(this);
            if (!$this.data('gonrin')) {
                // create a private copy of the defaults object
                options = $.extend(true, {}, $.fn.ref.defaults, options);
                $this.data('gonrin', GonrinRef($this, options));
            }
        });
    };

    $.fn.ref.defaults = {
    	context: null,
    	//template: null,
    	//height: null,
    	/*placeholder: null,
    	ignore_readonly: false,*/
    	readonly : false,
    	placeholder: null,
    	selectionMode: "single",
    	selectedItems:[],
    	debug: false,
    	filters: false,
    	textField: null,
        valueField: null,
        dataSource: null,
        //value: null,
        onChange : function(){}
    };
}));<|endoftext|>


<commit_before>// Copyright 2017-2020, University of Colorado Boulder

/**
 * Runs the lint rules on the specified files.
 *
 * @author Sam Reid (PhET Interactive Simulations)
 */

'use strict';

// modules
const _ = require( 'lodash' ); // eslint-disable-line require-statement-match
const { ESLint } = require( 'eslint' ); // eslint-disable-line
const fs = require( 'fs' );
const grunt = require( 'grunt' );
const md5 = require( 'md5' );

// constants
const EXCLUDE_PATTERNS = [ // patterns that have no code that should be linted

  '../babel',
  '../decaf',
  '../eliot',
  '../phet-android-app',
  '../phet-info',
  '../phet-io-client-guides',
  '../phet-io-wrapper-arithmetic',
  '../phet-io-wrapper-hookes-law-energy',
  '../phet-ios-app',
  '../smithers',
  '../tasks'
];

/**
 * Lints the specified repositories.
 * @public
 *
 * @returns {Promise} - results from linting files, see ESLint.lintFiles
 */
const lint = async ( patterns, options ) => {

  options = _.assignIn( {
    cache: true,
    format: false, // Use a separate set of rules purely for formatting code.
    fix: false, // whether fixes should be written to disk
    warn: true // whether errors should reported with grunt.warn
  }, options );

  // filter out all unlintable pattern. An unlintable repo is one that has no `js` in it, so it will fail when trying to
  // lint it.  Also, if the user doesn't have some repos checked out, those should be skipped
  patterns = patterns.filter( pattern => !EXCLUDE_PATTERNS.includes( pattern ) &&
                                         fs.existsSync( pattern ) );

  // 1. Create an instance with the `fix` option.
  const eslintConfig = {

    // optional auto-fix
    fix: options.fix,

    // 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: options.cache,

    // Where to store the target-specific cache file
    cacheLocation: `../chipper/eslint/cache/${md5( patterns.join( ',' ) )}.eslintcache`,

    ignorePath: '../chipper/eslint/.eslintignore',

    resolvePluginsRelativeTo: '../chipper/',

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

  if ( options.format ) {
    eslintConfig.baseConfig = {
      extends: [ '../chipper/eslint/format_eslintrc.js' ]
    };
  }

  const eslint = new ESLint( eslintConfig );

  grunt.verbose.writeln( `linting: ${patterns.join( ', ' )}` );

  // 2. Lint files. This doesn't modify target files.
  const results = await eslint.lintFiles( patterns );

  // 3. Modify the files with the fixed code.
  if ( options.fix ) {
    await ESLint.outputFixes( results );
  }

  // 4. Format the results.
  const formatter = await eslint.loadFormatter( 'stylish' );
  const resultText = formatter.format( results );

  const totalWarnings = _.sum( results.map( result => result.warningCount ) );
  const totalErrors = _.sum( results.map( result => result.errorCount ) );

  const total = totalWarnings + totalErrors;

  // 5. Output it.
  if ( total > 0 ) {
    console.log( resultText );
    options.warn && grunt.fail.warn( `${totalErrors} errors and ${totalWarnings} warnings` );
  }

  return results;
};

// Mark the version so that the pre-commit hook will only try to use the promise-based API, this means
// it won't run lint precommit hook on SHAs before the promise-based API
lint.chipperAPIVersion = 'promises1';

module.exports = lint;<commit_msg>Fix --format option docstring in grunt's lint.js, https://github.com/phetsims/phet-info/issues/150<commit_after>// Copyright 2017-2020, University of Colorado Boulder

/**
 * Runs the lint rules on the specified files.
 *
 * @author Sam Reid (PhET Interactive Simulations)
 */

'use strict';

// modules
const _ = require( 'lodash' ); // eslint-disable-line require-statement-match
const { ESLint } = require( 'eslint' ); // eslint-disable-line
const fs = require( 'fs' );
const grunt = require( 'grunt' );
const md5 = require( 'md5' );

// constants
const EXCLUDE_PATTERNS = [ // patterns that have no code that should be linted

  '../babel',
  '../decaf',
  '../eliot',
  '../phet-android-app',
  '../phet-info',
  '../phet-io-client-guides',
  '../phet-io-wrapper-arithmetic',
  '../phet-io-wrapper-hookes-law-energy',
  '../phet-ios-app',
  '../smithers',
  '../tasks'
];

/**
 * Lints the specified repositories.
 * @public
 *
 * @returns {Promise} - results from linting files, see ESLint.lintFiles
 */
const lint = async ( patterns, options ) => {

  options = _.assignIn( {
    cache: true,
    format: false, // append an extra set of rules for formatting code.
    fix: false, // whether fixes should be written to disk
    warn: true // whether errors should reported with grunt.warn
  }, options );

  // filter out all unlintable pattern. An unlintable repo is one that has no `js` in it, so it will fail when trying to
  // lint it.  Also, if the user doesn't have some repos checked out, those should be skipped
  patterns = patterns.filter( pattern => !EXCLUDE_PATTERNS.includes( pattern ) &&
                                         fs.existsSync( pattern ) );

  // 1. Create an instance with the `fix` option.
  const eslintConfig = {

    // optional auto-fix
    fix: options.fix,

    // 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: options.cache,

    // Where to store the target-specific cache file
    cacheLocation: `../chipper/eslint/cache/${md5( patterns.join( ',' ) )}.eslintcache`,

    ignorePath: '../chipper/eslint/.eslintignore',

    resolvePluginsRelativeTo: '../chipper/',

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

  if ( options.format ) {
    eslintConfig.baseConfig = {
      extends: [ '../chipper/eslint/format_eslintrc.js' ]
    };
  }

  const eslint = new ESLint( eslintConfig );

  grunt.verbose.writeln( `linting: ${patterns.join( ', ' )}` );

  // 2. Lint files. This doesn't modify target files.
  const results = await eslint.lintFiles( patterns );

  // 3. Modify the files with the fixed code.
  if ( options.fix ) {
    await ESLint.outputFixes( results );
  }

  // 4. Format the results.
  const formatter = await eslint.loadFormatter( 'stylish' );
  const resultText = formatter.format( results );

  const totalWarnings = _.sum( results.map( result => result.warningCount ) );
  const totalErrors = _.sum( results.map( result => result.errorCount ) );

  const total = totalWarnings + totalErrors;

  // 5. Output it.
  if ( total > 0 ) {
    console.log( resultText );
    options.warn && grunt.fail.warn( `${totalErrors} errors and ${totalWarnings} warnings` );
  }

  return results;
};

// Mark the version so that the pre-commit hook will only try to use the promise-based API, this means
// it won't run lint precommit hook on SHAs before the promise-based API
lint.chipperAPIVersion = 'promises1';

module.exports = lint;<|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 assert = require( 'assert' );
var eslint = require( 'eslint' );

// 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: [
      '**/.git',
      '**/build',
      '**/node_modules',
      '**/snapshots',
      '../sherpa/**',
      '**/js/parser/svgPath.js',
      '**/templates/sim-config.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',
      '../installer-builder/temp/**'
    ]
  } );

  // 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>Formatting fix<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 assert = require( 'assert' );
var eslint = require( 'eslint' );

// 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: [
      '**/.git',
      '**/build',
      '**/node_modules',
      '**/snapshots',
      '../sherpa/**',
      '**/js/parser/svgPath.js',
      '**/templates/sim-config.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',
      '../installer-builder/temp/**'
    ]
  } );

  // 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>define(["js/html/HtmlElement", "underscore"], function (HtmlElement, _) {
    var radioNameCache = {},
        undefined;

    return HtmlElement.inherit("js.html.Input", {

        $classAttributes: ['updateOnEvent', 'checked'],

        defaults: {
            /***
             * the type of the input element
             * @type String
             */
            type: 'text',

            /***
             * the checked state for radio buttons and checkboxes
             * @type Boolean
             */
            checked: false,

            /***
             * the event on which the bound value will be updated
             * @string String
             */
            updateOnEvent: 'input'
        },

        _commitChangedAttributes: function (attributes) {
            if (this.$.type === 'radio') {

                if (attributes.name) {

                    if (this.$previousAttributes.name && radioNameCache[this.$previousAttributes.name]) {
                        delete radioNameCache[this.$previousAttributes.name][this.$cid];
                    }

                    radioNameCache[attributes.name] = radioNameCache[attributes.name] || {};
                    radioNameCache[attributes.name][this.$cid] = this;
                }

            }
            this.callBase();
        },

        _renderEnabled: function (enabled) {
            if (enabled) {
                this.$el.removeAttribute("disabled");
            } else {
                this.$el.setAttribute("disabled", "disabled");
            }
        },

        _supportsPlaceholder: function () {
            return "placeHolder" in this.$el || "placeholder" in this.$el;
        },

        _renderValue: function (value) {
            if (value === null || value === undefined) {
                value = "";
            }

            if (value == "" && !this._supportsPlaceholder() && this.$.placeholder && !this.$.focused) {
                value = this.$.placeholder;

            }

            if (String(value) !== this.$el.value) {
                if (this.$.type === "date") {
                    if (value instanceof Date) {
                        value = value.toLocaleString();
                    }
                }

                this.$el.value = value;
            }
        },

        _commitChecked: function (checked) {
            // sync shadow dom
            if (checked && this.$.type === "radio") {
                var cache = radioNameCache[this.$.name];
                for (var id in cache) {
                    if (cache.hasOwnProperty(id)) {
                        if (cache[id] !== this) {
                            cache[id].set('checked', false);
                        }
                    }
                }
            }
        },

        _renderChecked: function (checked) {
            this.$el.checked = checked ? "checked" : false;
        },

        _transformValue: function (value) {
            if (this.$.type === "number") {
                if (value === "") {
                    return null;
                }
                value = parseInt(value, 10);
                if (isNaN(value)) {
                    value = this.$.value;
                }
            } else if (this.$.type === "date") {
                try {
                    value = value !== "" ? new Date(value) : null;
                } catch (e) {
                    this.log("Invalid Date", "warn");
                    value = this.$.value;
                }
            }

            return value;
        },

        _bindDomEvents: function () {

            var self = this;
            if (_.include(["text", "password", "date", "number"], this.$.type)) {
                if (this.$.type === "date" || this.$.type === "number") {
                    this.$.updateOnEvent = "change";
                }
                // fix for IE
                if (this.$.updateOnEvent === "input" && "onpropertychange" in this.$el) {
                    this.bindDomEvent("keyup", function (e) {
                        self.set('value', self._transformValue(self.$el.value));
                    });
                } else {
                    this.bindDomEvent(this.$.updateOnEvent, function (e) {
                        self.set('value', self._transformValue(self.$el.value));
                    });
                }

            } else if (this.$.type === "checkbox" || this.$.type === "radio") {
                this.bindDomEvent('click', function (e) {
                    self.set('checked', self.$el.checked);
                });
            }

            this.callBase();
        },
        _renderPlaceholder: function (placeholder) {
            // shim for placeholder
            if (!this._supportsPlaceholder()) {
                var self = this;
                if (!this.__blurHandler) {
                    this.__blurHandler = function (e) {
                        self.set('focused', false);
                        if (self.$el.value != "") {
                            return;
                        }
                        self.$el.value = self.$.placeholder || "";
                        self.addClass('placeholder');
                    };
                    this.bindDomEvent('blur', this.__blurHandler);
                }
                if (!this.__focusHandler) {
                    this.__focusHandler = function () {
                        self.set('focused', true);
                        self.removeClass('placeholder');
                        self.$el.value = '';

                    };
                    this.bindDomEvent("focus", this.__focusHandler);
                }
                if (placeholder) {
                    this.addClass('placeholder');
                }
            } else {
                this._setAttribute("placeHolder", placeholder);
            }
        }
    });
});<commit_msg>fixed input value rendering for browsers that don't support placeholders<commit_after>define(["js/html/HtmlElement", "underscore"], function (HtmlElement, _) {
    var radioNameCache = {},
        undefined;

    return HtmlElement.inherit("js.html.Input", {

        $classAttributes: ['updateOnEvent', 'checked'],

        defaults: {
            /***
             * the type of the input element
             * @type String
             */
            type: 'text',

            /***
             * the checked state for radio buttons and checkboxes
             * @type Boolean
             */
            checked: false,

            /***
             * the event on which the bound value will be updated
             * @string String
             */
            updateOnEvent: 'input'
        },

        _commitChangedAttributes: function (attributes) {
            if (this.$.type === 'radio') {

                if (attributes.name) {

                    if (this.$previousAttributes.name && radioNameCache[this.$previousAttributes.name]) {
                        delete radioNameCache[this.$previousAttributes.name][this.$cid];
                    }

                    radioNameCache[attributes.name] = radioNameCache[attributes.name] || {};
                    radioNameCache[attributes.name][this.$cid] = this;
                }

            }
            this.callBase();
        },

        _renderEnabled: function (enabled) {
            if (enabled) {
                this.$el.removeAttribute("disabled");
            } else {
                this.$el.setAttribute("disabled", "disabled");
            }
        },

        _supportsPlaceholder: function () {
            return "placeHolder" in this.$el || "placeholder" in this.$el;
        },

        _renderValue: function (value) {
            if (value === null || value === undefined) {
                value = "";
            }

            if (value == "" && !this._supportsPlaceholder() && this.$.placeholder && !this.$.focused) {
                value = this.$.placeholder;

            }

            if (String(value) !== this.$el.value) {
                if (this.$.type === "date") {
                    if (value instanceof Date) {
                        value = value.toLocaleString();
                    }
                }

                this.$el.value = value;
            }
        },

        _commitChecked: function (checked) {
            // sync shadow dom
            if (checked && this.$.type === "radio") {
                var cache = radioNameCache[this.$.name];
                for (var id in cache) {
                    if (cache.hasOwnProperty(id)) {
                        if (cache[id] !== this) {
                            cache[id].set('checked', false);
                        }
                    }
                }
            }
        },

        _renderChecked: function (checked) {
            this.$el.checked = checked ? "checked" : false;
        },

        _transformValue: function (value) {
            if (this.$.type === "number") {
                if (value === "") {
                    return null;
                }
                value = parseInt(value, 10);
                if (isNaN(value)) {
                    value = this.$.value;
                }
            } else if (this.$.type === "date") {
                try {
                    value = value !== "" ? new Date(value) : null;
                } catch (e) {
                    this.log("Invalid Date", "warn");
                    value = this.$.value;
                }
            }

            return value;
        },

        _bindDomEvents: function () {

            var self = this;
            if (_.include(["text", "password", "date", "number"], this.$.type)) {
                if (this.$.type === "date" || this.$.type === "number") {
                    this.$.updateOnEvent = "change";
                }
                // fix for IE
                if (this.$.updateOnEvent === "input" && "onpropertychange" in this.$el) {
                    this.bindDomEvent("keyup", function (e) {
                        self.set('value', self._transformValue(self.$el.value));
                    });
                } else {
                    this.bindDomEvent(this.$.updateOnEvent, function (e) {
                        self.set('value', self._transformValue(self.$el.value));
                    });
                }

            } else if (this.$.type === "checkbox" || this.$.type === "radio") {
                this.bindDomEvent('click', function (e) {
                    self.set('checked', self.$el.checked);
                });
            }

            this.callBase();
        },
        _renderPlaceholder: function (placeholder) {
            // shim for placeholder
            if (!this._supportsPlaceholder()) {
                var self = this;
                if (!this.__blurHandler) {
                    this.__blurHandler = function (e) {
                        self.set('focused', false);
                        if (self.$el.value != "") {
                            return;
                        }
                        self.$el.value = self.$.placeholder || "";
                        self.addClass('placeholder');
                    };
                    this.bindDomEvent('blur', this.__blurHandler);
                }
                if (!this.__focusHandler) {
                    this.__focusHandler = function () {
                        self.set('focused', true);
                        self.removeClass('placeholder');
                        if (!self.$.value) {
                            self.$el.value = '';
                        }

                    };
                    this.bindDomEvent("focus", this.__focusHandler);
                }
                if (placeholder) {
                    this.addClass('placeholder');
                }
            } else {
                this._setAttribute("placeHolder", placeholder);
            }
        }
    });
});<|endoftext|>


<commit_before>iD.ui.Save = function(context) {
    var map = context.map(),
        history = context.history(),
        connection = context.connection(),
        key = iD.ui.cmd('⌘S'),
        modal;

    function save() {
        d3.event.preventDefault();

        if (!history.hasChanges()) return;

        connection.authenticate(function(err) {
            modal = iD.ui.modal(context.container());
            var changes = history.changes();
            changes.connection = connection;
            modal.select('.content')
                .classed('commit-modal', true)
                .datum(changes)
                .call(iD.ui.Commit(context)
                    .on('cancel', function() {
                        modal.remove();
                    })
                    .on('fix', clickFix)
                    .on('save', commit));
        });
    }

    function commit(e) {
        context.container().select('.shaded')
            .remove();

        var loading = iD.ui.loading(context.container(), t('save.uploading'), true);

        connection.putChangeset(
            history.changes(),
            e.comment,
            history.imagery_used(),
            function(err, changeset_id) {
                loading.remove();
                history.reset();
                map.flush().redraw();
                if (err) {
                    var desc = iD.ui.confirm()
                        .select('.description');
                    desc.append('h2')
                        .text(t('save.error'));
                    desc.append('p').text(err.responseText);
                } else {
                    success(e, changeset_id);
                }
            });
    }

    function success(e, changeset_id) {
        modal = iD.ui.modal(context.container());
        modal.select('.content')
            .classed('success-modal', true)
            .datum({
                id: changeset_id,
                comment: e.comment
            })
            .call(iD.ui.Success(connection)
                .on('cancel', function() {
                    modal.remove();
                }));
    }

    function clickFix(d) {
        var extent = d.entity.extent(context.graph());
        map.centerZoom(extent.center(), Math.min(19, map.extentZoom(extent)));
        context.enter(iD.modes.Select(context, [d.entity.id]));
        modal.remove();
    }

    return function(selection) {
        var button = selection.append('button')
            .attr('class', 'save col12 disabled')
            .attr('tabindex', -1)
            .on('click', save)
            .call(bootstrap.tooltip()
                .placement('bottom')
                .html(true)
                .title(iD.ui.tooltipHtml(t('save.help'), key)));

        button.append('span')
            .attr('class', 'label')
            .text(t('save.title'));

        button.append('span')
            .attr('class', 'count');

        var keybinding = d3.keybinding('undo-redo')
            .on(key, save);

        d3.select(document)
            .call(keybinding);

        context.history().on('change.save', function() {
            var hasChanges = history.hasChanges();

            button
                .classed('disabled', !hasChanges)
                .classed('has-count', hasChanges);

            button.select('span.count')
                .text(history.numChanges());
        });
    };
};
<commit_msg>Fix save error causing modal to break (#790)<commit_after>iD.ui.Save = function(context) {
    var map = context.map(),
        history = context.history(),
        connection = context.connection(),
        key = iD.ui.cmd('⌘S'),
        modal;

    function save() {
        d3.event.preventDefault();

        if (!history.hasChanges()) return;

        connection.authenticate(function(err) {
            modal = iD.ui.modal(context.container());
            var changes = history.changes();
            changes.connection = connection;
            modal.select('.content')
                .classed('commit-modal', true)
                .datum(changes)
                .call(iD.ui.Commit(context)
                    .on('cancel', function() {
                        modal.remove();
                    })
                    .on('fix', clickFix)
                    .on('save', commit));
        });
    }

    function commit(e) {
        context.container().select('.shaded')
            .remove();

        var loading = iD.ui.loading(context.container(), t('save.uploading'), true);

        connection.putChangeset(
            history.changes(),
            e.comment,
            history.imagery_used(),
            function(err, changeset_id) {
                loading.remove();
                history.reset();
                map.flush().redraw();
                if (err) {
                    var desc = iD.ui.confirm(context.container())
                        .select('.description');
                    desc.append('h2')
                        .text(t('save.error'));
                    desc.append('p').text(err.responseText);
                } else {
                    success(e, changeset_id);
                }
            });
    }

    function success(e, changeset_id) {
        modal = iD.ui.modal(context.container());
        modal.select('.content')
            .classed('success-modal', true)
            .datum({
                id: changeset_id,
                comment: e.comment
            })
            .call(iD.ui.Success(connection)
                .on('cancel', function() {
                    modal.remove();
                }));
    }

    function clickFix(d) {
        var extent = d.entity.extent(context.graph());
        map.centerZoom(extent.center(), Math.min(19, map.extentZoom(extent)));
        context.enter(iD.modes.Select(context, [d.entity.id]));
        modal.remove();
    }

    return function(selection) {
        var button = selection.append('button')
            .attr('class', 'save col12 disabled')
            .attr('tabindex', -1)
            .on('click', save)
            .call(bootstrap.tooltip()
                .placement('bottom')
                .html(true)
                .title(iD.ui.tooltipHtml(t('save.help'), key)));

        button.append('span')
            .attr('class', 'label')
            .text(t('save.title'));

        button.append('span')
            .attr('class', 'count');

        var keybinding = d3.keybinding('undo-redo')
            .on(key, save);

        d3.select(document)
            .call(keybinding);

        context.history().on('change.save', function() {
            var hasChanges = history.hasChanges();

            button
                .classed('disabled', !hasChanges)
                .classed('has-count', hasChanges);

            button.select('span.count')
                .text(history.numChanges());
        });
    };
};
<|endoftext|>