<commit_before>/** Parse sieve analysis input files.
 * Expected input files:
 * 	FASTA file with vaccine ID and AA sequence
 * 	FASTA file with breakthrough sequences and IDs
 * 	CSV with seqID:treatment (vaccine/placebo) treatment
 * 	CSV with sequence mismatches (relative to vaccine) for each seqID */

/** 2D-array (of chars) representing AAs at each position in the sequence
 * for the vaccine and each sequence ID */
var sequences_raw = [];
/** Object holding a 2D-array of sequences for both the vaccine and placebo groups */
var sequences = {"vaccine":[], "placebo":[]};
/** Dictionary with sequence IDs as keys and entries for:
 * 		AA sequence (char array),
 * 		distances (dictionary with array for each distance measure)
 * 		vaccine/placebo status (boolean) */
var seqID_lookup = {};
/** Object with vaccine ID and AA sequence */
var vaccine = {};
/** Array with conservation and reference info for each position */
var display_idx_map;
/* Lookup table with index for each hxb2 position*/
var refmap = {};
/** Number of people in the vaccine group */
var numvac = 0;
/** Number of people in the placebo group */
var numplac = 0;
/** Dictionary with wite-level statistics to display in navigation chart.
 * 	Entries are dictionaries for each distance measurement, within which are
 * 		entries that hold a site statistic and its array of values */
var siteStats = {/*EX: vxmatch_site:{placDist: [], vacDist: [], sieve_statistic: [], pval: [], qval: []}*/};
/** Appropriate scale for each of the stats above */
var statScales = {};
/** Associated axes to above */
var statAxes = {};
/** Array of p-values */
var pvalues =[];
/** Array of absolute value of t-stats */
var tvalues =[];
/** Array of Entropy Values */
var entropies = {full:[],vaccine:[],placebo:[]};
/**  Object with nests of distances for each distance method */
var dists;
/** Datasets available for analysis */
var availableDatasets;
/** Initial values for study name, protein, reference, and distance measure */
var studyname = getParameterByName("study"),
	protein = getParameterByName("protein"),
	reference = getParameterByName("ref"),
	dist_metric = getParameterByName("dist");
if (dist_metric.length < 1) { dist_metric = "vxmatch_site"};

// define object containing all required files' names
var inputFiles = getInputFilenames(studyname, protein, reference, dist_metric);
parseInput(inputFiles);

function parseInput(inputFiles){

d3.csv(inputFiles.treatmentFile, function(assigndata)
{
	parseTreatmentFile(assigndata);
	d3.text(inputFiles.sequenceFastaFile, function(fastadata)
	{
		doseqparsing(fastadata);
		d3.csv(inputFiles.distanceFile, function(distdata)
		{
			dodistparsing(distdata);
			d3.csv(inputFiles.resultsFile, function(resultdata)
			{
				parseResultsFile(resultdata);

				// Transpose data for easier access
				sequences_raw = transpose(sequences_raw);
				sequences.vaccine = transpose(sequences.vaccine);
				sequences.placebo = transpose(sequences.placebo);
				// calculate entropies
				for(var i=0; i < sequences_raw.length; i++){
					entropies.full.push(jointentropy([i],sequences_raw,numvac+numplac).toFixed(2));
				}
				for(var i=0; i < sequences.vaccine.length; i++){
					entropies.vaccine.push(jointentropy([i],sequences.vaccine,numvac).toFixed(2));
				}
				for(var i=0; i < sequences.placebo.length; i++){
					entropies.placebo.push(jointentropy([i],sequences.placebo,numplac).toFixed(2));
				}
				// If loaded URL contains sites, add them to the current selection
				var urlSiteString = getParameterByName("sites");
				if (urlSiteString !== ""){
					// get sites identified by reference strand
					var urlSites = urlSiteString.split(",");
					// convert sites back to 0-based index
					//(our working index instead of the reference index)
					urlSites.forEach(function(d,i){
						urlSites[i] = refmap[urlSites[i]];
					})
					while(urlSites.length > 0){
						var urlsite = urlSites.pop();
						if (typeof urlsite != 'undefined'){ selected_sites.push(urlsite); }
					}
				}

				// Build the visualization
				generateVis();

			});
		});
	});
});
}

function parseTreatmentFile(assigndata){
	seqID_lookup = d3.nest()
		.key(function(d) {return d.ptid;})
		.rollup(function(d) {
			if (d[0].treatment.toUpperCase().startsWith("P")){
				return { "distance": {}, "sequence": [], "vaccine": false };
			} else {
				return { "distance": {}, "sequence": [], "vaccine": true };
			}
		})
		.map(assigndata.filter(function(d){return !d.treatment.toLowerCase().startsWith("ref");}));
}

function doseqparsing(fastadata) {
	var fastaSequences = fastadata.split(/[;>]+/);
	for (var i = 0; i < fastaSequences.length; i++) {
		if (fastaSequences[i].length !== 0) {
			var seqID = fastaSequences[i].substring(0,fastaSequences[i].indexOf("\n")).trim(/[\n\r]/g, '');
			var seq = fastaSequences[i].substring(fastaSequences[i].indexOf("\n") + 1, fastaSequences[i].length);
			seq = seq.replace(/[\n\r]/g, '');
			seq = seq.split("");
			sequences_raw.push(seq);
			if (seqID.startsWith("reference"))
			{
				vaccine.ID = seqID.substring(seqID.lastIndexOf('|')+1, seqID.length);
				vaccine.sequence = seq;
			} else if ((seqID in seqID_lookup) && seqID_lookup[seqID].vaccine) {
				seqID_lookup[seqID].sequence = seq;
				sequences.vaccine.push(seq);
				numvac++;
			} else if (seqID in seqID_lookup) {
				seqID_lookup[seqID].sequence = seq;
				sequences.placebo.push(seq);
				numplac++;
			}
		}
	}
}

function dodistparsing(distdata)
{
	dists = d3.nest()
		.key(function(d) {return d.distance_method;})
		.rollup(function(data)
			{
				return d3.nest()
					.key(function(d) { return d.ptid; })
					.rollup(function(d) { return d.map(function(a) {return a.distance;}); })
					.entries(data);
			})
		.entries(distdata);
	display_idx_map = distdata.filter(function (d)
		{
			return d.ptid == distdata[0].ptid && d.distance_method == distdata[0].distance_method;
		}).map(function(d) {return d.display_position;});
	display_idx_map.forEach(function(d, i) {refmap[d] = i;});

	var distMethodSelector = d3.select("#distMethod_selector");
	dists.forEach(function(d,i){
		var newOption = distMethodSelector.append("option")
			.attr("value", d["key"])
			.attr("id","yscale-selection-option-" + d["key"])
			.text(d["key"]);
		if (i === 0){ newOption.attr("selected","selected"); }
	})
}

function parseResultsFile(resultdata){

	var statsToDisplay = Object.keys(resultdata[0]).filter(function(d,i){ return i > 2; })
	siteStats = d3.nest()
		.key(function(d) {return d.distance_method;})
		.rollup(function(d){
			var result = {};
			for (var statidx in statsToDisplay){
				var stat = statsToDisplay[statidx];
				result[stat] = d.map(function(a){return +a[stat];});
			}
			return result;
		})
		.map(resultdata);

	var yScaleSelector = d3.select("#yscale_selector");
	statsToDisplay.forEach(function(d){
		var newOption = yScaleSelector.append("option")
			.attr("value", d)
			.attr("id","yscale-selection-option-" + d)
			.text(d);
		// hard coded for now. Will data always contain a pvalue?
		// answer is yes if we decide to build in a simple pval generator
		if (d === "pvalue"){ newOption.attr("selected","selected"); }
	})

	for (var metric in siteStats)
	{
		statScales[metric] = {};
		statAxes[metric] = {};

		for (var stat in siteStats[metric])
		{
			//test if the stat name is some variant of
			//p-value or q-value
			if (/^[pq][\s-]?val/i.test(stat))
			{
				statScales[metric][stat] = d3.scale.log()
					.domain([d3.min(siteStats[dist_metric][stat]), 1])
					.range([0, .95*height])
					.nice();
				statAxes[metric][stat] =
					{"left":d3.svg.axis()
						.scale(statScales[metric][stat])
						.orient("left")
						.ticks(5, "g"),
					"right":d3.svg.axis()
						.scale(statScales[metric][stat])
						.orient("right")
						.ticks(5, "g")};
				if (/^p/i.test(stat))
				{ //Try to set the default stat to pvalue
					yscale_mode = stat;
				}
			} else {
				statScales[metric][stat] = d3.scale.linear()
					.range([.95*height, 0])
					.domain([-1,0]);
				statAxes[metric][stat] =
					{"left":d3.svg.axis()
						.scale(statScales[metric][stat])
						.orient("left")
						.ticks(5),
					"right":d3.svg.axis()
						.scale(statScales[metric][stat])
						.orient("right")
						.ticks(5)};
			}
			if (yscale_mode === undefined)
			{ //No pvalue, set stat to arbitrary value
				for (var key in statScales[metric]) break;
				yscale_mode = key;
			}
		}
	}
}

/** Transpose 2D array */
function transpose(array) {
  return array[0].map(function (_, c) { return array.map(function (r) { return r[c]; }); });
}

/**  */
function getInputFilenames(studyname, protein, reference, dist_metric){
	var result = {};
	result.treatmentFile = "../data/treatment.csv?study=" + studyname;
	result.sequenceFastaFile = "../data/alignment.fasta?study=" + studyname + "&protein=" + protein + "&ref=" + reference;
	result.distanceFile = "../data/distance.csv?study=" + studyname + "&protein=" + protein + "&ref=" + reference;
	result.resultsFile = "../data/results.csv?study=" + studyname + "&protein=" + protein + "&ref=" + reference;
	return result;
}
function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
<commit_msg>Update data request links- change ref to reference<commit_after>/** Parse sieve analysis input files.
 * Expected input files:
 * 	FASTA file with vaccine ID and AA sequence
 * 	FASTA file with breakthrough sequences and IDs
 * 	CSV with seqID:treatment (vaccine/placebo) treatment
 * 	CSV with sequence mismatches (relative to vaccine) for each seqID */

/** 2D-array (of chars) representing AAs at each position in the sequence
 * for the vaccine and each sequence ID */
var sequences_raw = [];
/** Object holding a 2D-array of sequences for both the vaccine and placebo groups */
var sequences = {"vaccine":[], "placebo":[]};
/** Dictionary with sequence IDs as keys and entries for:
 * 		AA sequence (char array),
 * 		distances (dictionary with array for each distance measure)
 * 		vaccine/placebo status (boolean) */
var seqID_lookup = {};
/** Object with vaccine ID and AA sequence */
var vaccine = {};
/** Array with conservation and reference info for each position */
var display_idx_map;
/* Lookup table with index for each hxb2 position*/
var refmap = {};
/** Number of people in the vaccine group */
var numvac = 0;
/** Number of people in the placebo group */
var numplac = 0;
/** Dictionary with wite-level statistics to display in navigation chart.
 * 	Entries are dictionaries for each distance measurement, within which are
 * 		entries that hold a site statistic and its array of values */
var siteStats = {/*EX: vxmatch_site:{placDist: [], vacDist: [], sieve_statistic: [], pval: [], qval: []}*/};
/** Appropriate scale for each of the stats above */
var statScales = {};
/** Associated axes to above */
var statAxes = {};
/** Array of p-values */
var pvalues =[];
/** Array of absolute value of t-stats */
var tvalues =[];
/** Array of Entropy Values */
var entropies = {full:[],vaccine:[],placebo:[]};
/**  Object with nests of distances for each distance method */
var dists;
/** Datasets available for analysis */
var availableDatasets;
/** Initial values for study name, protein, reference, and distance measure */
var studyname = getParameterByName("study"),
	protein = getParameterByName("protein"),
	reference = getParameterByName("ref"),
	dist_metric = getParameterByName("dist");
if (dist_metric.length < 1) { dist_metric = "vxmatch_site"};

