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

var color = d3.scale.category20();

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

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

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

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

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

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

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

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

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

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

    var fill = d3.scale.ordinal()
        .domain([graphMin, graphMax])
        .range(["#DB704D", "#D2D0C6", "#ECD08D", "#F8EDD3"]);

    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); })
        .call(force.drag)
        .on('dblclick', connectedNodes);

    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; });
    });
  }
  //Toggle stores whether the highlighting is on
  var toggle = 0;

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

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

  function connectedNodes() {

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

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

        //Reduce the op

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

}

});

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

var color = d3.scale.category20();

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

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

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

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

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

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

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

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

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

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

    var fill = d3.scale.ordinal()
        .domain([graphMin, graphMax])
        .range(["#DB704D", "#D2D0C6", "#ECD08D", "#F8EDD3"]);

    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); })
        .call(force.drag)
        .on('dblclick', connectedNodes);

    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; });

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

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

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

  function connectedNodes() {

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

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

        //Reduce the op

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

}
    });
  }

});

<|endoftext|>


<commit_before>function loadUserData(config){
	var data, url, xmlHttp;

	//VARS from config
	var callback = config.customCallback;

	url = 'https://api.jh0.eu/swarm?fetch=user';
    xmlHttp = new XMLHttpRequest();
	xmlHttp.setRequestHeader('Access-Control-Allow-Origin', '*');
	xmlHttp.setRequestHeader('Access-Control-Allow-Methods', 'GET');
    xmlHttp.onreadystatechange = function(data) {
    	if(xmlHttp.readyState == 4 && xmlHttp.status == 200){

			var answer = JSON.parse(xmlHttp.responseText)
    		var niceAnswer = answer[0];
    		callback(niceAnswer);

    	}
  	}

  	xmlHttp.open("GET", url, true);
    xmlHttp.send();
}

function loadCheckins(config){
	var data, url, xmlHttp;

	//VARS from config
	var count = config.count;
	var callback = config.customCallback;
	//Setup config.ignore with help of these references: https://developer.foursquare.com/categorytree

	var vague = false;

	if(count > 0 && count < 50){
		url = 'https://api.jh0.eu/swarm?fetch=checkins&count=' + count;
	    xmlHttp = new XMLHttpRequest();
		xmlHttp.setRequestHeader('Access-Control-Allow-Origin', '*');
		xmlHttp.setRequestHeader('Access-Control-Allow-Methods', 'GET');
	    xmlHttp.onreadystatechange = function(data) {
	    	if(xmlHttp.readyState == 4 && xmlHttp.status == 200){

	    		var answer = JSON.parse(xmlHttp.responseText)
	    		var niceAnswer = answer[0];

				if(typeof config.ignore === 'object'){
					for(var i = config.ignore.length - 1; i >= 0; i--) {
						var ignoreListItem = config.ignore[i];
						for(var i = niceAnswer.venue.categories.length - 1; i >= 0; i--) {
							var categoryItem = niceAnswer.venue.categories[i].name;
							if(ignoreListItem == categoryItem){
								vague = true;
							}
						}
					}
				}

    			if(vague){
					var checkin = {
						"venue": {
							"name": niceAnswer.venue.location.city,
							"location": {
								"neighborhood": '',
								"city": '',
								"cc": niceAnswer.venue.location.cc,
								"country": niceAnswer.venue.location.country,
								"state": niceAnswer.venue.location.state,
							},
							"categories": niceAnswer.venue.categories
						}
					}
				}else{
					var checkin = {
						"venue": {
							"name": niceAnswer.venue.name,
							"location": {
								"neighborhood": niceAnswer.venue.location.neighborhood,
								"city": niceAnswer.venue.location.city,
								"cc": niceAnswer.venue.location.cc,
								"country": niceAnswer.venue.location.country,
								"state": niceAnswer.venue.location.state,
							},
							"categories": niceAnswer.venue.categories
						}
					}
				}

	    		callback(checkin);
	    	}
	  	}
	}

    xmlHttp.open("GET", url, true);
    xmlHttp.send();
}
<commit_msg>trying to make cors work. attempt 2<commit_after>function loadUserData(config){
	var data, url, xmlHttp;

	//VARS from config
	var callback = config.customCallback;

	url = 'https://api.jh0.eu/swarm?fetch=user';
   	xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function(data) {
    	if(xmlHttp.readyState == 4 && xmlHttp.status == 200){

			var answer = JSON.parse(xmlHttp.responseText)
    		var niceAnswer = answer[0];
    		callback(niceAnswer);

    	}
  	}

  	xmlHttp.open("GET", url, true);
    xmlHttp.send();
}

function loadCheckins(config){
	var data, url, xmlHttp;

	//VARS from config
	var count = config.count;
	var callback = config.customCallback;
	//Setup config.ignore with help of these references: https://developer.foursquare.com/categorytree

	var vague = false;

	if(count > 0 && count < 50){
		url = 'https://api.jh0.eu/swarm?fetch=checkins&count=' + count;
	    xmlHttp = new XMLHttpRequest();
	    xmlHttp.onreadystatechange = function(data) {
	    	if(xmlHttp.readyState == 4 && xmlHttp.status == 200){

	    		var answer = JSON.parse(xmlHttp.responseText)
	    		var niceAnswer = answer[0];

				if(typeof config.ignore === 'object'){
					for(var i = config.ignore.length - 1; i >= 0; i--) {
						var ignoreListItem = config.ignore[i];
						for(var i = niceAnswer.venue.categories.length - 1; i >= 0; i--) {
							var categoryItem = niceAnswer.venue.categories[i].name;
							if(ignoreListItem == categoryItem){
								vague = true;
							}
						}
					}
				}

    			if(vague){
					var checkin = {
						"venue": {
							"name": niceAnswer.venue.location.city,
							"location": {
								"neighborhood": '',
								"city": '',
								"cc": niceAnswer.venue.location.cc,
								"country": niceAnswer.venue.location.country,
								"state": niceAnswer.venue.location.state,
							},
							"categories": niceAnswer.venue.categories
						}
					}
				}else{
					var checkin = {
						"venue": {
							"name": niceAnswer.venue.name,
							"location": {
								"neighborhood": niceAnswer.venue.location.neighborhood,
								"city": niceAnswer.venue.location.city,
								"cc": niceAnswer.venue.location.cc,
								"country": niceAnswer.venue.location.country,
								"state": niceAnswer.venue.location.state,
							},
							"categories": niceAnswer.venue.categories
						}
					}
				}

	    		callback(checkin);
	    	}
	  	}
	}

    xmlHttp.open("GET", url, true);
    xmlHttp.send();
}
<|endoftext|>