// define object containing all required files' names
var inputFiles = getInputFilenames(studyname, protein, reference, dist_metric);
parseInput(inputFiles);

function parseInput(inputFiles){

d3.csv(inputFiles.treatmentFile, function(assigndata)
{
	parseTreatmentFile(assigndata);
	d3.text(inputFiles.sequenceFastaFile, function(fastadata)
	{
		doseqparsing(fastadata);
		d3.csv(inputFiles.distanceFile, function(distdata)
		{
			dodistparsing(distdata);
			d3.csv(inputFiles.resultsFile, function(resultdata)
			{
				parseResultsFile(resultdata);

				// Transpose data for easier access
				sequences_raw = transpose(sequences_raw);
				sequences.vaccine = transpose(sequences.vaccine);
				sequences.placebo = transpose(sequences.placebo);
				// calculate entropies
				for(var i=0; i < sequences_raw.length; i++){
					entropies.full.push(jointentropy([i],sequences_raw,numvac+numplac).toFixed(2));
				}
				for(var i=0; i < sequences.vaccine.length; i++){
					entropies.vaccine.push(jointentropy([i],sequences.vaccine,numvac).toFixed(2));
				}
				for(var i=0; i < sequences.placebo.length; i++){
					entropies.placebo.push(jointentropy([i],sequences.placebo,numplac).toFixed(2));
				}
				// If loaded URL contains sites, add them to the current selection
				var urlSiteString = getParameterByName("sites");
				if (urlSiteString !== ""){
					// get sites identified by reference strand
					var urlSites = urlSiteString.split(",");
					// convert sites back to 0-based index
					//(our working index instead of the reference index)
					urlSites.forEach(function(d,i){
						urlSites[i] = refmap[urlSites[i]];
					})
					while(urlSites.length > 0){
						var urlsite = urlSites.pop();
						if (typeof urlsite != 'undefined'){ selected_sites.push(urlsite); }
					}
				}

				// Build the visualization
				generateVis();

			});
		});
	});
});
}

function parseTreatmentFile(assigndata){
	seqID_lookup = d3.nest()
		.key(function(d) {return d.ptid;})
		.rollup(function(d) {
			if (d[0].treatment.toUpperCase().startsWith("P")){
				return { "distance": {}, "sequence": [], "vaccine": false };
			} else {
				return { "distance": {}, "sequence": [], "vaccine": true };
			}
		})
		.map(assigndata.filter(function(d){return !d.treatment.toLowerCase().startsWith("ref");}));
}

function doseqparsing(fastadata) {
	var fastaSequences = fastadata.split(/[;>]+/);
	for (var i = 0; i < fastaSequences.length; i++) {
		if (fastaSequences[i].length !== 0) {
			var seqID = fastaSequences[i].substring(0,fastaSequences[i].indexOf("\n")).trim(/[\n\r]/g, '');
			var seq = fastaSequences[i].substring(fastaSequences[i].indexOf("\n") + 1, fastaSequences[i].length);
			seq = seq.replace(/[\n\r]/g, '');
			seq = seq.split("");
			sequences_raw.push(seq);
			if (seqID.startsWith("reference"))
			{
				vaccine.ID = seqID.substring(seqID.lastIndexOf('|')+1, seqID.length);
				vaccine.sequence = seq;
			} else if ((seqID in seqID_lookup) && seqID_lookup[seqID].vaccine) {
				seqID_lookup[seqID].sequence = seq;
				sequences.vaccine.push(seq);
				numvac++;
			} else if (seqID in seqID_lookup) {
				seqID_lookup[seqID].sequence = seq;
				sequences.placebo.push(seq);
				numplac++;
			}
		}
	}
}

function dodistparsing(distdata)
{
	dists = d3.nest()
		.key(function(d) {return d.distance_method;})
		.rollup(function(data)
			{
				return d3.nest()
					.key(function(d) { return d.ptid; })
					.rollup(function(d) { return d.map(function(a) {return a.distance;}); })
					.entries(data);
			})
		.entries(distdata);
	display_idx_map = distdata.filter(function (d)
		{
			return d.ptid == distdata[0].ptid && d.distance_method == distdata[0].distance_method;
		}).map(function(d) {return d.display_position;});
	display_idx_map.forEach(function(d, i) {refmap[d] = i;});

	var distMethodSelector = d3.select("#distMethod_selector");
	dists.forEach(function(d,i){
		var newOption = distMethodSelector.append("option")
			.attr("value", d["key"])
			.attr("id","yscale-selection-option-" + d["key"])
			.text(d["key"]);
		if (i === 0){ newOption.attr("selected","selected"); }
	})
}

function parseResultsFile(resultdata){

	var statsToDisplay = Object.keys(resultdata[0]).filter(function(d,i){ return i > 2; })
	siteStats = d3.nest()
		.key(function(d) {return d.distance_method;})
		.rollup(function(d){
			var result = {};
			for (var statidx in statsToDisplay){
				var stat = statsToDisplay[statidx];
				result[stat] = d.map(function(a){return +a[stat];});
			}
			return result;
		})
		.map(resultdata);

	var yScaleSelector = d3.select("#yscale_selector");
	statsToDisplay.forEach(function(d){
		var newOption = yScaleSelector.append("option")
			.attr("value", d)
			.attr("id","yscale-selection-option-" + d)
			.text(d);
		// hard coded for now. Will data always contain a pvalue?
		// answer is yes if we decide to build in a simple pval generator
		if (d === "pvalue"){ newOption.attr("selected","selected"); }
	})

	for (var metric in siteStats)
	{
		statScales[metric] = {};
		statAxes[metric] = {};

		for (var stat in siteStats[metric])
		{
			//test if the stat name is some variant of
			//p-value or q-value
			if (/^[pq][\s-]?val/i.test(stat))
			{
				statScales[metric][stat] = d3.scale.log()
					.domain([d3.min(siteStats[dist_metric][stat]), 1])
					.range([0, .95*height])
					.nice();
				statAxes[metric][stat] =
					{"left":d3.svg.axis()
						.scale(statScales[metric][stat])
						.orient("left")
						.ticks(5, "g"),
					"right":d3.svg.axis()
						.scale(statScales[metric][stat])
						.orient("right")
						.ticks(5, "g")};
				if (/^p/i.test(stat))
				{ //Try to set the default stat to pvalue
					yscale_mode = stat;
				}
			} else {
				statScales[metric][stat] = d3.scale.linear()
					.range([.95*height, 0])
					.domain([-1,0]);
				statAxes[metric][stat] =
					{"left":d3.svg.axis()
						.scale(statScales[metric][stat])
						.orient("left")
						.ticks(5),
					"right":d3.svg.axis()
						.scale(statScales[metric][stat])
						.orient("right")
						.ticks(5)};
			}
			if (yscale_mode === undefined)
			{ //No pvalue, set stat to arbitrary value
				for (var key in statScales[metric]) break;
				yscale_mode = key;
			}
		}
	}
}

/** Transpose 2D array */
function transpose(array) {
  return array[0].map(function (_, c) { return array.map(function (r) { return r[c]; }); });
}

/**  */
function getInputFilenames(studyname, protein, reference, dist_metric){
	var result = {};
	result.treatmentFile = "../data/treatment.csv?study=" + studyname;
	result.sequenceFastaFile = "../data/alignment.fasta?study=" + studyname + "&protein=" + protein + "&reference=" + reference;
	result.distanceFile = "../data/distance.csv?study=" + studyname + "&protein=" + protein + "&reference=" + reference;
	result.resultsFile = "../data/results.csv?study=" + studyname + "&protein=" + protein + "&ref=" + reference;
	return result;
}
function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
<|endoftext|>


<commit_before>/*
  Polybutton - An accessible version of links that look like buttons
  License: MIT/GPLv2
  Author: Tim Wright, csskarma.com
  Script structure inspired by Scott Jehl's Picturefill
*/

;(function( b ){

  "use strict";

  b.polybutton = function() {

    var btn = b.document.querySelectorAll( "span[data-accessible]" );
    var count = btn.length;
    var i, obj, access, href, type, value, initClass, genBtn;

    // Loop through the polybuttons
    for ( i = 0; i < count; i = i + 1 ) {

      // store some variables
      obj = btn[i];
      href = obj.getAttribute('data-href');
      access = obj.getAttribute('data-accessible');
      type = obj.getAttribute('data-type');
      value = obj.getAttribute('data-value');
      initClass = obj.getAttribute('data-class');

      // make sure we're dealing with a button
      if( access === 'button' ) {

        genBtn = document.createElement( 'button' );

        // build out the new button asset
        genBtn.setAttribute("class", initClass);
        genBtn.setAttribute("type", type);
        genBtn.setAttribute("data-url", href);
        genBtn.innerHTML = value;

        // add the new button into the DOM
        obj.appendChild(genBtn);

        // check to see if we can use addEventListener on the new button, then tie a click event to it
        if( genBtn.addEventListener ) {

          genBtn.addEventListener('click', function(e) {

            window.location = this.getAttribute('data-url');

          }, false);

        } else if( genBtn.attachEvent ) {

          genBtn.attachEvent( "onload", function(e){
            window.location = this.getAttribute('data-url');
          });

        } // end if addEventListener

      } // end if button

    } // end for loop

  }; // end polybutton

  // execute on DOM ready (b.load as a fallback)
  if( b.addEventListener ){

    b.addEventListener( "DOMContentLoaded", function(){

      // execute polybutton
      b.polybutton();

      // only do it once
      b.removeEventListener( "load", b.polybutton, false );

    }, false );

  } else if( b.attachEvent ){

    b.attachEvent( "onload", b.polybutton );

  } // end initial load event

}( this ));<commit_msg>added a button aria role<commit_after>/*
  Polybutton - An accessible version of links that look like buttons
  License: MIT/GPLv2
  Author: Tim Wright, csskarma.com
  Script structure inspired by Scott Jehl's Picturefill
*/

;(function( b ){

  "use strict";

  b.polybutton = function() {

    var btn = b.document.querySelectorAll( "span[data-accessible]" );
    var count = btn.length;
    var i, obj, access, href, type, value, initClass, genBtn;

    // Loop through the polybuttons
    for ( i = 0; i < count; i = i + 1 ) {

      // store some variables
      obj = btn[i];
      href = obj.getAttribute('data-href');
      access = obj.getAttribute('data-accessible');
      type = obj.getAttribute('data-type');
      value = obj.getAttribute('data-value');
      initClass = obj.getAttribute('data-class');

      // make sure we're dealing with a button
      if( access === 'button' ) {

        genBtn = document.createElement( 'button' );

        // build out the new button asset
        genBtn.setAttribute("class", initClass);
        genBtn.setAttribute("type", type);
        genBtn.setAttribute("data-url", href);
        genBtn.setAttribute("role", "button");
        genBtn.innerHTML = value;

        // add the new button into the DOM
        obj.appendChild(genBtn);

        // check to see if we can use addEventListener on the new button, then tie a click event to it
        if( genBtn.addEventListener ) {

          genBtn.addEventListener('click', function(e) {

            window.location = this.getAttribute('data-url');

          }, false);

        } else if( genBtn.attachEvent ) {

          genBtn.attachEvent( "onload", function(e){
            window.location = this.getAttribute('data-url');
          });

        } // end if addEventListener

      } // end if button

    } // end for loop

  }; // end polybutton

  // execute on DOM ready (b.load as a fallback)
  if( b.addEventListener ){

    b.addEventListener( "DOMContentLoaded", function(){

      // execute polybutton
      b.polybutton();

      // only do it once
      b.removeEventListener( "load", b.polybutton, false );

    }, false );

  } else if( b.attachEvent ){

    b.attachEvent( "onload", b.polybutton );

  } // end initial load event

}( this ));<|endoftext|>


<commit_before>const childProcess = require('child_process')
const fs = require('fs')
const path = require('path')
const electronLink = require('electron-link')
const CONFIG = require('../config')

module.exports = function (packagedAppPath) {
  const snapshotScriptPath = path.join(CONFIG.buildOutputPath, 'startup.js')
  const coreModules = new Set(['electron', 'atom', 'shell', 'WNdb', 'lapack', 'remote'])
  const baseDirPath = path.join(CONFIG.intermediateAppPath, 'static')
  let processedFiles = 0

  return electronLink({
    baseDirPath,
    mainPath: path.resolve(baseDirPath, '..', 'src', 'initialize-application-window.js'),
    cachePath: path.join(CONFIG.atomHomeDirPath, 'snapshot-cache'),
    auxiliaryData: CONFIG.snapshotAuxiliaryData,
    shouldExcludeModule: (modulePath) => {
      if (processedFiles > 0) {
        process.stdout.write('\r')
      }
      process.stdout.write(`Generating snapshot script at "${snapshotScriptPath}" (${++processedFiles})`)

      const relativePath = path.relative(baseDirPath, modulePath)
      return (
        modulePath.endsWith('.node') ||
        coreModules.has(modulePath) ||
        (relativePath.startsWith(path.join('..', 'src')) && relativePath.endsWith('-element.js')) ||
        relativePath.startsWith(path.join('..', 'node_modules', 'dugite')) ||
        relativePath === path.join('..', 'exports', 'atom.js') ||
        relativePath === path.join('..', 'src', 'electron-shims.js') ||
        relativePath === path.join('..', 'src', 'safe-clipboard.js') ||
        relativePath === path.join('..', 'node_modules', 'atom-keymap', 'lib', 'command-event.js') ||
        relativePath === path.join('..', 'node_modules', 'babel-core', 'index.js') ||
        relativePath === path.join('..', 'node_modules', 'cached-run-in-this-context', 'lib', 'main.js') ||
        relativePath === path.join('..', 'node_modules', 'coffee-script', 'lib', 'coffee-script', 'register.js') ||
        relativePath === path.join('..', 'node_modules', 'cson-parser', 'node_modules', 'coffee-script', 'lib', 'coffee-script', 'register.js') ||
        relativePath === path.join('..', 'node_modules', 'decompress-zip', 'lib', 'decompress-zip.js') ||
        relativePath === path.join('..', 'node_modules', 'debug', 'node.js') ||
        relativePath === path.join('..', 'node_modules', 'fs-extra', 'lib', 'index.js') ||
        relativePath === path.join('..', 'node_modules', 'github', 'node_modules', 'fs-extra', 'lib', 'index.js') ||
        relativePath === path.join('..', 'node_modules', 'git-utils', 'lib', 'git.js') ||
        relativePath === path.join('..', 'node_modules', 'glob', 'glob.js') ||
        relativePath === path.join('..', 'node_modules', 'graceful-fs', 'graceful-fs.js') ||
        relativePath === path.join('..', 'node_modules', 'htmlparser2', 'lib', 'index.js') ||
        relativePath === path.join('..', 'node_modules', 'markdown-preview', 'node_modules', 'htmlparser2', 'lib', 'index.js') ||
        relativePath === path.join('..', 'node_modules', 'roaster', 'node_modules', 'htmlparser2', 'lib', 'index.js') ||
        relativePath === path.join('..', 'node_modules', 'task-lists', 'node_modules', 'htmlparser2', 'lib', 'index.js') ||
        relativePath === path.join('..', 'node_modules', 'iconv-lite', 'lib', 'index.js') ||
        relativePath === path.join('..', 'node_modules', 'less', 'index.js') ||
        relativePath === path.join('..', 'node_modules', 'less', 'lib', 'less', 'fs.js') ||
        relativePath === path.join('..', 'node_modules', 'less', 'lib', 'less-node', 'index.js') ||
        relativePath === path.join('..', 'node_modules', 'less', 'node_modules', 'graceful-fs', 'graceful-fs.js') ||
        relativePath === path.join('..', 'node_modules', 'minimatch', 'minimatch.js') ||
        relativePath === path.join('..', 'node_modules', 'node-fetch', 'lib', 'fetch-error.js') ||
        relativePath === path.join('..', 'node_modules', 'nsfw', 'node_modules', 'fs-extra', 'lib', 'index.js') ||
        relativePath === path.join('..', 'node_modules', 'superstring', 'index.js') ||
        relativePath === path.join('..', 'node_modules', 'oniguruma', 'src', 'oniguruma.js') ||
        relativePath === path.join('..', 'node_modules', 'request', 'index.js') ||
        relativePath === path.join('..', 'node_modules', 'resolve', 'index.js') ||
        relativePath === path.join('..', 'node_modules', 'resolve', 'lib', 'core.js') ||
        relativePath === path.join('..', 'node_modules', 'scandal', 'node_modules', 'minimatch', 'minimatch.js') ||
        relativePath === path.join('..', 'node_modules', 'settings-view', 'node_modules', 'glob', 'glob.js') ||
        relativePath === path.join('..', 'node_modules', 'settings-view', 'node_modules', 'minimatch', 'minimatch.js') ||
        relativePath === path.join('..', 'node_modules', 'spellchecker', 'lib', 'spellchecker.js') ||
        relativePath === path.join('..', 'node_modules', 'spelling-manager', 'node_modules', 'natural', 'lib', 'natural', 'index.js') ||
        relativePath === path.join('..', 'node_modules', 'tar', 'tar.js') ||
        relativePath === path.join('..', 'node_modules', 'temp', 'lib', 'temp.js') ||
        relativePath === path.join('..', 'node_modules', 'tmp', 'lib', 'tmp.js') ||
        relativePath === path.join('..', 'node_modules', 'tree-view', 'node_modules', 'minimatch', 'minimatch.js')
      )
    }
  }).then((snapshotScript) => {
    fs.writeFileSync(snapshotScriptPath, snapshotScript)
    process.stdout.write('\n')

    console.log('Verifying if snapshot can be executed via `mksnapshot`')
    const verifySnapshotScriptPath = path.join(CONFIG.repositoryRootPath, 'script', 'verify-snapshot-script')
    let nodeBundledInElectronPath
    if (process.platform === 'darwin') {
      nodeBundledInElectronPath = path.join(packagedAppPath, 'Contents', 'MacOS', 'Atom')
    } else if (process.platform === 'win32') {
      nodeBundledInElectronPath = path.join(packagedAppPath, 'atom.exe')
    } else {
      nodeBundledInElectronPath = path.join(packagedAppPath, 'atom')
    }
    childProcess.execFileSync(
      nodeBundledInElectronPath,
      [verifySnapshotScriptPath, snapshotScriptPath],
      {env: Object.assign({}, process.env, {ELECTRON_RUN_AS_NODE: 1})}
    )

    const generatedStartupBlobPath = path.join(CONFIG.buildOutputPath, 'snapshot_blob.bin')
    console.log(`Generating startup blob at "${generatedStartupBlobPath}"`)
    childProcess.execFileSync(
      path.join(CONFIG.repositoryRootPath, 'script', 'node_modules', 'electron-mksnapshot', 'bin', 'mksnapshot'),
      [snapshotScriptPath, '--startup_blob', generatedStartupBlobPath]
    )

    let startupBlobDestinationPath
    if (process.platform === 'darwin') {
      startupBlobDestinationPath = `${packagedAppPath}/Contents/Frameworks/Electron Framework.framework/Resources/snapshot_blob.bin`
    } else {
      startupBlobDestinationPath = path.join(packagedAppPath, 'snapshot_blob.bin')
    }

    console.log(`Moving generated startup blob into "${startupBlobDestinationPath}"`)
    fs.unlinkSync(startupBlobDestinationPath)
    fs.renameSync(generatedStartupBlobPath, startupBlobDestinationPath)
  })
}
<commit_msg>Use the Atom Beta executable to verify startup snapshots when building Beta<commit_after>const childProcess = require('child_process')
const fs = require('fs')
const path = require('path')
const electronLink = require('electron-link')
const CONFIG = require('../config')

module.exports = function (packagedAppPath) {
  const snapshotScriptPath = path.join(CONFIG.buildOutputPath, 'startup.js')
  const coreModules = new Set(['electron', 'atom', 'shell', 'WNdb', 'lapack', 'remote'])
  const baseDirPath = path.join(CONFIG.intermediateAppPath, 'static')
  let processedFiles = 0

  return electronLink({
    baseDirPath,
    mainPath: path.resolve(baseDirPath, '..', 'src', 'initialize-application-window.js'),
    cachePath: path.join(CONFIG.atomHomeDirPath, 'snapshot-cache'),
    auxiliaryData: CONFIG.snapshotAuxiliaryData,
    shouldExcludeModule: (modulePath) => {
      if (processedFiles > 0) {
        process.stdout.write('\r')
      }
      process.stdout.write(`Generating snapshot script at "${snapshotScriptPath}" (${++processedFiles})`)

      const relativePath = path.relative(baseDirPath, modulePath)
      return (
        modulePath.endsWith('.node') ||
        coreModules.has(modulePath) ||
        (relativePath.startsWith(path.join('..', 'src')) && relativePath.endsWith('-element.js')) ||
        relativePath.startsWith(path.join('..', 'node_modules', 'dugite')) ||
        relativePath === path.join('..', 'exports', 'atom.js') ||
        relativePath === path.join('..', 'src', 'electron-shims.js') ||
        relativePath === path.join('..', 'src', 'safe-clipboard.js') ||
        relativePath === path.join('..', 'node_modules', 'atom-keymap', 'lib', 'command-event.js') ||
        relativePath === path.join('..', 'node_modules', 'babel-core', 'index.js') ||
        relativePath === path.join('..', 'node_modules', 'cached-run-in-this-context', 'lib', 'main.js') ||
        relativePath === path.join('..', 'node_modules', 'coffee-script', 'lib', 'coffee-script', 'register.js') ||
        relativePath === path.join('..', 'node_modules', 'cson-parser', 'node_modules', 'coffee-script', 'lib', 'coffee-script', 'register.js') ||
        relativePath === path.join('..', 'node_modules', 'decompress-zip', 'lib', 'decompress-zip.js') ||
        relativePath === path.join('..', 'node_modules', 'debug', 'node.js') ||
        relativePath === path.join('..', 'node_modules', 'fs-extra', 'lib', 'index.js') ||
        relativePath === path.join('..', 'node_modules', 'github', 'node_modules', 'fs-extra', 'lib', 'index.js') ||
        relativePath === path.join('..', 'node_modules', 'git-utils', 'lib', 'git.js') ||
        relativePath === path.join('..', 'node_modules', 'glob', 'glob.js') ||
        relativePath === path.join('..', 'node_modules', 'graceful-fs', 'graceful-fs.js') ||
        relativePath === path.join('..', 'node_modules', 'htmlparser2', 'lib', 'index.js') ||
        relativePath === path.join('..', 'node_modules', 'markdown-preview', 'node_modules', 'htmlparser2', 'lib', 'index.js') ||
        relativePath === path.join('..', 'node_modules', 'roaster', 'node_modules', 'htmlparser2', 'lib', 'index.js') ||
        relativePath === path.join('..', 'node_modules', 'task-lists', 'node_modules', 'htmlparser2', 'lib', 'index.js') ||
        relativePath === path.join('..', 'node_modules', 'iconv-lite', 'lib', 'index.js') ||
        relativePath === path.join('..', 'node_modules', 'less', 'index.js') ||
        relativePath === path.join('..', 'node_modules', 'less', 'lib', 'less', 'fs.js') ||
        relativePath === path.join('..', 'node_modules', 'less', 'lib', 'less-node', 'index.js') ||
        relativePath === path.join('..', 'node_modules', 'less', 'node_modules', 'graceful-fs', 'graceful-fs.js') ||
        relativePath === path.join('..', 'node_modules', 'minimatch', 'minimatch.js') ||
        relativePath === path.join('..', 'node_modules', 'node-fetch', 'lib', 'fetch-error.js') ||
        relativePath === path.join('..', 'node_modules', 'nsfw', 'node_modules', 'fs-extra', 'lib', 'index.js') ||
        relativePath === path.join('..', 'node_modules', 'superstring', 'index.js') ||
        relativePath === path.join('..', 'node_modules', 'oniguruma', 'src', 'oniguruma.js') ||
        relativePath === path.join('..', 'node_modules', 'request', 'index.js') ||
        relativePath === path.join('..', 'node_modules', 'resolve', 'index.js') ||
        relativePath === path.join('..', 'node_modules', 'resolve', 'lib', 'core.js') ||
        relativePath === path.join('..', 'node_modules', 'scandal', 'node_modules', 'minimatch', 'minimatch.js') ||
        relativePath === path.join('..', 'node_modules', 'settings-view', 'node_modules', 'glob', 'glob.js') ||
        relativePath === path.join('..', 'node_modules', 'settings-view', 'node_modules', 'minimatch', 'minimatch.js') ||
        relativePath === path.join('..', 'node_modules', 'spellchecker', 'lib', 'spellchecker.js') ||
        relativePath === path.join('..', 'node_modules', 'spelling-manager', 'node_modules', 'natural', 'lib', 'natural', 'index.js') ||
        relativePath === path.join('..', 'node_modules', 'tar', 'tar.js') ||
        relativePath === path.join('..', 'node_modules', 'temp', 'lib', 'temp.js') ||
        relativePath === path.join('..', 'node_modules', 'tmp', 'lib', 'tmp.js') ||
        relativePath === path.join('..', 'node_modules', 'tree-view', 'node_modules', 'minimatch', 'minimatch.js')
      )
    }
  }).then((snapshotScript) => {
    fs.writeFileSync(snapshotScriptPath, snapshotScript)
    process.stdout.write('\n')

    console.log('Verifying if snapshot can be executed via `mksnapshot`')
    const verifySnapshotScriptPath = path.join(CONFIG.repositoryRootPath, 'script', 'verify-snapshot-script')
    let nodeBundledInElectronPath
    if (process.platform === 'darwin') {
      const executableName = CONFIG.channel === 'beta' ? 'Atom Beta' : 'Atom'
      nodeBundledInElectronPath = path.join(packagedAppPath, 'Contents', 'MacOS', executableName)
    } else if (process.platform === 'win32') {
      nodeBundledInElectronPath = path.join(packagedAppPath, 'atom.exe')
    } else {
      nodeBundledInElectronPath = path.join(packagedAppPath, 'atom')
    }
    childProcess.execFileSync(
      nodeBundledInElectronPath,
      [verifySnapshotScriptPath, snapshotScriptPath],
      {env: Object.assign({}, process.env, {ELECTRON_RUN_AS_NODE: 1})}
    )

    const generatedStartupBlobPath = path.join(CONFIG.buildOutputPath, 'snapshot_blob.bin')
    console.log(`Generating startup blob at "${generatedStartupBlobPath}"`)
    childProcess.execFileSync(
      path.join(CONFIG.repositoryRootPath, 'script', 'node_modules', 'electron-mksnapshot', 'bin', 'mksnapshot'),
      [snapshotScriptPath, '--startup_blob', generatedStartupBlobPath]
    )

    let startupBlobDestinationPath
    if (process.platform === 'darwin') {
      startupBlobDestinationPath = `${packagedAppPath}/Contents/Frameworks/Electron Framework.framework/Resources/snapshot_blob.bin`
    } else {
      startupBlobDestinationPath = path.join(packagedAppPath, 'snapshot_blob.bin')
    }

    console.log(`Moving generated startup blob into "${startupBlobDestinationPath}"`)
    fs.unlinkSync(startupBlobDestinationPath)
    fs.renameSync(generatedStartupBlobPath, startupBlobDestinationPath)
  })
}
<|endoftext|>