<commit_before>(function($) {
//
//$('#gbzw').hide(); // top bar including g+ crap
//$('#gbvg').hide(); // top side g+ personal crap
$('#pmocntr,#pmocntr2').hide().empty(); // chrome promo
$('#fll').css('visibility', 'hidden'); // advertising program
//
})(jQuery);<commit_msg>all styled now - no need for js<commit_after>//(function($) {
//
//$('#gbzw').hide(); // top bar including g+ crap
//$('#gbvg').hide(); // top side g+ personal crap
//$('#pmocntr,#pmocntr2').hide().empty(); // chrome promo
//$('#fll').css('visibility', 'hidden'); // advertising program
//
//})();<|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',
  '../phet-android-app',
  '../phet-info',
  '../phet-io-client-guides',
  '../phet-io-website',
  '../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. Parse the results.
  const totalWarnings = _.sum( results.map( result => result.warningCount ) );
  const totalErrors = _.sum( results.map( result => result.errorCount ) );

  // 5. Output results on errors.
  if ( totalWarnings + totalErrors > 0 ) {
    const formatter = await eslint.loadFormatter( 'stylish' );
    const resultText = formatter.format( results );
    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>update copyright dates from daily grunt work<commit_after>// Copyright 2017-2021, 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',
  '../phet-android-app',
  '../phet-info',
  '../phet-io-client-guides',
  '../phet-io-website',
  '../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. Parse the results.
  const totalWarnings = _.sum( results.map( result => result.warningCount ) );
  const totalErrors = _.sum( results.map( result => result.errorCount ) );

  // 5. Output results on errors.
  if ( totalWarnings + totalErrors > 0 ) {
    const formatter = await eslint.loadFormatter( 'stylish' );
    const resultText = formatter.format( results );
    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 2017-2021, 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',
  '../phet-android-app',
  '../phet-info',
  '../phet-io-client-guides',
  '../phet-io-website',
  '../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. Parse the results.
  const totalWarnings = _.sum( results.map( result => result.warningCount ) );
  const totalErrors = _.sum( results.map( result => result.errorCount ) );

  // 5. Output results on errors.
  if ( totalWarnings + totalErrors > 0 ) {
    const formatter = await eslint.loadFormatter( 'stylish' );
    const resultText = formatter.format( results );
    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>add QA to list of sims that should not be linted<commit_after>// Copyright 2017-2021, 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',
  '../phet-android-app',
  '../phet-info',
  '../phet-io-client-guides',
  '../phet-io-website',
  '../phet-io-wrapper-arithmetic',
  '../phet-io-wrapper-hookes-law-energy',
  '../phet-ios-app',
  '../QA',
  '../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. Parse the results.
  const totalWarnings = _.sum( results.map( result => result.warningCount ) );
  const totalErrors = _.sum( results.map( result => result.errorCount ) );

  // 5. Output results on errors.
  if ( totalWarnings + totalErrors > 0 ) {
    const formatter = await eslint.loadFormatter( 'stylish' );
    const resultText = formatter.format( results );
    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>var map;
var infowindow;
var service;
var userPosition;
var idCounter = 0;
var listArray = new Array();

/*
* Funktion som initiera Google Maps kartan och tar redan
* användarens position med geolocation
*/
function initMap() {
	map = new google.maps.Map(document.getElementById('map'), {
	  center: {lat: 55.5916628, lng: 12.9875187},
	  zoom: 12
	});
	service = new google.maps.places.PlacesService(map);
	infowindow = new google.maps.InfoWindow();
}

$( "#searchBtn" ).click(function() {
	if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
	} else {
        //x.innerHTML = "Geolocation is not supported by this browser.";
    }

});

/*
* Funktion som tar emot användarens position och sätter ut marker
* för användarens position
*/
function showPosition(position) {
    var latlon = {lat:position.coords.latitude, lng: position.coords.longitude};
	console.log(latlon);
	userPosition = latlon;

	var marker = new google.maps.Marker({
		position: userPosition,
		map: map,
		title: 'Hello World!',
		icon: 'http://maps.google.com/mapfiles/ms/icons/blue.png'
	});

	makeSearch(userPosition);
}

/*
* Funktion som gör sökningen av närliggande resturanger från användarens * position
*/
function makeSearch(userPosition){
	var request = {
		location: userPosition,
	  	radius: 500,
	  	type: ['restaurant']
	}
	service.nearbySearch(request, callback);
}

/*
* Funktion som tar emot närliggande resturanger ifrån APIn
*/
function callback(results, status) {
	if (status === google.maps.places.PlacesServiceStatus.OK) {
		for (var i = 0; i < results.length; i++) {
			//createMarker(results[i]);
			$(".test").append('
' + results[i].name + '
');
			listArray.push(results[i]);
			idCounter++;
		}
	}
}

$('.test').on('click', '.selectedH1', function(){
	console.log(this.id);
	console.log(listArray[this.id]);
	var currentId = listArray[this.id];
	createMarker(currentId);
});

/*
* Funktion som sätter ut alla resturanger i kartan och sätter ut en
* ikon för varje resturang
*/

function createMarker(place) {
	var placeLoc = place.geometry.location;
	var marker = new google.maps.Marker({
	  map: map,
	  position: place.geometry.location
	});

	marker.addListener('click', function(){
		    var request = {
                reference: place.reference
            };
            service.getDetails(request, function(details, status) {

              infowindow.setContent([
                details.name,
                details.formatted_address,
                details.website,
                details.rating,
                details.formatted_phone_number].join("
"));
              infowindow.open(map, marker);
            });
	})

	map.setZoom(15);
	map.panTo(marker.position);
	google.maps.event.addListener(marker, 'click', function() {
		infowindow.setContent(place.name);
		infowindow.open(map, this);
	});
}

/*
	console.log("KU");
		    var service = new google.maps.places.PlacesService(map);
	service.getDetails({
        placeId: place.id
    }, function (place, status) {
        if (status === google.maps.places.PlacesServiceStatus.OK) {
            // Loop through opening hours weekday text
            for (var i = 0; i < place.opening_hours.weekday_text.length; i++) {
                console.log(lace.opening_hours.weekday_text[i]);

            }
        }
    });

	var photos = place.photos;
  	if (!photos) {
    	return;
  	}
	//var p1 = userPosition;
	//var p2 = place.geometry.location.lat() + " " + place.geometry.location.lng() ;
	$(".test").append('
' + place.name + '
' +
					 '');

	//console.log((google.maps.geometry.spherical.computeDistanceBetween(p1, p2) / 1000).toFixed(2);
	*/

// ----- DÖLJER ALLT UTOM FÖRSTASIDAN I FÖRSTA LÄGET & VISAR ALLT NÄR MAN TRYCKER PÅ SÖK -----

var searchBtn = document.querySelector("#searchBtn");
searchBtn.addEventListener("click", show);

function show(){
    var menuSection = document.querySelector(".menu");
    var restaurantSection = document.querySelector("#portfolio");
    var mapSection = document.querySelector("#contact");
    var footerSection = document.querySelector("#footer");

    if(menuSection.className && restaurantSection.className && mapSection.className && footerSection.className !== "hide"){
        menuSection.className = "show";
        restaurantSection.className = "show";
        mapSection.className = "show";
        footerSection.className = "show";
        initMap();
    }
}

// ------ SKRIVA UT RESTAURANGER --------

/*$("#title").on("keyup", function(){

	$("#title").show();
	$.ajax({
		url: "http://www.omdbapi.com/?s=" + UserInput + "&y=&plot=short&r=json",
		dataType: "JSON"
    }).done(function(data){
        $("#presentRestaurants").html("");

        try{
            var restaurants = data.Search;   //lista av alla restauranger
            console.log(restaurants);

        for(var i = 0; i < restaurants.length; i++) {
            var name = restaurants[i].Name;   //Varje restaurang

            $("#presentRestaurants").append("
" + place.Name + "
");
        });

*/<commit_msg>revert<commit_after>var map;
var userPosition;
var infowindow;

/*
* Funktion som initiera Google Maps kartan och tar redan
* användarens position med geolocation
*/
function initMap() {
	map = new google.maps.Map(document.getElementById('map'), {
	  center: {lat: 55.5916628, lng: 12.9875187},
	  zoom: 12
	});

	infowindow = new google.maps.InfoWindow();
	if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    } else {
        //x.innerHTML = "Geolocation is not supported by this browser.";
    }
}

/*
* Funktion som tar emot användarens position och sätter ut marker
* för användarens position
*/
function showPosition(position) {
    var latlon = {lat:position.coords.latitude, lng: position.coords.longitude};
	console.log(latlon);
	userPosition = latlon;

	var marker = new google.maps.Marker({
		position: userPosition,
		map: map,
		title: 'Hello World!',
		icon: 'http://maps.google.com/mapfiles/ms/icons/blue.png'
	});

	makeSearch(userPosition);
}

/*
* Funktion som gör sökningen av närliggande resturanger från användarens * position
*/
function makeSearch(userPosition){
	var service = new google.maps.places.PlacesService(map);
	service.nearbySearch ({
	  location: userPosition,
	  radius: 500,
	  type: ['restaurant']
	}, callback);
}

/*
* Funktion som tar emot närliggande resturanger ifrån APIn
*/
function callback(results, status) {
	if (status === google.maps.places.PlacesServiceStatus.OK) {
		for (var i = 0; i < results.length; i++) {
			createMarker(results[i]);
	  	}
	}
}

/*
* Funktion som sätter ut alla resturanger i kartan och sätter ut en
* ikon för varje resturang
*/

function createMarker(place) {
	var placeLoc = place.geometry.location;
	var marker = new google.maps.Marker({
	  map: map,
	  position: place.geometry.location
	});

	map.setZoom(15);
	map.panTo(marker.position);
	google.maps.event.addListener(marker, 'click', function() {
	  infowindow.setContent(place.name);
	  infowindow.open(map, this);
	});
}

	var photos = place.photos;
  	if (!photos) {
    	return;
  	}
	//var p1 = userPosition;
	//var p2 = place.geometry.location.lat() + " " + place.geometry.location.lng() ;
	$(".test").append('
' + place.name + '
' +
					 '');

	//console.log((google.maps.geometry.spherical.computeDistanceBetween(p1, p2) / 1000).toFixed(2);
	*/

// ----- DÖLJER ALLT UTOM FÖRSTASIDAN I FÖRSTA LÄGET & VISAR ALLT NÄR MAN TRYCKER PÅ SÖK -----

var searchBtn = document.querySelector("#searchBtn");
searchBtn.addEventListener("click", show);

function show(){
    var menuSection = document.querySelector(".menu");
    var restaurantSection = document.querySelector("#portfolio");
    var mapSection = document.querySelector("#contact");
    var footerSection = document.querySelector("#footer");

    if(menuSection.className && restaurantSection.className && mapSection.className && footerSection.className !== "hide"){
        menuSection.className = "show";
        restaurantSection.className = "show";
        mapSection.className = "show";
        footerSection.className = "show";
        initMap();
    }
}

// ------ SKRIVA UT RESTAURANGER --------

/*$("#title").on("keyup", function(){

	$("#title").show();
	$.ajax({
		url: "http://www.omdbapi.com/?s=" + UserInput + "&y=&plot=short&r=json",
		dataType: "JSON"
    }).done(function(data){
        $("#presentRestaurants").html("");

        try{
            var restaurants = data.Search;   //lista av alla restauranger
            console.log(restaurants);

        for(var i = 0; i < restaurants.length; i++) {
            var name = restaurants[i].Name;   //Varje restaurang

            $("#presentRestaurants").append("
" + place.Name + "
");
        });

*/<|endoftext|>


<commit_before>(function(win, $) {
    var items = [];
    var $el;
    var init = function() {
        $el = $('div[node-type="apps"]');
        appTodo();
    };
    var appTodo = function() {
        var numobj = $el.find('b[node-type="num"]');
        var partMash=$el.find('div[node-type="sm"]');
        var mask= $('.screen_mask');
        var group = new Group();
        group.callback(function(mistake,index,compound,result){
            if(!mistake){
                numobj.text(result[2]);
                renderNumArea(index,compound,result);
            }else{
                mask.show();
            }
        });

        group.setDefine(function(){
            partMash.hide();
            numobj.text(result[0]);
        });

        var renderNumArea=function(){
            var color='';
            return function(index,compound,result){
                color || (color=getColor());
                partMash.eq(index).show().css('background-color','#'+color);
                if(compound){
                    color=getColor();
                }
            };
        }();

        $el.find('a[node-type="btn-l"]').tap(function() {
            group.left();
            // numobj.text('L');
        })

        $el.find('a[node-type="btn-r"]').tap(function() {
            group.right();
            // numobj.text('R');
        });
        mask.find('a.errbtn').tap(function(){
            group.reset();
        });

    };
    var getColor=function(){
         var colors=["ff9800","e65100","795548","b0120a","c2185b","f57c00","#dd2c00","e91e63"];
         var colorLen=colors.length;
        var index=0;
        return function(){
            var color=colors[index];
            index = (index+1)%colorLen;
            console.log(index)
           return color;
        }
    }();

    var Group = function() {
        this.flag = [0, 0];
        this.result=[0,0,0];
        this._callback=null;
        this.mistake=false;//错误
    };
    $.extend(Group.prototype, {
        init: function() {

        },
        left: function() {
            var flag = this.flag;
            var result=this.result;
            if(this._check(0)){
                flag[0] = 1;
                result[0] = this.result[0]+1;
            }
            this._result(0);
        },
        right: function() {
            var flag = this.flag;
            var result=this.result;
            if(this._check(1)){
                flag[1] = 1;
                result[1] = this.result[1]+1;
            }
            this._result(1);
        },
        _check: function(inx) {
            var val=this.flag[inx];
            var flag;
            if(val>0){
                flag = false;
                this.mistake = true;
            }
            flag = true;
            return flag;
        },
        _result:function(inx){
            var flag=this.flag;
            var result=this.result;
            var compound=false;
            //一对成功
            if(!this.mistake && (flag[0] & flag[1])){
                this.flag=[0,0];
                result[2] = result[2]+1;
                compound=true;
            }
            this._callback(this.mistake,inx,compound,result);
        },
        //flag [true,false]
        callback: function(fn) {
            this._callback = fn;
        },
        reset: function(fn) {
           this.flag = [0, 0];
            this.result=[0,0,0];
            this._callback=null;
            this.mistake=false;//错误
            this._defineFn();
        },
        setDefine:function(fn){
            this._defineFn= fn|| function(){};
        },
        getResult:function(){
            return this.result;
        }
    });

    init();

})(this, $);
<commit_msg>Update index.js<commit_after>(function(win, $) {
    var items = [];
    var $el;
    var init = function() {
        $el = $('div[node-type="apps"]');
        appTodo();
    };
    var appTodo = function() {
        var numobj = $el.find('b[node-type="num"]');
        var partMash=$el.find('div[node-type="sm"]');
        var mask= $('.screen_mask');
        var group = new Group();
        group.callback(function(mistake,index,compound,result){
            if(!mistake){
                numobj.text(result[2]);
                renderNumArea(index,compound,result);
            }else{
                mask.show();
            }
        });

        group.setDefine(function(){
            partMash.hide();
            numobj.text(result[0]);
        });

        var renderNumArea=function(){
            var color='';
            return function(index,compound,result){
                color || (color=getColor());
                partMash.eq(index).show().css('background-color','#'+color);
                if(compound){
                    color=getColor();
                }
            };
        }();

        $el.find('a[node-type="btn-l"]').on('tap',function() {
            group.left();
            // numobj.text('L');
        })

        $el.find('a[node-type="btn-r"]').on('tap',function() {
            group.right();
            // numobj.text('R');
        });
        mask.find('a.errbtn').on('tap',function(){
            group.reset();
        });

    };
    var getColor=function(){
         var colors=["ff9800","e65100","795548","b0120a","c2185b","f57c00","#dd2c00","e91e63"];
         var colorLen=colors.length;
        var index=0;
        return function(){
            var color=colors[index];
            index = (index+1)%colorLen;
            console.log(index)
           return color;
        }
    }();

    var Group = function() {
        this.flag = [0, 0];
        this.result=[0,0,0];
        this._callback=null;
        this.mistake=false;//错误
    };
    $.extend(Group.prototype, {
        init: function() {

        },
        left: function() {
            var flag = this.flag;
            var result=this.result;
            if(this._check(0)){
                flag[0] = 1;
                result[0] = this.result[0]+1;
            }
            this._result(0);
        },
        right: function() {
            var flag = this.flag;
            var result=this.result;
            if(this._check(1)){
                flag[1] = 1;
                result[1] = this.result[1]+1;
            }
            this._result(1);
        },
        _check: function(inx) {
            var val=this.flag[inx];
            var flag;
            if(val>0){
                flag = false;
                this.mistake = true;
            }
            flag = true;
            return flag;
        },
        _result:function(inx){
            var flag=this.flag;
            var result=this.result;
            var compound=false;
            //一对成功
            if(!this.mistake && (flag[0] & flag[1])){
                this.flag=[0,0];
                result[2] = result[2]+1;
                compound=true;
            }
            this._callback(this.mistake,inx,compound,result);
        },
        //flag [true,false]
        callback: function(fn) {
            this._callback = fn;
        },
        reset: function(fn) {
           this.flag = [0, 0];
            this.result=[0,0,0];
            this._callback=null;
            this.mistake=false;//错误
            this._defineFn();
        },
        setDefine:function(fn){
            this._defineFn= fn|| function(){};
        },
        getResult:function(){
            return this.result;
        }
    });

    init();

})(this, $);
<|endoftext|>


<commit_before>
(function ($){
  var app = $.app;
  var IMG_WIDTH = 100;

  function mainColumn () {}

  function showSearchResults() {
    $('#shelf', '#search_column').hide();
    $('#search_results', '#search_column').empty();
    $('#search_results', '#search_column').show();
  }

  function showShelf() {
    $('#shelf', '#search_column').show();
    $('#search_results', '#search_column').hide();
  }

  function populateShelf(url, artist, album){
    var shelf = $('#shelf', '#search_column');
    var artworkNum = Math.floor(shelf.width()/IMG_WIDTH);
    var margin = (shelf.width()-(artworkNum*IMG_WIDTH))/(artworkNum*2);
    var artwork = $('')
      .attr('src', url)
      .data('meta', { album : album, artist : artist })
      .css('margin', Math.floor(margin)-1)
      .fadeIn()
      .click(function () {
        showSearchResults();
        populateSearchResults($(this).data('meta').album);
        $('input[name=search]').val($(this).data('meta').album);
      });
    $('#shelf', '#search_column').append(artwork);
    app.artworks[url] = { album : album, artist : artist };
  }

  function populateSearchResults(query) {
    var results = $.app.Storage.search(query);
    _(results).each(function (muFile) {
      $('#search_results', '#search_column')
        .append($.app.utils.getSongEntryHTML(muFile, true));
    });

    $('#search_results', '#search_column').find('.entry_action')
      .click(function () {
        var muFile = $(this).data('muFile');
        var player_entry = $.app.utils.getSongEntryHTML(muFile, false);
        $.app.Playlist.attachEntryControls(player_entry);
        $.app.Playlist.add(player_entry)
      });
  }

  function init() {
    /*if(_.isNull(window.localStorage.getItem('__name_index__'))){}
    else { } */
    app.artworks = {};
    showShelf();
    loadArtworkMap();
    _.each(app.artworks, function (artwork, key){
      populateShelf(key, artwork.artist, artwork.album);
    });

    $('input[name=search]').keyup(function (e) {

      var text = $(this).val();

      if(!text || (text && text.length < 4)) { return; }
      showSearchResults();
      populateSearchResults(text);

    })
    .focus(function (e){
      $(this).val('');
      showSearchResults();
    })
    .focusout(function (e){
      if($(this).val() == ''){
        $(this).val('Search...');
        showShelf();
      }
    });
  }

  function storeArtworkMap() {
    window.localStorage.setItem(
      '__artwork_map__', JSON.stringify(app.artworks));
  }

  function loadArtworkMap() {
    app.artworks = JSON.parse(window.localStorage.getItem('__artwork_map__'));
  }

  app.mainColumn = mainColumn;
  app.mainColumn.init = init;
  app.mainColumn.storeArtworkMap = storeArtworkMap;
  app.mainColumn.loadArtworkMap = loadArtworkMap;
  app.mainColumn.populateShelf = populateShelf;

})(jQuery);
<commit_msg>no text box clear on focusout<commit_after>
(function ($){
  var app = $.app;
  var IMG_WIDTH = 100;

  function mainColumn () {}

  function showSearchResults() {
    $('#shelf', '#search_column').hide();
    $('#search_results', '#search_column').empty();
    $('#search_results', '#search_column').show();
  }

  function showShelf() {
    $('#shelf', '#search_column').show();
    $('#search_results', '#search_column').hide();
  }

  function populateShelf(url, artist, album){
    var shelf = $('#shelf', '#search_column');
    var artworkNum = Math.floor(shelf.width()/IMG_WIDTH);
    var margin = (shelf.width()-(artworkNum*IMG_WIDTH))/(artworkNum*2);
    var artwork = $('')
      .attr('src', url)
      .data('meta', { album : album, artist : artist })
      .css('margin', Math.floor(margin)-1)
      .fadeIn()
      .click(function () {
        showSearchResults();
        populateSearchResults($(this).data('meta').album);
        $('input[name=search]').val($(this).data('meta').album);
      });
    $('#shelf', '#search_column').append(artwork);
    app.artworks[url] = { album : album, artist : artist };
  }

  function populateSearchResults(query) {
    var results = $.app.Storage.search(query);
    _(results).each(function (muFile) {
      $('#search_results', '#search_column')
        .append($.app.utils.getSongEntryHTML(muFile, true));
    });

    $('#search_results', '#search_column').find('.entry_action')
      .click(function () {
        var muFile = $(this).data('muFile');
        var player_entry = $.app.utils.getSongEntryHTML(muFile, false);
        $.app.Playlist.attachEntryControls(player_entry);
        $.app.Playlist.add(player_entry)
      });
  }

  function init() {
    /*if(_.isNull(window.localStorage.getItem('__name_index__'))){}
    else { } */
    app.artworks = {};
    showShelf();
    loadArtworkMap();
    _.each(app.artworks, function (artwork, key){
      populateShelf(key, artwork.artist, artwork.album);
    });

    $('input[name=search]').keyup(function (e) {

      var text = $(this).val();

      if(!text || (text && text.length < 4)) {
        showShelf();
        return;
      }
      showSearchResults();
      populateSearchResults(text);

    })
    .focusout(function (e){
      if($(this).val() == ''){
        $(this).val('Search...');
        showShelf();
      }
    });
  }

  function storeArtworkMap() {
    window.localStorage.setItem(
      '__artwork_map__', JSON.stringify(app.artworks));
  }

  function loadArtworkMap() {
    app.artworks = JSON.parse(window.localStorage.getItem('__artwork_map__'));
  }

  app.mainColumn = mainColumn;
  app.mainColumn.init = init;
  app.mainColumn.storeArtworkMap = storeArtworkMap;
  app.mainColumn.loadArtworkMap = loadArtworkMap;
  app.mainColumn.populateShelf = populateShelf;

})(jQuery);
<|endoftext|>


<commit_before>// Auto-create new intput-groups
$(".js-lists").on("focus", ".disabled", function () {
	var disabledRow = $(".input-group.disabled");
	var newInputGroup = disabledRow.clone()[0];
	disabledRow.removeClass("disabled").addClass("js-create-on-keypress");
	$(".js-lists").one("keypress", ".js-create-on-keypress", function () {
		$(".js-create-on-keypress")
			.removeClass("js-create-on-keypress")
			.after(newInputGroup);
	});
});

$(".js-lists").on("keyup", recountTotals);
$(".js-lists").on("blur", recountTotals);

// Count the non-blank inputs in each column
function recountTotals () {
	$(".js-listcount").each(function (index, element) {
		var count = 0;
		$("input", $(".js-list").get(index)).each(function (i, el) {
			if (el.value) {
				++count;
			}
		})
		$(element).text(count);
	})
}
<commit_msg>Second half of Operation Sensible Reordering.<commit_after>// Auto-create new intput-groups
$(".js-lists").on("focus", ".disabled", function () {
	var disabledRow = $(".input-group.disabled");
	var newInputGroup = disabledRow.clone()[0];
	disabledRow.removeClass("disabled").addClass("js-create-on-keypress");
	$(".js-lists").one("keypress", ".js-create-on-keypress", function () {
		$(".js-create-on-keypress")
			.removeClass("js-create-on-keypress");
		$(".js-list > div:last-child")
			.after(newInputGroup);
	});
});

$(".js-lists").on("keyup", recountTotals);
$(".js-lists").on("blur", recountTotals);

// Count the non-blank inputs in each column
function recountTotals () {
	$(".js-listcount").each(function (index, element) {
		var count = 0;
		$("input", $(".js-list").get(index)).each(function (i, el) {
			if (el.value) {
				++count;
			}
		})
		$(element).text(count);
	})
}
<|endoftext|>


<commit_before>/**
 * all URLs used in the openrouteservice
 */

/**
 * namespaces and schemata e.g. for XML requests to services
 */
namespaces = {
	xls : 'http://www.opengis.net/xls',
	sch : 'http://www.ascc.net/xml/schematron',
	gml : 'http://www.opengis.net/gml',
	wps : 'http://www.opengis.net/wps/1.0.0',
	ows : 'http://www.opengis.net/ows/1.1',
	xlink : 'http://www.w3.org/1999/xlink',
	xsi : 'http://www.w3.org/2001/XMLSchema-instance',
	ascc : 'http://www.ascc.net/xml/schematron',
	aas : 'http://www.geoinform.fh-mainz.de/aas'
};
namespaces.schemata = {
	directoryService : 'http://www.opengis.net/xls http://schemas.opengis.net/ols/1.1.0/DirectoryService.xsd',
	analyseService : 'http://www.geoinform.fh-mainz.de/aas',
	gatewayService : 'http://www.opengis.net/xls http://schemas.opengis.net/ols/1.1.0/GatewayService.xsd',
	locationUtilityService : 'http://www.opengis.net/xls http://schemas.opengis.net/ols/1.1.0/LocationUtilityService.xsd',
	presentationService : 'http://www.opengis.net/xls http://schemas.opengis.net/ols/1.1.0/PresentationService.xsd',
	routeService : 'http://www.opengis.net/xls http://schemas.opengis.net/ols/1.1.0/RouteService.xsd',
	wpsService : 'http://www.opengis.net/xls http://schemas.opengis.net/wps/1.0.0/wpsExecute_request.xsd',
	lineStringService : 'http://www.opengis.net/gml http://schemas.opengis.net/gml/3.1.1/base/geometryBasic0d1d.xsd'
};

/**
 * services that are called by openrouteservice, e.g. to determine the route between two waypoints
 * important note: all these URLs must be listed in the cgi-bin/proxy.cgi script of the server running ORS!
 * important note: all URLs have been blanked out for security reasons
 * if you want to become an active ORS code contributor please contact us: openrouteserviceATgeog.uni-heidelberg.de
 */
namespaces.services = {
	// see latest ORS API documentation http://wiki.openstreetmap.org/wiki/OpenRouteService
	geocoding : 'http://openls.geog.uni-heidelberg.de/testing2015/geocoding', //for address search requests
	//routing : 'http://openls.geog.uni-heidelberg.de/testing2015/routing', //for routing requests
	routing: 'http://openls.geog.uni-heidelberg.de/osm/routing-test',
	directory : 'http://openls.geog.uni-heidelberg.de/testing2015/directory', //for POI search requests
	analyse : 'http://openls.geog.uni-heidelberg.de/testing2015/analysis',
	shorten: 'http://openls.geog.uni-heidelberg.de/osm/shortenlink-test',
	wps : '' //for calculation of polygon around route for POI search
	//profile: '' 			//for height profile of route
};

/**
 * map layers used on the openlayers map
 */
//url to ORS-WMS map layer
namespaces.layerWms = 'http://129.206.228.72/cached/osm?';
//url to Open Map Surfer layer
namespaces.layerMapSurfer = 'http://korona.geog.uni-heidelberg.de/tiles/roads/x=${x}&y=${y}&z=${z}';
//url to hillshade overlay
namespaces.layerHs = 'http://korona.geog.uni-heidelberg.de/tiles/asterh/';
//urls to TMC overlay
namespaces.overlayTmc = '';
namespaces.overlayTmcLines = ''
;<commit_msg>AA Service URL changed<commit_after>/**
 * all URLs used in the openrouteservice
 */

/**
 * namespaces and schemata e.g. for XML requests to services
 */
namespaces = {
	xls : 'http://www.opengis.net/xls',
	sch : 'http://www.ascc.net/xml/schematron',
	gml : 'http://www.opengis.net/gml',
	wps : 'http://www.opengis.net/wps/1.0.0',
	ows : 'http://www.opengis.net/ows/1.1',
	xlink : 'http://www.w3.org/1999/xlink',
	xsi : 'http://www.w3.org/2001/XMLSchema-instance',
	ascc : 'http://www.ascc.net/xml/schematron',
	aas : 'http://www.geoinform.fh-mainz.de/aas'
};
namespaces.schemata = {
	directoryService : 'http://www.opengis.net/xls http://schemas.opengis.net/ols/1.1.0/DirectoryService.xsd',
	analyseService : 'http://www.geoinform.fh-mainz.de/aas',
	gatewayService : 'http://www.opengis.net/xls http://schemas.opengis.net/ols/1.1.0/GatewayService.xsd',
	locationUtilityService : 'http://www.opengis.net/xls http://schemas.opengis.net/ols/1.1.0/LocationUtilityService.xsd',
	presentationService : 'http://www.opengis.net/xls http://schemas.opengis.net/ols/1.1.0/PresentationService.xsd',
	routeService : 'http://www.opengis.net/xls http://schemas.opengis.net/ols/1.1.0/RouteService.xsd',
	wpsService : 'http://www.opengis.net/xls http://schemas.opengis.net/wps/1.0.0/wpsExecute_request.xsd',
	lineStringService : 'http://www.opengis.net/gml http://schemas.opengis.net/gml/3.1.1/base/geometryBasic0d1d.xsd'
};

/**
 * services that are called by openrouteservice, e.g. to determine the route between two waypoints
 * important note: all these URLs must be listed in the cgi-bin/proxy.cgi script of the server running ORS!
 * important note: all URLs have been blanked out for security reasons
 * if you want to become an active ORS code contributor please contact us: openrouteserviceATgeog.uni-heidelberg.de
 */
namespaces.services = {
	// see latest ORS API documentation http://wiki.openstreetmap.org/wiki/OpenRouteService
	geocoding : 'http://openls.geog.uni-heidelberg.de/testing2015/geocoding', //for address search requests
	//routing : 'http://openls.geog.uni-heidelberg.de/testing2015/routing', //for routing requests
	routing: 'http://openls.geog.uni-heidelberg.de/osm/routing-test',
	directory : 'http://openls.geog.uni-heidelberg.de/testing2015/directory', //for POI search requests
	analyse : 'http://openls.geog.uni-heidelberg.de/testing2015/analysis-test',
	shorten: 'http://openls.geog.uni-heidelberg.de/osm/shortenlink-test',
	wps : '' //for calculation of polygon around route for POI search
	//profile: '' 			//for height profile of route
};

/**
 * map layers used on the openlayers map
 */
//url to ORS-WMS map layer
namespaces.layerWms = 'http://129.206.228.72/cached/osm?';
//url to Open Map Surfer layer
namespaces.layerMapSurfer = 'http://korona.geog.uni-heidelberg.de/tiles/roads/x=${x}&y=${y}&z=${z}';
//url to hillshade overlay
namespaces.layerHs = 'http://korona.geog.uni-heidelberg.de/tiles/asterh/';
//urls to TMC overlay
namespaces.overlayTmc = '';
namespaces.overlayTmcLines = ''
;<|endoftext|>


<commit_before>module.exports = function(pool, opts) {

  var opts = opts || {};

  var defaults = {
    xScale: pool.xScale().copy(),
    width: 8
  };

  _.defaults(opts, defaults);

  function carbs(selection) {
    selection.each(function(currentData) {
      var rects = d3.select(this)
        .selectAll('rect')
        .data(currentData, function(d) {
          // leveraging the timestamp of each datapoint as the ID for D3's binding
          return d.normalTime;
        });
      rects.enter()
        .append('rect')
        .attr({
          'x': function(d) {
            return opts.xScale(Date.parse(d.normalTime)) - opts.width/2;
          },
          'y': function(d) {
            return opts.yScale(d.value);
          },
          'width': opts.width,
          'height': function(d) {
            return opts.yScale.range()[0] - opts.yScale(d.value);
          },
          'class': 'd3-rect-bolus d3-bolus',
          'id': function(d) {
            return d.normalTime + ' ' + d.value;
          }
        });
        rects.exit().remove();
    });
  }

  return carbs;
};<commit_msg>switch to bolus groups for managing boluses enter() and exit() selections; add bolus.x for easy getting of x-coords<commit_after>module.exports = function(pool, opts) {

  var opts = opts || {};

  var defaults = {
    xScale: pool.xScale().copy(),
    width: 8
  };

  _.defaults(opts, defaults);

  function bolus(selection) {
    selection.each(function(currentData) {
      var boluses = d3.select(this)
        .selectAll('g')
        .data(currentData, function(d) {
          // leveraging the timestamp of each datapoint as the ID for D3's binding
          return d.normalTime;
        });
      var bolusGroups = boluses.enter()
        .append('g')
        .attr({
          'class': 'd3-bolus-group'
        });
      var top = opts.yScale.range()[0];
      bolusGroups.append('rect')
        .attr({
          'x': function(d) {
            return bolus.x(d);
          },
          'y': function(d) {
            return opts.yScale(d.value);
          },
          'width': opts.width,
          'height': function(d) {
            return top - opts.yScale(d.value);
          },
          'class': 'd3-rect-bolus d3-bolus',
          'id': function(d) {
            return d.normalTime + ' ' + d.value + ' ' + d.recommended + ' recommended';
          }
        });
      boluses.exit().remove();
    });
  }

  bolus.x = function(d) {
    return opts.xScale(Date.parse(d.normalTime)) - opts.width/2;
  };

  return bolus;
};<|endoftext|>


<commit_before>if(typeof Merquery == "undefined" ) {
    Merquery = {};
}

Merquery.queryMaker = {

    // queryPieces are the pieces of information used to form the query based on the selection of checkboxes
    queryPieces: [
        {
            category: "Demographics",
            columnNames: "Demographics.firstname, Demographics.lastname, Demographics.emailmd5, Demographics.birthdate, Demographics.gender, Demographics.city, " +
            "Demographics.ethnicity, Demographics.sexorient, Demographics.marital, Demographics.children",
            fromStatement: "(SELECT firstname, lastname, emailmd5, birthdate,gender, city, ethnicity, sexorient, marital, children " +
            "FROM [formal-cascade-571:uci.demo_info] where emailmd5 is not null ) AS Demographics"
        },
        {
            category: "Address",
            columnNames: "Address.Address1, Address.Address2, Address.City, Address.State, Address.Zip",
            fromStatement: "(SELECT emailmd5, Address1, Address2, City, State, Zip FROM [formal-cascade-571:uci.address_info]) " +
            "AS Address ON Address.emailmd5 = Demographics.emailmd5"
        },
        {
            category: "Campaign",
            columnNames: "Campaign.advertiser_id, Campaign.advertiser_name, Campaign.campaign_id, Campaign.campaign_name," +
            " Campaign.impression_count, Campaign.click_count, Campaign.conversion_count",
            fromStatement: "(SELECT emailmd5, advertiser_id, advertiser_name, campaign_id, campaign_name, impression_count, " +
            "click_count, conversion_count FROM [formal-cascade-571:uci.campaign_info]) AS Campaign ON Campaign.emailmd5 = Demographics.emailmd5"
        },
        {
            category: "Behavior",
            columnNames: "Behavior.id, Behavior.name, Behavior.last_seen, Behavior.count",
            fromStatement: "(SELECT emailmd5, id, name, last_seen, count FROM [formal-cascade-571:uci.behavior_info]) " +
            "AS Behavior ON Behavior.emailmd5 = Demographics.emailmd5"
        },
        {
            category: "Device",
            columnNames: "Device.device_id, Device.device_name, Device.device_type_id, Device.device_type_name, " +
            "Device.operating_system, Device.last_seen",
            fromStatement: "(SELECT emailmd5, device_id, device_name, device_type_id, device_type_name, operating_system, " +
            "last_seen FROM [formal-cascade-571:uci.device_info]) AS Device ON Device.emailmd5 = Demographics.emailmd5"
        },
        {
            category: "Purchase",
            columnNames: "Purchase.advertiser_id, Purchase.last_sales_amount, Purchase.last_purchase_date, " +
            "Purchase.ltv_online, Purchase.ltv_offline",
            fromStatement: "(SELECT emailmd5, advertiser_id, last_sales_amount, last_purchase_date, ltv_online, " +
            "ltv_offline FROM [formal-cascade-571:uci.purchase_info]) AS Purchase ON Purchase.emailmd5 = Demographics.emailmd5"
        }
    ],

    // formQuery: Uses the queryPieces object to form the queries based on the breadcrumbs and selected checkboxes
    formQuery: function() {
        var checkedBoxes = Merquery.checkboxes.checkedBoxes;
        var formedQuery = "";
        var queryString = "";
        var fromString = "";
        var whereString = "";
        var endString = "";
        var queryPieces = Merquery.queryMaker.queryPieces;
        var userInputs= Merquery.BreadCrumbs.crumbs;
        for (var i=0; i<checkedBoxes.length; i++) {
            for (var j = i; j < queryPieces.length; j++) {
                var categoryNotInFromString = fromString.indexOf(queryPieces[j].category) == -1;
                var categoryNotSelected = checkedBoxes.indexOf(queryPieces[j].category) == -1;
                if (i == 0) {
                    if (j!=0 && queryPieces[j].category == checkedBoxes[i] && categoryNotInFromString) {
                        queryString += "Demographics.emailmd5, " + queryPieces[j].columnNames;
                        fromString += " LEFT JOIN EACH " + queryPieces[j].fromStatement;
                    }
                    else if (j==0 && queryPieces[j].category == checkedBoxes[i] && categoryNotInFromString) {
                        queryString += queryPieces[j].columnNames;
                        fromString += " FROM " + queryPieces[j].fromStatement;
                    }
                    else if (j==0 && categoryNotInFromString) {
                        fromString += " FROM " + queryPieces[j].fromStatement;
                    }
                    else if ((queryPieces[j].category != checkedBoxes[i]) && categoryNotInFromString && categoryNotSelected) {
                        fromString += " LEFT JOIN EACH " + queryPieces[j].fromStatement;
                    }
                }
                else {
                    if ((queryPieces[j].category == checkedBoxes[i]) && categoryNotInFromString) {
                        queryString += ", " + queryPieces[j].columnNames;
                        fromString += " LEFT JOIN EACH " + queryPieces[j].fromStatement;
                    }
                    else if ((queryPieces[j].category != checkedBoxes[i]) && categoryNotInFromString && categoryNotSelected) {
                        console.log("elseIF2: " + queryPieces[j].category + " " + checkedBoxes[i]);
                        fromString += " LEFT JOIN EACH " + queryPieces[j].fromStatement;
                    }

                }
            }
        }

        whereString += ' WHERE ';

        for(var i=0; i<userInputs.length; i++){
            var formattedFieldName;
            if(i ==0){
                formattedFieldName = Merquery.TableAndFieldsFormatter.formatFieldName(userInputs[i].queryField);
                whereString +=  'lower(' + formattedFieldName + ') ' + ' like "%' + userInputs[i].input + '%"';
            }
            else if(i>0){
                whereString += ' AND ';
                formattedFieldName = Merquery.TableAndFieldsFormatter.formatFieldName(userInputs[i].queryField)
                if(userInputs[i].querytype == 'STRING')
                    whereString += 'lower(' + formattedFieldName + ') ' + ' like "%' + userInputs[i].input + '%"';
                else
                    whereString += formattedFieldName + ' = ' + userInputs[i].input;
            }
        }

        formedQuery += "SELECT " + queryString + fromString + whereString + " GROUP each BY " + queryString + ' Limit ' + "20" + ';';
        return formedQuery;
    }
};

<commit_msg>Fixed query statement<commit_after>if(typeof Merquery == "undefined" ) {
    Merquery = {};
}

Merquery.queryMaker = {

    // queryPieces are the pieces of information used to form the query based on the selection of checkboxes
    queryPieces: [
        {
            category: "Demographics",
            columnNames: "Demographics.firstname, Demographics.lastname, Demographics.emailmd5, Demographics.birthdate, Demographics.gender, Demographics.city, " +
            "Demographics.ethnicity, Demographics.sexorient, Demographics.marital, Demographics.children",
            fromStatement: "(SELECT firstname, lastname, emailmd5, birthdate,gender, city, ethnicity, sexorient, marital, children " +
            "FROM [formal-cascade-571:uci.demo_info] where emailmd5 is not null ) AS Demographics"
        },
        {
            category: "Address",
            columnNames: "Address.Address1, Address.Address2, Address.City, Address.State, Address.Zip",
            fromStatement: "(SELECT emailmd5, Address1, Address2, City, State, Zip FROM [formal-cascade-571:uci.address_info]) " +
            "AS Address ON Address.emailmd5 = Demographics.emailmd5"
        },
        {
            category: "Campaign",
            columnNames: "Campaign.advertiser_id, Campaign.advertiser_name, Campaign.campaign_id, Campaign.campaign_name," +
            " Campaign.impression_count, Campaign.click_count, Campaign.conversion_count",
            fromStatement: "(SELECT emailmd5, advertiser_id, advertiser_name, campaign_id, campaign_name, impression_count, " +
            "click_count, conversion_count FROM [formal-cascade-571:uci.campaign_info]) AS Campaign ON Campaign.emailmd5 = Demographics.emailmd5"
        },
        {
            category: "Behavior",
            columnNames: "Behavior.id, Behavior.name, Behavior.last_seen, Behavior.count",
            fromStatement: "(SELECT emailmd5, id, name, last_seen, count FROM [formal-cascade-571:uci.behavior_info]) " +
            "AS Behavior ON Behavior.emailmd5 = Demographics.emailmd5"
        },
        {
            category: "Device",
            columnNames: "Device.device_id, Device.device_name, Device.device_type_id, Device.device_type_name, " +
            "Device.operating_system, Device.last_seen",
            fromStatement: "(SELECT emailmd5, device_id, device_name, device_type_id, device_type_name, operating_system, " +
            "last_seen FROM [formal-cascade-571:uci.device_info]) AS Device ON Device.emailmd5 = Demographics.emailmd5"
        },
        {
            category: "Purchase",
            columnNames: "Purchase.advertiser_id, Purchase.last_sales_amount, Purchase.last_purchase_date, " +
            "Purchase.ltv_online, Purchase.ltv_offline",
            fromStatement: "(SELECT emailmd5, advertiser_id, last_sales_amount, last_purchase_date, ltv_online, " +
            "ltv_offline FROM [formal-cascade-571:uci.purchase_info]) AS Purchase ON Purchase.emailmd5 = Demographics.emailmd5"
        }
    ],

    // formQuery: Uses the queryPieces object to form the queries based on the breadcrumbs and selected checkboxes
    formQuery: function() {
        var checkedBoxes = Merquery.checkboxes.checkedBoxes;
        var formedQuery = "";
        var queryString = "";
        var fromString = "";
        var whereString = "";
        var endString = "";
        var queryPieces = Merquery.queryMaker.queryPieces;
        var userInputs= Merquery.BreadCrumbs.crumbs;
        for (var i=0; i<checkedBoxes.length; i++) {
            for (var j = i; j < queryPieces.length; j++) {
                var categoryNotInFromString = fromString.indexOf(queryPieces[j].category) == -1;
                var categoryNotSelected = checkedBoxes.indexOf(queryPieces[j].category) == -1;
                if (i == 0) {
                    if (j!=0 && queryPieces[j].category == checkedBoxes[i] && categoryNotInFromString) {
                        queryString += "Demographics.emailmd5, " + queryPieces[j].columnNames;
                        fromString += " LEFT JOIN EACH " + queryPieces[j].fromStatement;
                    }
                    else if (j==0 && queryPieces[j].category == checkedBoxes[i] && categoryNotInFromString) {
                        queryString += queryPieces[j].columnNames;
                        fromString += " FROM " + queryPieces[j].fromStatement;
                    }
                    else if (j==0 && categoryNotInFromString) {
                        fromString += " FROM " + queryPieces[j].fromStatement;
                    }
                    else if ((queryPieces[j].category != checkedBoxes[i]) && categoryNotInFromString && categoryNotSelected) {
                        fromString += " LEFT JOIN EACH " + queryPieces[j].fromStatement;
                    }
                }
                else {
                    if ((queryPieces[j].category == checkedBoxes[i]) && categoryNotInFromString) {
                        queryString += ", " + queryPieces[j].columnNames;
                        fromString += " LEFT JOIN EACH " + queryPieces[j].fromStatement;
                    }
                    else if ((queryPieces[j].category != checkedBoxes[i]) && categoryNotInFromString && categoryNotSelected) {
                        console.log("elseIF2: " + queryPieces[j].category + " " + checkedBoxes[i]);
                        fromString += " LEFT JOIN EACH " + queryPieces[j].fromStatement;
                    }

                }
            }
        }

        whereString += ' WHERE ';

        for(var i=0; i<userInputs.length; i++){
            var formattedFieldName;
            if(i ==0){
                formattedFieldName = Merquery.TableAndFieldsFormatter.formatFieldName(userInputs[i].queryField);
                whereString +=  'lower(' + formattedFieldName + ') ' + ' like "%' + (userInputs[i].input).toLowerCase() + '%"';
            }
            else if(i>0){
                whereString += ' AND ';
                formattedFieldName = Merquery.TableAndFieldsFormatter.formatFieldName(userInputs[i].queryField)
                if(userInputs[i].querytype == 'STRING')
                    whereString += 'lower(' + formattedFieldName + ') ' + ' like "%' + (userInputs[i].input).toLowerCase() + '%"';
                else
                    whereString += formattedFieldName + ' = ' + (userInputs[i].input).toLowerCase();
            }
        }

        formedQuery += "SELECT " + queryString + fromString + whereString + " GROUP each BY " + queryString + ' Limit ' + "20" + ';';
        return formedQuery;
    }
};

<|endoftext|>


<commit_before>// Wrap an HTMLElement around each element in an HTMLElement array.
HTMLElement.prototype.wrap = function(elms) {
    // Convert `elms` to an array, if necessary.
    if (!elms.length) elms = [elms];

    // Loops backwards to prevent having to clone the wrapper on the
    // first element (see `child` below).
    for (var i = elms.length - 1; i >= 0; i--) {
        var child = (i > 0) ? this.cloneNode(true) : this;
        var el    = elms[i];

        // Cache the current parent and sibling.
        var parent  = el.parentNode;
        var sibling = el.nextSibling;

        // Wrap the element (is automatically removed from its current
        // parent).
        child.appendChild(el);

        // If the element had a sibling, insert the wrapper before
        // the sibling to maintain the HTML structure; otherwise, just
        // append it to the parent.
        if (sibling) {
            parent.insertBefore(child, sibling);
        } else {
            parent.appendChild(child);
        }
    }
};

/*
    Usage
    ------
    Four parameters you can use:
    'parent'     = parent element object or id
    'wrapper_id' = the attribute that you need this innerwrapped element to have

    Example
    -------
    wrapInner(parent, 'wrapper_id');
*/

function wrapInner(parent, wrapperID) {
    wrapper = document.createElement('div');
    if (typeof parent === "string") { parent = document.getElementById(parent); }
    var div = parent.appendChild(wrapper).setAttribute('id', wrapperID);
    while (parent.firstChild !== wrapper) {
        wrapper.appendChild(parent.firstChild);
    }
}

function initResponsiveHeader() {
    responsiveHeaderHTML = '\
     \

 \

 \

SNUL
 \

 \

 \

 \
                     \

 \

User Login
 \

 \

 \
    ';
    responsiveHeader = $(responsiveHeaderHTML);
    headerContainer = $('#header');
    responsiveHeader.insertAfter(headerContainer);
}

function initResponsiveContainers() {
    scrollerContainerID = "scroller";
    naviPusherID = "navi-pusher";
    responsiveContainerID = "responsive-container";
    // initiate contstruction
    wrapInner(document.body, responsiveContainerID);
    wrapInner(responsiveContainerID, scrollerContainerID);
    wrapInner(scrollerContainerID, naviPusherID);

    $('').insertBefore("#scroller");
    $('

').insertAfter()
}

function isKorean(){
    return $('body').hasClass('EXLCurrentLang_ko_KR');
}

function convertResponsiveMenu(desktopMenu) {
    // Initial Variables
    responsiveMenu   = desktopMenu.clone();
    menuLevelDiv     = '

';
    firstLevelItems  = responsiveMenu.children('li');
    submenuTitleDiv  = '

';
    backButtonAnchor = 'back';

    // Responsive id and navi menu class
    responsiveMenu.attr('id', "navi-" + responsiveMenu.attr('id'));
    responsiveMenu.addClass('navi-menu');

    // First level
    $('
Main Menu
').insertBefore(firstLevelItems.first());
    responsiveMenu.wrapInner(menuLevelDiv);

    // Second level
    firstLevelItems.each(function(index) {
        title = $(this).children('a').first();
        $(backButtonAnchor).insertAfter(title);
        title.wrap(submenuTitleDiv);
        $(this).wrapInner(menuLevelDiv);
    });

    return responsiveMenu;
}

function createResponsiveMenu() {
    if (isKorean()) {
        return convertResponsiveMenu($('#korean-main-navigation'));
    } else {
        return convertResponsiveMenu($('#english-main-menu'));
    }
}

var responsiveMenu = {};

$(document).ready(function () {
    // Responsive Header
    initResponsiveHeader();
    // Responsive Containers
    initResponsiveContainers();
    // Responsive Menu
    $('#responsive-menu').append(createResponsiveMenu());
});<commit_msg>Deploying changes<commit_after>// Wrap an HTMLElement around each element in an HTMLElement array.
HTMLElement.prototype.wrap = function(elms) {
    // Convert `elms` to an array, if necessary.
    if (!elms.length) elms = [elms];

    // Loops backwards to prevent having to clone the wrapper on the
    // first element (see `child` below).
    for (var i = elms.length - 1; i >= 0; i--) {
        var child = (i > 0) ? this.cloneNode(true) : this;
        var el    = elms[i];

        // Cache the current parent and sibling.
        var parent  = el.parentNode;
        var sibling = el.nextSibling;

        // Wrap the element (is automatically removed from its current
        // parent).
        child.appendChild(el);

        // If the element had a sibling, insert the wrapper before
        // the sibling to maintain the HTML structure; otherwise, just
        // append it to the parent.
        if (sibling) {
            parent.insertBefore(child, sibling);
        } else {
            parent.appendChild(child);
        }
    }
};

/*
    Usage
    ------
    Four parameters you can use:
    'parent'     = parent element object or id
    'wrapper_id' = the attribute that you need this innerwrapped element to have

    Example
    -------
    wrapInner(parent, 'wrapper_id');
*/

function wrapInner(parent, wrapperID) {
    wrapper = document.createElement('div');
    if (typeof parent === "string") { parent = document.getElementById(parent); }
    var div = parent.appendChild(wrapper).setAttribute('id', wrapperID);
    while (parent.firstChild !== wrapper) {
        wrapper.appendChild(parent.firstChild);
    }
}

function initResponsiveHeader() {
    responsiveHeaderHTML = '\
     \

 \

 \

SNUL
 \

 \

 \

 \
                     \

 \

User Login
 \

 \

 \
    ';
    responsiveHeader = $(responsiveHeaderHTML);
    headerContainer = $('#header');
    responsiveHeader.insertAfter(headerContainer);
}

function initResponsiveContainers() {
    scrollerContainerID = "scroller";
    naviPusherID = "navi-pusher";
    responsiveContainerID = "responsive-container";
    // initiate contstruction
    wrapInner(document.body, responsiveContainerID);
    wrapInner(responsiveContainerID, scrollerContainerID);
    wrapInner(scrollerContainerID, naviPusherID);

    $('').insertBefore("#scroller");
    $('

').insertAfter()
}

function isKorean(){
    return $('body').hasClass('EXLCurrentLang_ko_KR');
}

function convertResponsiveMenu(desktopMenu) {
    // Initial Variables
    responsiveMenu   = desktopMenu.clone();
    menuLevelDiv     = '

';
    firstLevelItems  = responsiveMenu.children('li');
    submenuTitleDiv  = '

';
    backButtonAnchor = 'back';

    // Responsive id and navi menu class
    responsiveMenu.attr('id', "navi-" + responsiveMenu.attr('id'));
    responsiveMenu.addClass('navi-menu');

    // First level
    $('
Main Menu
').insertBefore(firstLevelItems.first());
    responsiveMenu.wrapInner(menuLevelDiv);

    // Second level
    firstLevelItems.each(function(index) {
        title = $(this).children('a').first();
        $(backButtonAnchor).insertAfter(title);
        title.wrap(submenuTitleDiv);
        $(this).wrapInner(menuLevelDiv);
    });

    return responsiveMenu;
}

function createResponsiveMenu() {
    if (isKorean()) {
        return convertResponsiveMenu($('#korean-main-navigation'));
    } else {
        return convertResponsiveMenu($('#english-main-menu'));
    }
}

var responsiveMenu = {};

$(document).ready(function () {
    // Responsive Header
    initResponsiveHeader();
    // Responsive Containers
    initResponsiveContainers();
    // Responsive Menu
    $('#responsive-menu').append(createResponsiveMenu());
});<|endoftext|>


<commit_before>/*
 *  Free Room Finder Website
 *
 *
 *  Authors -- Crow's Foot Group
 *  -------------------------------------------------------
 *
 *  Jonathan Gillett
 *  Joseph Heron
 *  Amit Jain
 *  Wesley Unwin
 *  Anthony Jihn
 *
 *
 *  License
 *  -------------------------------------------------------
 *
 *  Copyright (C) 2012 Crow's Foot Group
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

/* The root URL for the RESTful services */
var rootURL = "http://free-room.dom/api";

$(document).ready(function () {
	alert(window.location.toString());
	/* Display the statistics when page is loaded */
	busyProfs();
});

/* Get the list of the busiest professors and populate the table */
function busyProfs() {
	console.log('busyprofs');
	$.ajax({
		type: 'GET',
		url: rootURL + '/busyprofs',
		dataType: "json", // data type of response
		success: displayTable
	});
}

/* Function which populates the busiest profs table with the top 10
 * busiest professors
 */
function displayTable(data) {
	console.log('displayTable');
	// JAX-RS serializes an empty list as null, and a 'collection of one' as an object (not an 'array of one')
	var list = data == null ? [] : (data.busyProfs instanceof Array ? data.busyProfs : [data.busyProfs]);

	$.each(list, function(index, prof) {
		$('#tbody_busyprofs').append('
' + prof.professor + '	' + prof.student_num + '
');
	});
}<commit_msg>Changed Busiest profs table to only display the top 10 busiest profs<commit_after>/*
 *  Free Room Finder Website
 *
 *
 *  Authors -- Crow's Foot Group
 *  -------------------------------------------------------
 *
 *  Jonathan Gillett
 *  Joseph Heron
 *  Amit Jain
 *  Wesley Unwin
 *  Anthony Jihn
 *
 *
 *  License
 *  -------------------------------------------------------
 *
 *  Copyright (C) 2012 Crow's Foot Group
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

/* The root URL for the RESTful services */
var rootURL = "http://free-room.dom/api";

$(document).ready(function () {
	alert(window.location.toString());
	/* Display the statistics when page is loaded */
	busyProfs();
});

/* Get the list of the top 10 busiest professors and populate the table */
function busyProfs() {
	console.log('busyprofs');
	$.ajax({
		type: 'GET',
		url: rootURL + '/busyprofs/10',
		dataType: "json", // data type of response
		success: displayTable
	});
}

/* Function which populates the busiest profs table with the top 10
 * busiest professors
 */
function displayTable(data) {
	console.log('displayTable');
	// JAX-RS serializes an empty list as null, and a 'collection of one' as an object (not an 'array of one')
	var list = data == null ? [] : (data.busyProfs instanceof Array ? data.busyProfs : [data.busyProfs]);

	$.each(list, function(index, prof) {
		$('#tbody_busyprofs').append('
' + prof.professor + '	' + prof.student_num + '
');
	});
}<|endoftext|>


<commit_before>function TabStack (tabStack) {
  this.depth = 15

  if (tabStack) {
    this.stack = tabStack.stack
  } else {
    this.stack = []
  }
}

TabStack.prototype.push = function (closedTab) {
  // Do not store private tabs or blank tabs
  if (closedTab.private ||
    closedTab.url === '') {
    return
  }

  if (this.stack.length >= this.depth) {
    this.stack.shift()
  }

  this.stack.push(closedTab)
}

TabStack.prototype.pop = function () {
  return this.stack.pop()
}

module.exports = TabStack
<commit_msg>reduce tab history size<commit_after>function TabStack (tabStack) {
  this.depth = 10

  if (tabStack) {
    this.stack = tabStack.stack
  } else {
    this.stack = []
  }
}

TabStack.prototype.push = function (closedTab) {
  // Do not store private tabs or blank tabs
  if (closedTab.private ||
    closedTab.url === '') {
    return
  }

  if (this.stack.length >= this.depth) {
    this.stack.shift()
  }

  this.stack.push(closedTab)
}

TabStack.prototype.pop = function () {
  return this.stack.pop()
}

module.exports = TabStack
<|endoftext|>


<commit_before>// Test Sprite, extends sprite, just to show an example
(function () {
	//constructor
    function TestSprite(options)
    {
		Sprite.call(this, options);
		this.clickable = true;

		this.addAnimation([0,1,2], "walk");
		this.addAnimation([5,3,4], "punch");
		this.playAnimation('walk', 130, 1);
	}

	TestSprite.prototype = new Sprite();
	this.TestSprite = TestSprite;

	// public
	TestSprite.prototype.update = function(deltaTime)
    {
		Sprite.prototype.update.call(this, deltaTime);

		if(!this.isAnimating){
			this.playAnimation('walk', 130, 1);
		}

		this.vel.x = (Math.cos(((this.angle)) *  Math.PI / 180) * this.thrust * deltaTime);
		this.vel.y = (Math.sin(((this.angle)) *  Math.PI / 180) * this.thrust * deltaTime);

		this.pos.x += this.vel.x;
		this.pos.y += this.vel.y;

		if(this.pos.x > Game.bounds.width){
			this.pos.x = -16;
		}

		if(this.pos.y > Game.bounds.height){
			this.pos.y = -16;
		}

		this.startY = this.height*Math.round(this.angle/90);
    };

	TestSprite.prototype.clicked = function(){
		this.playAnimation('punch', 130, 0);
	};

})();<commit_msg>Fixed some incorrect indentation.<commit_after>// Test Sprite, extends sprite, just to show an example
(function () {
	//constructor
    function TestSprite(options)
    {
		Sprite.call(this, options);
		this.clickable = true;

		this.addAnimation([0,1,2], "walk");
		this.addAnimation([5,3,4], "punch");
		this.playAnimation('walk', 130, 1);
	}

	TestSprite.prototype = new Sprite();
	this.TestSprite = TestSprite;

	TestSprite.prototype.update = function(deltaTime)
    	{
		Sprite.prototype.update.call(this, deltaTime);

		if(!this.isAnimating){
			this.playAnimation('walk', 130, 1);
		}

		this.vel.x = (Math.cos(((this.angle)) *  Math.PI / 180) * this.thrust * deltaTime);
		this.vel.y = (Math.sin(((this.angle)) *  Math.PI / 180) * this.thrust * deltaTime);

		this.pos.x += this.vel.x;
		this.pos.y += this.vel.y;

		if(this.pos.x > Game.bounds.width){
			this.pos.x = -16;
		}

		if(this.pos.y > Game.bounds.height){
			this.pos.y = -16;
		}

		this.startY = this.height*Math.round(this.angle/90);
    	};

	TestSprite.prototype.clicked = function(){
		this.playAnimation('punch', 130, 0);
	};

})();<|endoftext|>


<commit_before>(function() {
  var TileMap = function(options) {
    this.canvas = options.canvas;
    this.context = this.canvas.getContext('2d');
    this.images = options.images;
    this.map = options.map;

    // Normalize layers to a zero indexed map
    this.map.layers.forEach(function(layer) {
      layer.data.forEach(function(number, index, layer) {
        layer[index] = number - 1;
      });
    });
  }

  TileMap.prototype.clip = function(index) {
    // TODO Generalize for multiple tilesets
    var tileset = this.map.tilesets[0];
    var row = Math.floor((index * tileset.tilewidth) / tileset.imagewidth);

    return {
      image: this.images[0],
      x: (index * tileset.tilewidth) % tileset.imagewidth,
      y: (row * tileset.tileheight) % tileset.imageheight,
      width: tileset.tilewidth,
      height: tileset.tileheight,
    }
  }

  TileMap.prototype.draw = function() {
    this.map.layers.forEach(function(layer) {
      layer.data.forEach(function(number, index) {
        var x = index % layer.width;
        var y = Math.floor(index / layer.width);
        var clip = this.clip(number);
        this.context.drawImage(clip.image, clip.x, clip.y, clip.width, clip.height,
                               x * Map.tilewidth, y * Map.tileheight, Map.tilewidth, Map.tileheight);
      }, this)
    }, this);
  }

  window.TileMap = TileMap;
})();
<commit_msg>Generalize clipping for multiple tilesets<commit_after>(function() {
  var TileMap = function(options) {
    this.canvas = options.canvas;
    this.context = this.canvas.getContext('2d');
    this.map = options.map;

    // Add each image to the appropriate tileset and patch a function to verify
    // it's index boundaries
    this.map.tilesets.forEach(function(tileset, index, tilesets) {
      var tiles = Math.floor(tileset.imagewidth / tileset.tilewidth) *
                  Math.floor(tileset.imageheight / tileset.tileheight);

      tilesets[index].image = options.images[index];
      tilesets[index].min = tileset.firstgid - 1;
      tilesets[index].max = tilesets[index].min + tiles;

      // Check whether the 'number' is in this tileset or not
      tilesets[index].inside = function(number) {
        return number >= this.min && this.max >= number;
      }.bind(tileset);
    });

    // Normalize layers to a zero indexed map
    this.map.layers.forEach(function(layer) {
      layer.data.forEach(function(number, index, layer) {
        layer[index] = number - 1;
      });
    });
  }

  TileMap.prototype.clip = function(index) {
    var tileset = null;
    this.map.tilesets.forEach(function(set) {
      if (set.inside(index)) {
        tileset = set;
      }
    });
    var row = Math.floor((index * tileset.tilewidth) / tileset.imagewidth);

    return {
      image: tileset.image,
      x: (index * tileset.tilewidth) % tileset.imagewidth,
      y: (row * tileset.tileheight) % tileset.imageheight,
      width: tileset.tilewidth,
      height: tileset.tileheight,
    }
  }

  TileMap.prototype.draw = function() {
    this.map.layers.forEach(function(layer) {
      layer.data.forEach(function(number, index) {
        var x = index % layer.width;
        var y = Math.floor(index / layer.width);
        var clip = this.clip(number);
        this.context.drawImage(clip.image, clip.x, clip.y, clip.width, clip.height,
                               x * Map.tilewidth, y * Map.tileheight, Map.tilewidth, Map.tileheight);
      }, this)
    }, this);
  }

  window.TileMap = TileMap;
})();
<|endoftext|>


<commit_before>UIControls = {
  getFieldTypeSelectTemplate: function() {
    var options = [];
    for (var id in UIHelper.FIELD_TYPES) {
      options.push({ id: id, value: UIHelper.FIELD_TYPES[id].title });
    }
    return {
      view: 'select',
      required: true,
      name: 'type',
      label: 'Type',
      options: options
    };
  },

  getEntityTypeSelectTemplate: function() {
    return {
      view: 'select',
      label: 'Type',
      name: 'type',
      options: [
        { id: 'private', value: 'Private' },
        { id: 'public', value: 'Public' },
        { id: 'unqiue', value: 'Unique' },
      ]
    };
  },

  getOnForFormWindow: function(id) {
    var formId = id + '_form';
    var windowId = id + '_window';
    return {
      onHide: function() {
        $$(formId).clearValidation();
        $$(formId).setValues($$(formId).getCleanValues());
      },
      onShow: function() {
        $$(formId).focus();
        $$(formId).setDirty(false);
        $$(windowId + '__cancel_button').define('hotkey', 'escape');
      }
    };
  },

  getSubmitCancelForFormWindow: function(id) {
    var formId = id + '_form';
    var windowId = id + '_window';
    return { cols: [
        { view: 'button',
          value: 'Create',
          type: 'form',
          click: function() { $$(formId).callEvent('onSubmit') }
        },
        { view: 'button',
          id: windowId + '__cancel_button',
          value: 'Cancel',
          type: 'danger', click: function() { $$(windowId).hide() }
        },
      ]
    }
  },

  getLoginButtonView: function(providerName) {
    var authProvider = MyDataSpace.authProviders[providerName];
    return {
      view: 'button',
      label: authProvider.title,
      type: 'iconButton',
      icon: authProvider.icon,
      width: 250,
      height: 50,
      css: 'login_panel__' + providerName + '_button',
      click: function() {
        if (MyDataSpace.isLoggedIn()) {
          throw new Error('Already logged in');
        }
        MyDataSpace.login(providerName);
      }
    };
  },
};
<commit_msg>feat: Type -> Access<commit_after>UIControls = {
  getFieldTypeSelectTemplate: function() {
    var options = [];
    for (var id in UIHelper.FIELD_TYPES) {
      options.push({ id: id, value: UIHelper.FIELD_TYPES[id].title });
    }
    return {
      view: 'select',
      required: true,
      name: 'type',
      label: 'Type',
      options: options
    };
  },

  getEntityTypeSelectTemplate: function() {
    return {
      view: 'select',
      label: 'Access',
      name: 'type',
      options: [
        { id: 'private', value: 'Private' },
        { id: 'public', value: 'Create Children' },
        { id: 'unqiue', value: 'Create One Child' },
      ]
    };
  },

  getOnForFormWindow: function(id) {
    var formId = id + '_form';
    var windowId = id + '_window';
    return {
      onHide: function() {
        $$(formId).clearValidation();
        $$(formId).setValues($$(formId).getCleanValues());
      },
      onShow: function() {
        $$(formId).focus();
        $$(formId).setDirty(false);
        $$(windowId + '__cancel_button').define('hotkey', 'escape');
      }
    };
  },

  getSubmitCancelForFormWindow: function(id) {
    var formId = id + '_form';
    var windowId = id + '_window';
    return { cols: [
        { view: 'button',
          value: 'Create',
          type: 'form',
          click: function() { $$(formId).callEvent('onSubmit') }
        },
        { view: 'button',
          id: windowId + '__cancel_button',
          value: 'Cancel',
          type: 'danger', click: function() { $$(windowId).hide() }
        },
      ]
    }
  },

  getLoginButtonView: function(providerName) {
    var authProvider = MyDataSpace.authProviders[providerName];
    return {
      view: 'button',
      label: authProvider.title,
      type: 'iconButton',
      icon: authProvider.icon,
      width: 250,
      height: 50,
      css: 'login_panel__' + providerName + '_button',
      click: function() {
        if (MyDataSpace.isLoggedIn()) {
          throw new Error('Already logged in');
        }
        MyDataSpace.login(providerName);
      }
    };
  },
};
<|endoftext|>


<commit_before>define(function() {
    return {
        dec2hex: function(s) {
            return (s < 15.5 ? '0' : '') + Math.round(s).toString(16);
        },

        hex2dec: function(s) {
            return parseInt(s, 16);
        },

        base32tohex: function(base32) {
            var base32chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
            var bits = "";
            var hex = "";

            for (var i = 0; i < base32.length; i++) {
                var val = base32chars.indexOf(base32.charAt(i).toUpperCase());
                bits += this.leftpad(val.toString(2), 5, '0');
            }

            for (var j = 0; j + 4 <= bits.length; j += 4) {
                var chunk = bits.substr(j, 4);
                hex = hex + parseInt(chunk, 2).toString(16);
            }

            return hex;
        },

        leftpad: function(str, len, pad) {
            if (len + 1 >= str.length) {
                str = Array(len + 1 - str.length).join(pad) + str;
            }
            return str;
        },

        generate: function(secret) {
            var key = this.base32tohex(secret);
            var epoch = Math.round(new Date().getTime() / 1000.0);
            var time = this.leftpad(this.dec2hex(Math.floor(epoch / 30)), 16, '0');

            // external library for SHA functionality
            var hmacObj = new jsSHA(time, "HEX");
            var hmac = hmacObj.getHMAC(key, "HEX", "SHA-1", "HEX");

            if (hmac != 'KEY MUST BE IN BYTE INCREMENTS') {
                var offset = this.hex2dec(hmac.substring(hmac.length - 1));
            }

            var otp = (this.hex2dec(hmac.substr(offset * 2, 8)) & this.hex2dec('7fffffff')) + '';
            return (otp).substr(otp.length - 6, 6).toString();
        }
    };
});<commit_msg>Added attribution for TOTP generation code.<commit_after>define(function() {
    /*
     * Based on the great work by russ at http://blog.tinisles.com/2011/10/google-authenticator-one-time-password-algorithm-in-javascript/
     */

    return {
        dec2hex: function(s) {
            return (s < 15.5 ? '0' : '') + Math.round(s).toString(16);
        },

        hex2dec: function(s) {
            return parseInt(s, 16);
        },

        base32tohex: function(base32) {
            var base32chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
            var bits = "";
            var hex = "";

            for (var i = 0; i < base32.length; i++) {
                var val = base32chars.indexOf(base32.charAt(i).toUpperCase());
                bits += this.leftpad(val.toString(2), 5, '0');
            }

            for (var j = 0; j + 4 <= bits.length; j += 4) {
                var chunk = bits.substr(j, 4);
                hex = hex + parseInt(chunk, 2).toString(16);
            }

            return hex;
        },

        leftpad: function(str, len, pad) {
            if (len + 1 >= str.length) {
                str = Array(len + 1 - str.length).join(pad) + str;
            }
            return str;
        },

        generate: function(secret) {
            var key = this.base32tohex(secret);
            var epoch = Math.round(new Date().getTime() / 1000.0);
            var time = this.leftpad(this.dec2hex(Math.floor(epoch / 30)), 16, '0');

            // external library for SHA functionality
            var hmacObj = new jsSHA(time, 'HEX');
            var hmac = hmacObj.getHMAC(key, 'HEX', 'SHA-1', 'HEX');

            var offset;
            if (hmac !== 'KEY MUST BE IN BYTE INCREMENTS') {
                offset = this.hex2dec(hmac.substring(hmac.length - 1));
            }

            var otp = (this.hex2dec(hmac.substr(offset * 2, 8)) & this.hex2dec('7fffffff')) + '';
            return otp.substr(otp.length - 6, 6);
        }
    };
});<|endoftext|>