<commit_before>const childProcess = require('child_process')
const fs = require('fs')
const path = require('path')
const electronLink = require('electron-link')
const terser = require('terser')
const CONFIG = require('../config')

module.exports = function (packagedAppPath) {
  const snapshotScriptPath = path.join(CONFIG.buildOutputPath, 'startup.js')
  const coreModules = new Set(['electron', 'atom', 'shell', 'WNdb', 'lapack', 'remote'])
  const baseDirPath = path.join(CONFIG.intermediateAppPath, 'static')
  let processedFiles = 0

  return electronLink({
    baseDirPath,
    mainPath: path.resolve(baseDirPath, '..', 'src', 'initialize-application-window.js'),
    cachePath: path.join(CONFIG.atomHomeDirPath, 'snapshot-cache'),
    auxiliaryData: CONFIG.snapshotAuxiliaryData,
    shouldExcludeModule: ({requiringModulePath, requiredModulePath}) => {
      if (processedFiles > 0) {
        process.stdout.write('\r')
      }
      process.stdout.write(`Generating snapshot script at "${snapshotScriptPath}" (${++processedFiles})`)

      const requiringModuleRelativePath = path.relative(baseDirPath, requiringModulePath)
      const requiredModuleRelativePath = path.relative(baseDirPath, requiredModulePath)
      return (
        requiredModulePath.endsWith('.node') ||
        coreModules.has(requiredModulePath) ||
        requiringModuleRelativePath.endsWith(path.join('node_modules/xregexp/xregexp-all.js')) ||
        (requiredModuleRelativePath.startsWith(path.join('..', 'src')) && requiredModuleRelativePath.endsWith('-element.js')) ||
        requiredModuleRelativePath.startsWith(path.join('..', 'node_modules', 'dugite')) ||
        requiredModuleRelativePath.startsWith(path.join('..', 'node_modules', 'markdown-preview', 'node_modules', 'yaml-front-matter')) ||
        requiredModuleRelativePath.startsWith(path.join('..', 'node_modules', 'markdown-preview', 'node_modules', 'cheerio')) ||
        requiredModuleRelativePath.startsWith(path.join('..', 'node_modules', 'markdown-preview', 'node_modules', 'marked')) ||
        requiredModuleRelativePath.startsWith(path.join('..', 'node_modules', 'typescript-simple')) ||
        requiredModuleRelativePath.endsWith(path.join('node_modules', 'coffee-script', 'lib', 'coffee-script', 'register.js')) ||
        requiredModuleRelativePath.endsWith(path.join('node_modules', 'fs-extra', 'lib', 'index.js')) ||
        requiredModuleRelativePath.endsWith(path.join('node_modules', 'graceful-fs', 'graceful-fs.js')) ||
        requiredModuleRelativePath.endsWith(path.join('node_modules', 'htmlparser2', 'lib', 'index.js')) ||
        requiredModuleRelativePath.endsWith(path.join('node_modules', 'minimatch', 'minimatch.js')) ||
        requiredModuleRelativePath.endsWith(path.join('node_modules', 'request', 'index.js')) ||
        requiredModuleRelativePath.endsWith(path.join('node_modules', 'request', 'request.js')) ||
        requiredModuleRelativePath.endsWith(path.join('node_modules', 'superstring', 'index.js')) ||
        requiredModuleRelativePath.endsWith(path.join('node_modules', 'temp', 'lib', 'temp.js')) ||
        requiredModuleRelativePath === path.join('..', 'exports', 'atom.js') ||
        requiredModuleRelativePath === path.join('..', 'src', 'electron-shims.js') ||
        requiredModuleRelativePath === path.join('..', 'node_modules', 'atom-keymap', 'lib', 'command-event.js') ||
        requiredModuleRelativePath === path.join('..', 'node_modules', 'babel-core', 'index.js') ||
        requiredModuleRelativePath === path.join('..', 'node_modules', 'cached-run-in-this-context', 'lib', 'main.js') ||
        requiredModuleRelativePath === path.join('..', 'node_modules', 'debug', 'node.js') ||
        requiredModuleRelativePath === path.join('..', 'node_modules', 'git-utils', 'src', 'git.js') ||
        requiredModuleRelativePath === path.join('..', 'node_modules', 'glob', 'glob.js') ||
        requiredModuleRelativePath === path.join('..', 'node_modules', 'iconv-lite', 'lib', 'index.js') ||
        requiredModuleRelativePath === path.join('..', 'node_modules', 'less', 'index.js') ||
        requiredModuleRelativePath === path.join('..', 'node_modules', 'less', 'lib', 'less', 'fs.js') ||
        requiredModuleRelativePath === path.join('..', 'node_modules', 'less', 'lib', 'less-node', 'index.js') ||
        requiredModuleRelativePath === path.join('..', 'node_modules', 'lodash.isequal', 'index.js') ||
        requiredModuleRelativePath === path.join('..', 'node_modules', 'node-fetch', 'lib', 'fetch-error.js') ||
        requiredModuleRelativePath === path.join('..', 'node_modules', 'oniguruma', 'src', 'oniguruma.js') ||
        requiredModuleRelativePath === path.join('..', 'node_modules', 'resolve', 'index.js') ||
        requiredModuleRelativePath === path.join('..', 'node_modules', 'resolve', 'lib', 'core.js') ||
        requiredModuleRelativePath === path.join('..', 'node_modules', 'settings-view', 'node_modules', 'glob', 'glob.js') ||
        requiredModuleRelativePath === path.join('..', 'node_modules', 'spellchecker', 'lib', 'spellchecker.js') ||
        requiredModuleRelativePath === path.join('..', 'node_modules', 'spelling-manager', 'node_modules', 'natural', 'lib', 'natural', 'index.js') ||
        requiredModuleRelativePath === path.join('..', 'node_modules', 'tar', 'tar.js') ||
        requiredModuleRelativePath === path.join('..', 'node_modules', 'ls-archive', 'node_modules', 'tar', 'tar.js') ||
        requiredModuleRelativePath === path.join('..', 'node_modules', 'tmp', 'lib', 'tmp.js') ||
        requiredModuleRelativePath === path.join('..', 'node_modules', 'tree-sitter', 'index.js') ||
        requiredModuleRelativePath === path.join('..', 'node_modules', 'yauzl', 'index.js') ||
        requiredModuleRelativePath === path.join('..', 'node_modules', 'winreg', 'lib', 'registry.js') ||
        requiredModuleRelativePath === path.join('..', 'node_modules', '@atom', 'fuzzy-native', 'lib', 'main.js') ||
        // The startup-time script is used by both the renderer and the main process and having it in the
        // snapshot causes issues.
        requiredModuleRelativePath === path.join('..', 'src', 'startup-time.js')
      )
    }
  }).then(({snapshotScript}) => {
    process.stdout.write('\n')

    process.stdout.write('Minifying startup script')
    const minification = terser.minify(snapshotScript, {
      keep_fnames: true,
      keep_classnames: true,
      compress: {keep_fargs: true, keep_infinity: true}
    })
    if (minification.error) throw minification.error
    process.stdout.write('\n')
    fs.writeFileSync(snapshotScriptPath, minification.code)

    console.log('Verifying if snapshot can be executed via `mksnapshot`')
    const verifySnapshotScriptPath = path.join(CONFIG.repositoryRootPath, 'script', 'verify-snapshot-script')
    let nodeBundledInElectronPath
    if (process.platform === 'darwin') {
      const executableName = CONFIG.appName
      nodeBundledInElectronPath = path.join(packagedAppPath, 'Contents', 'MacOS', executableName)
    } else if (process.platform === 'win32') {
      nodeBundledInElectronPath = path.join(packagedAppPath, 'atom.exe')
    } else {
      nodeBundledInElectronPath = path.join(packagedAppPath, 'atom')
    }
    childProcess.execFileSync(
      nodeBundledInElectronPath,
      [verifySnapshotScriptPath, snapshotScriptPath],
      {env: Object.assign({}, process.env, {ELECTRON_RUN_AS_NODE: 1})}
    )

    const generatedStartupBlobPath = path.join(CONFIG.buildOutputPath, 'snapshot_blob.bin')
    console.log(`Generating startup blob at "${generatedStartupBlobPath}"`)
    childProcess.execFileSync(
      path.join(CONFIG.repositoryRootPath, 'script', 'node_modules', 'electron-mksnapshot', 'bin', 'mksnapshot'),
      ['--no-use_ic', snapshotScriptPath, '--startup_blob', generatedStartupBlobPath]
    )

    let startupBlobDestinationPath
    if (process.platform === 'darwin') {
      startupBlobDestinationPath = `${packagedAppPath}/Contents/Frameworks/Electron Framework.framework/Resources/snapshot_blob.bin`
    } else {
      startupBlobDestinationPath = path.join(packagedAppPath, 'snapshot_blob.bin')
    }

    console.log(`Moving generated startup blob into "${startupBlobDestinationPath}"`)
    fs.unlinkSync(startupBlobDestinationPath)
    fs.renameSync(generatedStartupBlobPath, startupBlobDestinationPath)
  })
}
<commit_msg>Update snapshot path from snapshot_blob to v8_context_snapshot<commit_after>const childProcess = require('child_process')
const fs = require('fs')
const path = require('path')
const electronLink = require('electron-link')
const terser = require('terser')
const CONFIG = require('../config')

module.exports = function (packagedAppPath) {
  const snapshotScriptPath = path.join(CONFIG.buildOutputPath, 'startup.js')
  const coreModules = new Set(['electron', 'atom', 'shell', 'WNdb', 'lapack', 'remote'])
  const baseDirPath = path.join(CONFIG.intermediateAppPath, 'static')
  let processedFiles = 0

  return electronLink({
    baseDirPath,
    mainPath: path.resolve(baseDirPath, '..', 'src', 'initialize-application-window.js'),
    cachePath: path.join(CONFIG.atomHomeDirPath, 'snapshot-cache'),
    auxiliaryData: CONFIG.snapshotAuxiliaryData,
    shouldExcludeModule: ({requiringModulePath, requiredModulePath}) => {
      if (processedFiles > 0) {
        process.stdout.write('\r')
      }
      process.stdout.write(`Generating snapshot script at "${snapshotScriptPath}" (${++processedFiles})`)

      const requiringModuleRelativePath = path.relative(baseDirPath, requiringModulePath)
      const requiredModuleRelativePath = path.relative(baseDirPath, requiredModulePath)
      return (
        requiredModulePath.endsWith('.node') ||
        coreModules.has(requiredModulePath) ||
        requiringModuleRelativePath.endsWith(path.join('node_modules/xregexp/xregexp-all.js')) ||
        (requiredModuleRelativePath.startsWith(path.join('..', 'src')) && requiredModuleRelativePath.endsWith('-element.js')) ||
        requiredModuleRelativePath.startsWith(path.join('..', 'node_modules', 'dugite')) ||
        requiredModuleRelativePath.startsWith(path.join('..', 'node_modules', 'markdown-preview', 'node_modules', 'yaml-front-matter')) ||
        requiredModuleRelativePath.startsWith(path.join('..', 'node_modules', 'markdown-preview', 'node_modules', 'cheerio')) ||
        requiredModuleRelativePath.startsWith(path.join('..', 'node_modules', 'markdown-preview', 'node_modules', 'marked')) ||
        requiredModuleRelativePath.startsWith(path.join('..', 'node_modules', 'typescript-simple')) ||
        requiredModuleRelativePath.endsWith(path.join('node_modules', 'coffee-script', 'lib', 'coffee-script', 'register.js')) ||
        requiredModuleRelativePath.endsWith(path.join('node_modules', 'fs-extra', 'lib', 'index.js')) ||
        requiredModuleRelativePath.endsWith(path.join('node_modules', 'graceful-fs', 'graceful-fs.js')) ||
        requiredModuleRelativePath.endsWith(path.join('node_modules', 'htmlparser2', 'lib', 'index.js')) ||
        requiredModuleRelativePath.endsWith(path.join('node_modules', 'minimatch', 'minimatch.js')) ||
        requiredModuleRelativePath.endsWith(path.join('node_modules', 'request', 'index.js')) ||
        requiredModuleRelativePath.endsWith(path.join('node_modules', 'request', 'request.js')) ||
        requiredModuleRelativePath.endsWith(path.join('node_modules', 'superstring', 'index.js')) ||
        requiredModuleRelativePath.endsWith(path.join('node_modules', 'temp', 'lib', 'temp.js')) ||
        requiredModuleRelativePath === path.join('..', 'exports', 'atom.js') ||
        requiredModuleRelativePath === path.join('..', 'src', 'electron-shims.js') ||
        requiredModuleRelativePath === path.join('..', 'node_modules', 'atom-keymap', 'lib', 'command-event.js') ||
        requiredModuleRelativePath === path.join('..', 'node_modules', 'babel-core', 'index.js') ||
        requiredModuleRelativePath === path.join('..', 'node_modules', 'cached-run-in-this-context', 'lib', 'main.js') ||
        requiredModuleRelativePath === path.join('..', 'node_modules', 'debug', 'node.js') ||
        requiredModuleRelativePath === path.join('..', 'node_modules', 'git-utils', 'src', 'git.js') ||
        requiredModuleRelativePath === path.join('..', 'node_modules', 'glob', 'glob.js') ||
        requiredModuleRelativePath === path.join('..', 'node_modules', 'iconv-lite', 'lib', 'index.js') ||
        requiredModuleRelativePath === path.join('..', 'node_modules', 'less', 'index.js') ||
        requiredModuleRelativePath === path.join('..', 'node_modules', 'less', 'lib', 'less', 'fs.js') ||
        requiredModuleRelativePath === path.join('..', 'node_modules', 'less', 'lib', 'less-node', 'index.js') ||
        requiredModuleRelativePath === path.join('..', 'node_modules', 'lodash.isequal', 'index.js') ||
        requiredModuleRelativePath === path.join('..', 'node_modules', 'node-fetch', 'lib', 'fetch-error.js') ||
        requiredModuleRelativePath === path.join('..', 'node_modules', 'oniguruma', 'src', 'oniguruma.js') ||
        requiredModuleRelativePath === path.join('..', 'node_modules', 'resolve', 'index.js') ||
        requiredModuleRelativePath === path.join('..', 'node_modules', 'resolve', 'lib', 'core.js') ||
        requiredModuleRelativePath === path.join('..', 'node_modules', 'settings-view', 'node_modules', 'glob', 'glob.js') ||
        requiredModuleRelativePath === path.join('..', 'node_modules', 'spellchecker', 'lib', 'spellchecker.js') ||
        requiredModuleRelativePath === path.join('..', 'node_modules', 'spelling-manager', 'node_modules', 'natural', 'lib', 'natural', 'index.js') ||
        requiredModuleRelativePath === path.join('..', 'node_modules', 'tar', 'tar.js') ||
        requiredModuleRelativePath === path.join('..', 'node_modules', 'ls-archive', 'node_modules', 'tar', 'tar.js') ||
        requiredModuleRelativePath === path.join('..', 'node_modules', 'tmp', 'lib', 'tmp.js') ||
        requiredModuleRelativePath === path.join('..', 'node_modules', 'tree-sitter', 'index.js') ||
        requiredModuleRelativePath === path.join('..', 'node_modules', 'yauzl', 'index.js') ||
        requiredModuleRelativePath === path.join('..', 'node_modules', 'winreg', 'lib', 'registry.js') ||
        requiredModuleRelativePath === path.join('..', 'node_modules', '@atom', 'fuzzy-native', 'lib', 'main.js') ||
        // The startup-time script is used by both the renderer and the main process and having it in the
        // snapshot causes issues.
        requiredModuleRelativePath === path.join('..', 'src', 'startup-time.js')
      )
    }
  }).then(({snapshotScript}) => {
    process.stdout.write('\n')

    process.stdout.write('Minifying startup script')
    const minification = terser.minify(snapshotScript, {
      keep_fnames: true,
      keep_classnames: true,
      compress: {keep_fargs: true, keep_infinity: true}
    })
    if (minification.error) throw minification.error
    process.stdout.write('\n')
    fs.writeFileSync(snapshotScriptPath, minification.code)

    console.log('Verifying if snapshot can be executed via `mksnapshot`')
    const verifySnapshotScriptPath = path.join(CONFIG.repositoryRootPath, 'script', 'verify-snapshot-script')
    let nodeBundledInElectronPath
    if (process.platform === 'darwin') {
      const executableName = CONFIG.appName
      nodeBundledInElectronPath = path.join(packagedAppPath, 'Contents', 'MacOS', executableName)
    } else if (process.platform === 'win32') {
      nodeBundledInElectronPath = path.join(packagedAppPath, 'atom.exe')
    } else {
      nodeBundledInElectronPath = path.join(packagedAppPath, 'atom')
    }
    childProcess.execFileSync(
      nodeBundledInElectronPath,
      [verifySnapshotScriptPath, snapshotScriptPath],
      {env: Object.assign({}, process.env, {ELECTRON_RUN_AS_NODE: 1})}
    )

    const generatedStartupBlobPath = path.join(CONFIG.buildOutputPath, 'v8_context_snapshot.bin')
    console.log(`Generating startup blob at "${generatedStartupBlobPath}"`)
    childProcess.execFileSync(
      path.join(CONFIG.repositoryRootPath, 'script', 'node_modules', 'electron-mksnapshot', 'bin', 'mksnapshot'),
      ['--no-use_ic', snapshotScriptPath, '--startup_blob', generatedStartupBlobPath]
    )

    let startupBlobDestinationPath
    if (process.platform === 'darwin') {
      startupBlobDestinationPath = `${packagedAppPath}/Contents/Frameworks/Electron Framework.framework/Resources/v8_context_snapshot.bin`
    } else {
      startupBlobDestinationPath = path.join(packagedAppPath, 'v8_context_snapshot.bin')
    }

    console.log(`Moving generated startup blob into "${startupBlobDestinationPath}"`)
    fs.unlinkSync(startupBlobDestinationPath)
    fs.renameSync(generatedStartupBlobPath, startupBlobDestinationPath)
  })
}
<|endoftext|>


<commit_before>/**
 * The grid view.
 */

'use strict';

define(
    [
        'collections/settings',
        'hbs!templates/grid',
        'jquery',
        'backbone',
        'imagesloaded',
        'jquery.magnific-popup'
    ], function(settings, template, $, Backbone) {

        var Grid = Backbone.View.extend({

            template: template,

            events: {
                'touchstart': 'touchstartHandler',
                'mousewheel': 'mousewheelHandler',
                'DOMMouseScroll': 'domMouseScrollHandler',
                'click .shot a': 'clickShotHandler'
            },

            touched: false,

            /**
             * Initialize the grid view.
             */
            initialize: function() {
                this.el = $(this.el);
                this.render();
                this.$queue = 0;
                this.resize();
                this.bindEvents();
                this.startTimers();
            },

            /**
             * Render this view.
             */
            render: function() {
                this.el.html(this.template());
                this.$wrapper = this.$('.grid-wrapper');
                this.$grid = this.$('.grid');
                this.$header = this.$('header');
                this.$footer = this.$('footer');
                this.$prev = this.$('.prev');
                this.$next = this.$('.next');
            },

            /**
             * Add an element to the grid.
             *
             * @param html mixed The element to add.
             */
            add: function(html) {
                this.$queue++;
                var when = $(html).imagesLoaded(function() {
                    --this.$queue;
                    if (!this.$queue) {
                        this.trigger('complete');
                    }
                }.bind(this));

                when.done(function() {
                    this.prepend(html);
                }.bind(this));
            },

            /**
             * Return all columns available.
             */
            cols: function() {
                return this.el.find('.col:visible');
            },

            /**
             * Resize the view.
             */
            resize: function() {
                if (this.touched) {
                    return; // Nothing to do here.
                }
                // The following line should not be there.
                this.el.height($(window).height() - (this.el.outerHeight(true) - this.el.height()));
                this.$wrapper.height(this.el.height());
                this.$footer.css('top', this.el.height() - this.$footer.height());
            },

            /**
             * Prepend an element to the view.
             */
            prepend: function(html) {
                var cols = this.cols();
                var col = cols.first();
                cols.each(function() {
                    var $this = $(this);
                    col = col.children().length <= $this.children().length ? col : $this;
                });
                col.prepend(html);
            },

            /**
             * Move the grid to make the next row visible.
             */
            next: function() {
                var rowHeight = this.rowHeight();
                var remaining = this.$grid.height() - this.el.height() + (parseInt(this.$grid.css('top'), 10) || 0);
                if (remaining > rowHeight) {
                    this.$grid.css('top', '-=' + rowHeight);
                } else {
                    this.$grid.css('top', (this.el.height() - this.$grid.height()));
                }
            },

            /**
             * Move the grid to make the previous row visible.
             */
            prev: function() {
                var rowHeight = this.rowHeight();
                var remaining = -parseInt(this.$grid.css('top'), 10) || 0;
                var inperfections = (remaining % rowHeight);
                if (inperfections) {
                    this.$grid.css('top', '+=' + inperfections);
                    this.$lastRow = false;
                } else if (remaining > rowHeight) {
                    this.$grid.css('top', '+=' + rowHeight);
                } else {
                    this.$grid.css('top', 0);
                }
            },

            /**
             * Return the virtual row height.
             */
            rowHeight: function() {
                var children = this.cols().first().children();
                if (children.length >= 2) {
                    return children.eq(1).offset().top - children.eq(0).offset().top;
                }
                return 0;
            },

            /**
             * Refresh arrows visibility state.
             */
            refresh: function() {
                if (settings.value('grid_controls')) {
                    var top = parseInt(this.$grid.css('top'), 10);
                    if (top === 0) {
                        this.$header.hide();
                    } else {
                        this.$header.show();
                    }
                    var remaining = this.$grid.height() - this.el.height() + top;
                    if (remaining > 0) {
                        this.$footer.show();
                    } else {
                        this.$footer.hide();
                    }
                }
            },

            /**
             * Bind events.
             */
            bindEvents: function() {
                this.listenTo(this.$prev, 'click', function(event) {
                    event.preventDefault();
                    this.prev();
                }.bind(this));

                this.listenTo(this.$next, 'click', function(event) {
                    event.preventDefault();
                    this.next();
                }.bind(this));
            },

            startTimers: function() {
                setInterval(function() {
                    this.refresh();
                }.bind(this), 300);
            },

            // Event handlers //

            mousewheelHandler: function(event) {
                if (this.touched) {
                    return; // Nothing to do here.
                }
                event.preventDefault();
                if (event.originalEvent.wheelDelta < 0) {
                    this.next();
                } else {
                    this.prev();
                }
            },

            domMouseScrollHandler: function(event) {
                if (this.touched) {
                    return; // Nothing to do here.
                }
                event.preventDefault();
                if (event.originalEvent.detail > 0) {
                    this.next();
                } else {
                    this.prev();
                }
            },

            touchstartHandler: function() {
                if (!this.touched) {
                    this.el.css('height', 'auto');
                    this.$wrapper.css('height', 'auto');
                }
                this.touched = true;
            },

            clickShotHandler: function(event) {
                event.preventDefault();
                $.magnificPopup.open({
                    items: {
                        src: event.currentTarget.href
                    },
                    type: 'image',
                    zoom: {
                        enabled: true,
                        duration: 300,
                        easing: 'ease-in-out',
                        opener: function() {
                            return $(event.currentTarget);
                        }
                    }
                });
            }

        });

        return Grid;

    }
);<commit_msg>Inline documentation added to grid view element.<commit_after>/**
 * The grid view.
 */

'use strict';

define(
    [
        'collections/settings',
        'hbs!templates/grid',
        'jquery',
        'backbone',
        'imagesloaded',
        'jquery.magnific-popup'
    ], function(settings, template, $, Backbone) {

        var Grid = Backbone.View.extend({

            /** The template used by this grid. */
            template: template,

            /** Hash of events. */
            events: {
                'touchstart': 'touchstartHandler',
                'mousewheel': 'mousewheelHandler',
                'DOMMouseScroll': 'domMouseScrollHandler',
                'click .shot a': 'clickShotHandler'
            },

            /** Indicates if the grid was touched. */
            touched: false,

            /**
             * Initialize the grid view.
             *
             * @return void
             */
            initialize: function() {
                this.el = $(this.el);
                this.render();
                this.$queue = 0;
                this.resize();
                this.bindEvents();
                this.startTimers();
            },

            /**
             * Render this view.
             *
             * @return void
             */
            render: function() {
                this.el.html(this.template());
                this.$wrapper = this.$('.grid-wrapper');
                this.$grid = this.$('.grid');
                this.$header = this.$('header');
                this.$footer = this.$('footer');
                this.$prev = this.$('.prev');
                this.$next = this.$('.next');
            },

            /**
             * Add an element to the grid.
             *
             * @param object html The element to add.
             * @return void
             */
            add: function(html) {
                this.$queue++;
                var when = $(html).imagesLoaded(function() {
                    --this.$queue;
                    if (!this.$queue) {
                        this.trigger('complete');
                    }
                }.bind(this));

                when.done(function() {
                    this.prepend(html);
                }.bind(this));
            },

            /**
             * Return all columns available.
             *
             * @return Array An array of available columns.
             */
            cols: function() {
                return this.el.find('.col:visible');
            },

            /**
             * Resize the view.
             *
             * @return void
             */
            resize: function() {
                if (this.touched) {
                    return; // Nothing to do here.
                }
                // The following line should not be there.
                this.el.height($(window).height() - (this.el.outerHeight(true) - this.el.height()));
                this.$wrapper.height(this.el.height());
                this.$footer.css('top', this.el.height() - this.$footer.height());
            },

            /**
             * Prepends an element to the view.
             *
             * @return void
             */
            prepend: function(html) {
                var cols = this.cols();
                var col = cols.first();
                cols.each(function() {
                    var $this = $(this);
                    col = col.children().length <= $this.children().length ? col : $this;
                });
                col.prepend(html);
            },

            /**
             * Move the grid to make the next row visible.
             *
             * @return void
             */
            next: function() {
                var rowHeight = this.rowHeight();
                var remaining = this.$grid.height() - this.el.height() + (parseInt(this.$grid.css('top'), 10) || 0);
                if (remaining > rowHeight) {
                    this.$grid.css('top', '-=' + rowHeight);
                } else {
                    this.$grid.css('top', (this.el.height() - this.$grid.height()));
                }
            },

            /**
             * Move the grid to make the previous row visible.
             *
             * @return void
             */
            prev: function() {
                var rowHeight = this.rowHeight();
                var remaining = -parseInt(this.$grid.css('top'), 10) || 0;
                var inperfections = (remaining % rowHeight);
                if (inperfections) {
                    this.$grid.css('top', '+=' + inperfections);
                    this.$lastRow = false;
                } else if (remaining > rowHeight) {
                    this.$grid.css('top', '+=' + rowHeight);
                } else {
                    this.$grid.css('top', 0);
                }
            },

            /**
             * Return the virtual row height.
             *
             * @return number The virtual row height.
             */
            rowHeight: function() {
                var children = this.cols().first().children();
                if (children.length >= 2) {
                    return children.eq(1).offset().top - children.eq(0).offset().top;
                }
                return 0;
            },

            /**
             * Refresh arrows visibility state.
             *
             * @return void
             */
            refresh: function() {
                if (settings.value('grid_controls')) {
                    var top = parseInt(this.$grid.css('top'), 10);
                    if (top === 0) {
                        this.$header.hide();
                    } else {
                        this.$header.show();
                    }
                    var remaining = this.$grid.height() - this.el.height() + top;
                    if (remaining > 0) {
                        this.$footer.show();
                    } else {
                        this.$footer.hide();
                    }
                }
            },

            /**
             * Bind events.
             *
             * @return void
             */
            bindEvents: function() {
                this.listenTo(this.$prev, 'click', function(event) {
                    event.preventDefault();
                    this.prev();
                }.bind(this));

                this.listenTo(this.$next, 'click', function(event) {
                    event.preventDefault();
                    this.next();
                }.bind(this));
            },

            /**
             * Start internal timers.
             *
             * @return void
             */
            startTimers: function() {
                setInterval(function() {
                    this.refresh();
                }.bind(this), 300);
            },

            // Event handlers //

            /**
             * Handle the mouse wheel event.
             *
             * @param event object The event object.
             * @return void
             */
            mousewheelHandler: function(event) {
                if (this.touched) {
                    return; // Nothing to do here.
                }
                event.preventDefault();
                if (event.originalEvent.wheelDelta < 0) {
                    this.next();
                } else {
                    this.prev();
                }
            },

            /**
             * Handle the mouse scroll event.
             *
             * @param event object The event object.
             * @return void
             */
            domMouseScrollHandler: function(event) {
                if (this.touched) {
                    return; // Nothing to do here.
                }
                event.preventDefault();
                if (event.originalEvent.detail > 0) {
                    this.next();
                } else {
                    this.prev();
                }
            },

            /**
             * Handle the touch start event.
             *
             * @return void
             */
            touchstartHandler: function() {
                if (!this.touched) {
                    this.el.css('height', 'auto');
                    this.$wrapper.css('height', 'auto');
                }
                this.touched = true;
            },

            /**
             * Handle the click event on a shot.
             *
             * @param event object The event object.
             * @return void
             */
            clickShotHandler: function(event) {
                event.preventDefault();
                $.magnificPopup.open({
                    items: {
                        src: event.currentTarget.href
                    },
                    type: 'image',
                    zoom: {
                        enabled: true,
                        duration: 300,
                        easing: 'ease-in-out',
                        opener: function() {
                            return $(event.currentTarget);
                        }
                    }
                });
            }

        });

        return Grid;

    }
);<|endoftext|>


<commit_before>var jwt = require('./jwt.js'),
dynamo = require('./aws.js'),
//redis mem storage
redis = require('redis'),
client = redis.createClient(6379, 'localhost', { enable_offline_queue: false });

//redis rate limiter. Tthis package because it also has the ability to spread the requests
//so that users can't do 100 consecutive requests in 10 seconds. It will allow one per 0.6 seconds instead.
//For now I have it set to a simple 100/minute at any rate.

var rateLimiter = require('redis-rate-limiter');
var limit = rateLimiter.create({
    redis: client,
    key: 'ip',
    value: (Date.now() / 1000),
    rate: '100/minute'
});

//Init main object to export
var Handlers = {};

//Get Sources in Table Form
Handlers.auth = function () {
    return function (req, res) {
        limit(req, function (err, rate) {
            //set response headers
            res.header("Content-Type", "text/json");
            //make absolutely sure POST
            if (req.method === 'POST' && !rate.over) {
                //Get credentials from dynamo
                dynamo.getCredentials(req.body, function (err, credentials) {
                    //make sure user and password exist in DB
                    if (JSON.stringify(credentials) === JSON.stringify(req.body)) {
                        var token = jwt.getToken(req);
                        jwt.success(res, token, "success");
                    }
                    else {
                        jwt.authFail(res, 'error, cannot autheticate credentials.');
                    }
                });//dynamo get
            }//if POST and rate over
            else {
                res.end('Rate limit reached for ' + req.method);
            }
        });
    }//return
}//auth
Handlers.validate = function () {
    return function (req, res) {
        //set headers
        res.header("Content-Type", "text/html");
        //make absolutely sure POST
        if (req.method === 'GET') {
            //Get credentials from dynamo
            jwt.validate(req, res, function (err, valid) {
                //make sure user and password exist in DB
                if (valid) {
                    jwt.success(res, token);
                }
                else {
                    jwt.authFail(res, 'Could not auth token.');
                }
            });//jwt validate
        }//if
    }//return
}//validate
module.exports = Handlers;
<commit_msg>Update routeHandlers.js<commit_after>var jwt = require('./jwt.js'),
dynamo = require('./aws.js'),
//redis mem storage
redis = require('redis'),
client = redis.createClient(6379, 'localhost', { enable_offline_queue: false });

//redis rate limiter. Tthis package because it also has the ability to spread the requests
//so that users can't do 100 consecutive requests in 10 seconds. It will allow one per 0.6 seconds instead.
//For now I have it set to a simple 100/minute at any rate.

var rateLimiter = require('redis-rate-limiter');
var limit = rateLimiter.create({
    redis: client,
    key: 'ip',
    value: (Date.now() / 1000),
    rate: '100/minute'
});

//Init main object to export
var Handlers = {};

//Get Sources in Table Form
Handlers.auth = function () {
    return function (req, res) {
        limit(req, function (err, rate) {
            //set response headers
            res.header("Content-Type", "text/json");
            //make absolutely sure POST
            if (req.method === 'POST' && !rate.over) {
                //Get credentials from dynamo
                dynamo.getCredentials(req.body, function (err, credentials) {
                    //make sure user and password exist in DB
                    if (JSON.stringify(credentials) === JSON.stringify(req.body)) {
                        var token = jwt.getToken(req);
                        jwt.success(res, token, "success");
                    }
                    else {
                        jwt.authFail(res, 'error, cannot autheticate credentials.');
                    }
                });//dynamo get
            }//if POST and rate over
            else {
                res.end('Rate limit reached for ' + req.method);
            }
        });//limiter
    }//return
}//auth
Handlers.validate = function () {
    return function (req, res) {
        //set headers
        res.header("Content-Type", "text/html");
        //make absolutely sure POST
        if (req.method === 'GET') {
            //Get credentials from dynamo
            jwt.validate(req, res, function (err, valid) {
                //make sure user and password exist in DB
                if (valid) {
                    jwt.success(res, token);
                }
                else {
                    jwt.authFail(res, 'Could not auth token.');
                }
            });//jwt validate
        }//if
    }//return
}//validate
module.exports = Handlers;
<|endoftext|>


<commit_before>
//positioning settings
var width = 740;
var height = 4000;
var pad = { left: 10, right: 0, top: 60, bottom: 10 };
var vertSpace = 45;
var xName = 20;

var xPrct = 520;
var xChange = 640;
var xNumF = 260;
var xTotal = 380;

var rectW = 80;
var rectH = 35;
var yHeader = 20;
var ySubHead = 40;

//define scales
var scaleRB6 = ['rgb(178,24,43)','rgb(239,138,98)','rgb(253,219,199)','rgb(209,229,240)','rgb(103,169,207)','rgb(33,102,172)'];
var colors = d3.scale.quantize().domain([30, 0]).range(scaleRB6);
var sizeNumF = d3.scale.linear().domain([10, 100]).range([11, 30]);
var sizeTotal = d3.scale.linear().domain([50, 500]).range([11, 30]);
var changeH = d3.scale.linear().domain([0, 13]).range([0, 18]);
var prctBar = d3.scale.linear().domain([0, 32]).range([0, 25]);

//create container elements
var svg = d3.select(".top25").append("svg")
            .attr("width", width + pad.left + pad.right)
            .attr("height", height + pad.top + pad.bottom);

//create header (background) tiles
var headerTiles = svg.append("g").attr("class", "headerTile").attr("transform", "translate(" + pad.left + ",0)");
var activeTile = headerTiles.append("rect").attr({x: xPrct-45, y: 7, width: 90, height: 43, class: "prct"}).style("fill", "#eee").on("click", rankPrct);
headerTiles.append("rect").attr({x: xChange-70, y: 7, width: 140, height: 43, fill: "white", class: "change"}).on("click", rankChange);
headerTiles.append("rect").attr({x: xNumF-65, y: 7, width: 130, height: 43, fill: "white", class: "numF"}).on("click", rankNumF);
headerTiles.append("rect").attr({x: xTotal-37, y: 7, width: 74, height: 43, fill: "white", class: "total"}).on("click", rankTotal);
headerTiles.selectAll("rect").style("cursor", "pointer");

//create header text
var header = svg.append("g").attr("class", "header").attr("transform", "translate(" + pad.left + "," + yHeader + ")");
header.append("text").text("% Women").attr("x", xPrct).on("click", rankPrct);
header.append("text").text("Change in %").attr("x", xChange).on("click", rankChange);
header.append("text").text("Explicit").attr("x", xNumF).on("click", rankNumF);
header.append("text").text("Implicit").attr("x", xTotal).on("click", rankTotal);
var subHead = svg.append("g").attr("class", "subHead").attr("transform", "translate(" + pad.left + "," + ySubHead + ")");
subHead.append("text").text("(2011-2013)").attr("x", xPrct).on("click", rankPrct);
subHead.append("text").text("(compared to 2008-2010)").attr("x", xChange).on("click", rankChange);
subHead.append("text").text("Stereotypes").attr("x", xNumF).on("click", rankNumF);
subHead.append("text").text("Stereotypes").attr("x", xTotal).on("click", rankTotal);
header.selectAll("text").style("cursor", "pointer");
subHead.selectAll("text").style("cursor", "pointer");
//event handlers for resorting the rows
function rankPrct() {
  activeTile.style("fill", "white");
  activeTile = d3.select(".headerTile .prct");
  activeTile.style("fill", "#eee");
  d3.selectAll("g.row")
    .transition().duration(800)
    .attr("transform", function(d) { return "translate(0," + vertSpace*(+d.rank - 0.5) + ")"; });
}
function rankChange() {
  activeTile.style("fill", "white");
  activeTile = d3.select(".headerTile .change");
  activeTile.style("fill", "#eee");
  d3.selectAll("g.row")
    .transition().duration(800)
    .attr("transform", function(d) { return "translate(0," + vertSpace*(+d.rankChange - 0.5) + ")"; });
}
function rankNumF() {
  activeTile.style("fill", "white");
  activeTile = d3.select(".headerTile .numF");
  activeTile.style("fill", "#eee");
  d3.selectAll("g.row")
    .transition().duration(800)
    .attr("transform", function(d) { return "translate(0," + vertSpace*(+d.rankNumF - 0.5) + ")"; });
}
function rankTotal() {
  activeTile.style("fill", "white");
  activeTile = d3.select(".headerTile .total");
  activeTile.style("fill", "#eee");
  d3.selectAll("g.row")
    .transition().duration(800)
    .attr("transform", function(d) { return "translate(0," + vertSpace*(+d.rankTotal - 0.5) + ")"; });
}

//create header line and content SVG group
svg.append("line").attr({ x1: 0, x2: width, y1: 2, y2: 2}).style({"stroke-width": 2, stroke: "#222"});
svg.append("line").attr({ x1: 0, x2: width, y1: pad.top-5, y2: pad.top-5}).style({"stroke-width": 2, stroke: "#222"});
var g = svg.append("g").attr("transform", "translate(" + pad.left + ", " + pad.top + ")");

//load data...
d3.csv("data/top25.csv", function(data) {

  ///////////////////////////////
  //  FIXED POSITION ELEMENTS  //
  ///////////////////////////////

  //add lines in between
  g.selectAll("line.sep").data(data).enter().append("line")
    .attr({ x1: -pad.left, x2: width-pad.left, class: "sep"})
    .attr("y1", function(d) { return vertSpace*d.rank; })
    .attr("y2", function(d) { return vertSpace*d.rank; })
    .style({"stroke-width": 0.5, stroke: "#888"});

  //ranking text
  g.selectAll("text.rank").data(data).enter().append("text")
    .attr("class", "rank")
    .text(function(d) { return d.rank + "."; })
    .attr("y", function(d) { return vertSpace*(d.rank - 0.5); })
    .attr("x", 5);

  /////////////////////////////////
  //  DYNAMIC POSITION ELEMENTS  //
  /////////////////////////////////

  //add grouping elements
  var rows = g.selectAll(".rows")
              .data(data).enter()
              .append("g")
              .attr("class", "row")
              .attr("transform", function(d) {
                return "translate(0," + vertSpace*(+d.rank - 0.5) + ")";
              });

  //for each school...
  rows.each(function(d) {

    //get a D3 selection of the g SVG element
    var s = d3.select(this);

    //school name
    s.append("text")
      .attr("class", "name")
      .text(function(d) { return d.abbrev; })
      .attr("x", xName);

    //percent women text
    s.append("text")
      .attr("class", "prct")
      .text(function(d) { return d.prctStr; })
      .attr("x", xPrct)
      .style("fill", "#333")
      .style("font-size", 25);

    //change percent text
    s.append("text")
      .attr("class", "change")
      .text(function(d) { return d.changeStr; })
      .attr("x", xChange)
      .style("font-size", 25);

    //number women text
    s.append("text")
      .attr("class", "numF")
      .text(function(d) { return d.numF; })
      .attr("x", xNumF)
      .style("font-size", 25);
      //.style("font-size", function(d) { return sizeNumF(d.numF); });

    //total number text
    s.append("text")
      .attr("class", "total")
      .text(function(d) { return d.total; })
      .attr("x", xTotal)
      .style("font-size", 25);
      //.style("font-size", function(d) { return sizeTotal(d.total); });

  });

});<commit_msg>update<commit_after>
//positioning settings
var width = 740;
var height = 4000;
var pad = { left: 10, right: 0, top: 60, bottom: 10 };
var vertSpace = 45;
var xName = 20;

var xPrct = 520;
var xChange = 640;
var xNumF = 260;
var xTotal = 380;

var rectW = 80;
var rectH = 35;
var yHeader = 20;
var ySubHead = 40;

//define scales
var scaleRB6 = ['rgb(178,24,43)','rgb(239,138,98)','rgb(253,219,199)','rgb(209,229,240)','rgb(103,169,207)','rgb(33,102,172)'];
var colors = d3.scale.quantize().domain([30, 0]).range(scaleRB6);
var sizeNumF = d3.scale.linear().domain([10, 100]).range([11, 30]);
var sizeTotal = d3.scale.linear().domain([50, 500]).range([11, 30]);
var changeH = d3.scale.linear().domain([0, 13]).range([0, 18]);
var prctBar = d3.scale.linear().domain([0, 32]).range([0, 25]);

//create container elements
var svg = d3.select(".top25").append("svg")
            .attr("width", width + pad.left + pad.right)
            .attr("height", height + pad.top + pad.bottom);

//create header (background) tiles
var headerTiles = svg.append("g").attr("class", "headerTile").attr("transform", "translate(" + pad.left + ",0)");
var activeTile = headerTiles.append("rect").attr({x: xPrct-45, y: 7, width: 90, height: 43, class: "prct"}).style("fill", "#eee").on("click", rankPrct);
headerTiles.append("rect").attr({x: xChange-70, y: 7, width: 140, height: 43, fill: "white", class: "change"}).on("click", rankChange);
headerTiles.append("rect").attr({x: xNumF-65, y: 7, width: 130, height: 43, fill: "white", class: "numF"}).on("click", rankNumF);
headerTiles.append("rect").attr({x: xTotal-37, y: 7, width: 74, height: 43, fill: "white", class: "total"}).on("click", rankTotal);
headerTiles.selectAll("rect").style("cursor", "pointer");

//create header text
var header = svg.append("g").attr("class", "header").attr("transform", "translate(" + pad.left + "," + yHeader + ")");
header.append("text").text("Science Majors").attr("x", xPrct).on("click", rankPrct);
header.append("text").text("Researchers").attr("x", xChange).on("click", rankChange);
header.append("text").text("Explicit").attr("x", xNumF).on("click", rankNumF);
header.append("text").text("Implicit").attr("x", xTotal).on("click", rankTotal);
var subHead = svg.append("g").attr("class", "subHead").attr("transform", "translate(" + pad.left + "," + ySubHead + ")");
subHead.append("text").text("% Women").attr("x", xPrct).on("click", rankPrct);
subHead.append("text").text("% Women").attr("x", xChange).on("click", rankChange);
subHead.append("text").text("Stereotypes").attr("x", xNumF).on("click", rankNumF);
subHead.append("text").text("Stereotypes").attr("x", xTotal).on("click", rankTotal);
header.selectAll("text").style("cursor", "pointer");
subHead.selectAll("text").style("cursor", "pointer");
//event handlers for resorting the rows
function rankPrct() {
  activeTile.style("fill", "white");
  activeTile = d3.select(".headerTile .prct");
  activeTile.style("fill", "#eee");
  d3.selectAll("g.row")
    .transition().duration(800)
    .attr("transform", function(d) { return "translate(0," + vertSpace*(+d.rank - 0.5) + ")"; });
}
function rankChange() {
  activeTile.style("fill", "white");
  activeTile = d3.select(".headerTile .change");
  activeTile.style("fill", "#eee");
  d3.selectAll("g.row")
    .transition().duration(800)
    .attr("transform", function(d) { return "translate(0," + vertSpace*(+d.rankChange - 0.5) + ")"; });
}
function rankNumF() {
  activeTile.style("fill", "white");
  activeTile = d3.select(".headerTile .numF");
  activeTile.style("fill", "#eee");
  d3.selectAll("g.row")
    .transition().duration(800)
    .attr("transform", function(d) { return "translate(0," + vertSpace*(+d.rankNumF - 0.5) + ")"; });
}
function rankTotal() {
  activeTile.style("fill", "white");
  activeTile = d3.select(".headerTile .total");
  activeTile.style("fill", "#eee");
  d3.selectAll("g.row")
    .transition().duration(800)
    .attr("transform", function(d) { return "translate(0," + vertSpace*(+d.rankTotal - 0.5) + ")"; });
}

//create header line and content SVG group
svg.append("line").attr({ x1: 0, x2: width, y1: 2, y2: 2}).style({"stroke-width": 2, stroke: "#222"});
svg.append("line").attr({ x1: 0, x2: width, y1: pad.top-5, y2: pad.top-5}).style({"stroke-width": 2, stroke: "#222"});
var g = svg.append("g").attr("transform", "translate(" + pad.left + ", " + pad.top + ")");

//load data...
d3.csv("data/top25.csv", function(data) {

  ///////////////////////////////
  //  FIXED POSITION ELEMENTS  //
  ///////////////////////////////

  //add lines in between
  g.selectAll("line.sep").data(data).enter().append("line")
    .attr({ x1: -pad.left, x2: width-pad.left, class: "sep"})
    .attr("y1", function(d) { return vertSpace*d.rank; })
    .attr("y2", function(d) { return vertSpace*d.rank; })
    .style({"stroke-width": 0.5, stroke: "#888"});

  //ranking text
  g.selectAll("text.rank").data(data).enter().append("text")
    .attr("class", "rank")
    .text(function(d) { return d.rank + "."; })
    .attr("y", function(d) { return vertSpace*(d.rank - 0.5); })
    .attr("x", 5);

  /////////////////////////////////
  //  DYNAMIC POSITION ELEMENTS  //
  /////////////////////////////////

  //add grouping elements
  var rows = g.selectAll(".rows")
              .data(data).enter()
              .append("g")
              .attr("class", "row")
              .attr("transform", function(d) {
                return "translate(0," + vertSpace*(+d.rank - 0.5) + ")";
              });

  //for each school...
  rows.each(function(d) {

    //get a D3 selection of the g SVG element
    var s = d3.select(this);

    //school name
    s.append("text")
      .attr("class", "name")
      .text(function(d) { return d.abbrev; })
      .attr("x", xName);

    //percent women text
    s.append("text")
      .attr("class", "prct")
      .text(function(d) { return d.prctStr; })
      .attr("x", xPrct)
      .style("fill", "#333")
      .style("font-size", 25);

    //change percent text
    s.append("text")
      .attr("class", "change")
      .text(function(d) { return d.changeStr; })
      .attr("x", xChange)
      .style("font-size", 25);

    //number women text
    s.append("text")
      .attr("class", "numF")
      .text(function(d) { return d.numF; })
      .attr("x", xNumF)
      .style("font-size", 25);
      //.style("font-size", function(d) { return sizeNumF(d.numF); });

    //total number text
    s.append("text")
      .attr("class", "total")
      .text(function(d) { return d.total; })
      .attr("x", xTotal)
      .style("font-size", 25);
      //.style("font-size", function(d) { return sizeTotal(d.total); });

  });

});<|endoftext|>


<commit_before>import md5 from 'md5'

function createNewVersionsTable(release) {
  const entries = Object.keys(release.newVersionByPackage)
    .filter(packageName => {
      return (
        release.currentVersionByPackage[packageName] !==
        release.newVersionByPackage[packageName]
      )
    })
    .map(packageName => {
      return `| ${packageName} | ${release.currentVersionByPackage[
        packageName
      ]} | ${release.newVersionByPackage[packageName]} |`
    })

  if (!entries.length) {
    return ''
  }

  return `## Updated packages

| package | from version | to version |
|:---|:---|:---|
${entries.join('\n')}
`
}

function byPackageName(a, b) {
  if (a.packageName > b.packageName) return 1
  else if (a.packageName < b.packageName) return -1
  else return 0
}

const typeHeaders = {
  feat: ':fire: Feature change',
  fix: ':bug: Bug fixes',
  docs: ':paperclip: Documentation',
  chore: ':wrench: Chores',
  style: ':pencil2: Styling',
  refactor: ':mag: Refactors',
  perf: ':runner: Performance',
  test: ':vertical_traffic_light: Tests',
  ts: ':pencil: Typescript',
}

function createChangeTable(type, release) {
  const entries = release.summary[type]
    .reduce((allEntries, summary) => {
      return allEntries.concat(
        summary.commits.map(commit => {
          return {
            packageName: summary.name,
            summary: commit.summary,
            issues: commit.issues,
            hash: commit.hash,
            authorName: commit.author.name,
            authorEmail: commit.author.email,
          }
        })
      )
    }, [])
    .sort(byPackageName)

  return `## ${typeHeaders[type]}
| package | summary | commit | issues | author | |
|:---|:---|:---|:---|:---|---|
${entries
    .map(entry => {
      return `| ${entry.packageName} | ${entry.summary} | ${entry.hash} | ${entry.issues.join(
        ', '
      )} | ${entry.authorName} | ![${entry.authorName}](https://www.gravatar.com/avatar/${md5(
        entry.authorEmail
      )}?s=40) |`
    })
    .join('\n')}
`
}

function createBreakingTable(type, release) {
  const entries = release.summary[type]
    .reduce((allEntries, summary) => {
      const onlyBreaking = summary.commits.filter(
        commit => commit.breaks.length
      )

      // Mutate in place (easier :))
      summary.commits = summary.commits.filter(commit => !commit.breaks.length)

      return allEntries.concat(
        onlyBreaking.map(commit => {
          return {
            packageName: summary.name,
            summary: commit.summary,
            issues: commit.issues,
            hash: commit.hash,
            authorName: commit.author.name,
            authorEmail: commit.author.email,
          }
        })
      )
    }, [])
    .sort(byPackageName)

  if (!entries.length) {
    return ''
  }

  return `## :rotating_light: Breaking
| package | summary | commit | issues | author | |
|:---|:---|:---|:---|:---|---|
${entries
    .map(entry => {
      return `| ${entry.packageName} | ${entry.summary} | ${entry.hash} | ${entry.issues.join(
        ', '
      )} | ${entry.authorName} | ![${entry.authorName}](https://www.gravatar.com/avatar/${md5(
        entry.authorEmail
      )}?s=40) |`
    })
    .join('\n')}
`
}

function createOtherTable(release) {
  if (!release.commitsWithoutPackage.length) {
    return ''
  }

  return `## :relieved: Other
| summary | commit | issues | author | |
|:---|:---|:---|:---|---|
${release.commitsWithoutPackage
    .map(entry => {
      return `| ${entry.summary} | ${entry.hash} | ${entry.issues.join(
        ', '
      )} | ${entry.author.name} | ![${entry.author
        .email}](https://www.gravatar.com/avatar/${md5(
        entry.author.email
      )}?s=40) |`
    })
    .join('\n')}
`
}

export default release => {
  const breaking = Object.keys(release.summary).map(type =>
    createBreakingTable(type, release)
  )
  const changes = Object.keys(release.summary).map(type =>
    createChangeTable(type, release)
  )

  const other = createOtherTable(release)

  return `
${createNewVersionsTable(release)}
${breaking.join('\n')}
${changes.join('\n')}
${other}
`
}
<commit_msg>chore(release): add type and scope to others table<commit_after>import md5 from 'md5'

function createNewVersionsTable(release) {
  const entries = Object.keys(release.newVersionByPackage)
    .filter(packageName => {
      return (
        release.currentVersionByPackage[packageName] !==
        release.newVersionByPackage[packageName]
      )
    })
    .map(packageName => {
      return `| ${packageName} | ${release.currentVersionByPackage[
        packageName
      ]} | ${release.newVersionByPackage[packageName]} |`
    })

  if (!entries.length) {
    return ''
  }

  return `## Updated packages

| package | from version | to version |
|:---|:---|:---|
${entries.join('\n')}
`
}

function byPackageName(a, b) {
  if (a.packageName > b.packageName) return 1
  else if (a.packageName < b.packageName) return -1
  else return 0
}

const typeHeaders = {
  feat: ':fire: Feature change',
  fix: ':bug: Bug fixes',
  docs: ':paperclip: Documentation',
  chore: ':wrench: Chores',
  style: ':pencil2: Styling',
  refactor: ':mag: Refactors',
  perf: ':runner: Performance',
  test: ':vertical_traffic_light: Tests',
  ts: ':pencil: Typescript',
}

function createChangeTable(type, release) {
  const entries = release.summary[type]
    .reduce((allEntries, summary) => {
      return allEntries.concat(
        summary.commits.map(commit => {
          return {
            packageName: summary.name,
            summary: commit.summary,
            issues: commit.issues,
            hash: commit.hash,
            authorName: commit.author.name,
            authorEmail: commit.author.email,
          }
        })
      )
    }, [])
    .sort(byPackageName)

  return `## ${typeHeaders[type]}
| package | summary | commit | issues | author | |
|:---|:---|:---|:---|:---|---|
${entries
    .map(entry => {
      return `| ${entry.packageName} | ${entry.summary} | ${entry.hash} | ${entry.issues.join(
        ', '
      )} | ${entry.authorName} | ![${entry.authorName}](https://www.gravatar.com/avatar/${md5(
        entry.authorEmail
      )}?s=40) |`
    })
    .join('\n')}
`
}

function createBreakingTable(type, release) {
  const entries = release.summary[type]
    .reduce((allEntries, summary) => {
      const onlyBreaking = summary.commits.filter(
        commit => commit.breaks.length
      )

      // Mutate in place (easier :))
      summary.commits = summary.commits.filter(commit => !commit.breaks.length)

      return allEntries.concat(
        onlyBreaking.map(commit => {
          return {
            packageName: summary.name,
            summary: commit.summary,
            issues: commit.issues,
            hash: commit.hash,
            authorName: commit.author.name,
            authorEmail: commit.author.email,
          }
        })
      )
    }, [])
    .sort(byPackageName)

  if (!entries.length) {
    return ''
  }

  return `## :rotating_light: Breaking
| package | summary | commit | issues | author | |
|:---|:---|:---|:---|:---|---|
${entries
    .map(entry => {
      return `| ${entry.packageName} | ${entry.summary} | ${entry.hash} | ${entry.issues.join(
        ', '
      )} | ${entry.authorName} | ![${entry.authorName}](https://www.gravatar.com/avatar/${md5(
        entry.authorEmail
      )}?s=40) |`
    })
    .join('\n')}
`
}

function createOtherTable(release) {
  if (!release.commitsWithoutPackage.length) {
    return ''
  }

  return `## :relieved: Other
| type | summary | commit | issues | author | |
|---|:---|:---|:---|:---|---|
${release.commitsWithoutPackage
    .map(entry => {
      return `| ${entry.type} (${entry.scope ||
        'monorepo'}) | ${entry.summary} | ${entry.hash} | ${entry.issues.join(
        ', '
      )} | ${entry.author.name} | ![${entry.author
        .email}](https://www.gravatar.com/avatar/${md5(
        entry.author.email
      )}?s=40) |`
    })
    .join('\n')}
`
}

export default release => {
  console.log(release)
  const breaking = Object.keys(release.summary).map(type =>
    createBreakingTable(type, release)
  )
  const changes = Object.keys(release.summary).map(type =>
    createChangeTable(type, release)
  )

  const other = createOtherTable(release)

  return `
${createNewVersionsTable(release)}
${breaking.join('\n')}
${changes.join('\n')}
${other}
`
}
<|endoftext|>