<commit_before>var fs    = require('fs');
var jsdom = require('jsdom');
var path  = require('path');
var us    = require('underscore');

var PATH_BASE = './data/www.cplusplus.com/reference/';
var URL_BASE  = 'http://www.cplusplus.com/reference/';
var JQUERY_URL = './jquery-1.5.min.js'; // 'http://code.jquery.com/jquery-1.5.min.js';

function create_window(cb) {
    var document = jsdom.jsdom('');
    var window = document.createWindow();

    jsdom.jQueryify(window, JQUERY_URL, function() {
	cb(window, document);
    });
}

function fetch_html(path, cb) {
    var html = fs.readFileSync(path).toString();
    // console.error("html:", html);
    // process.nextTick(function() {
	cb(html);
    // });
}

function get_all_file_paths() {
    function is_a_directory(dir) {
	return dir !== 'algorithm' && fs.statSync(path.join(PATH_BASE, dir)).isDirectory();
    }

    function get_all_subdirs(sdirs) {
	sdirs = us.flatten(sdirs.map(function(dir) {
	    return fs.readdirSync(path.join(PATH_BASE, dir)).map(function(sdir) {
		return path.join(dir, sdir);
	    });
	})).filter(is_a_directory);
	return sdirs;
    }

    var sdirs = get_all_subdirs(get_all_subdirs(get_all_subdirs(['.'])));
    sdirs = sdirs.concat(get_all_subdirs(['algorithm']));
    return sdirs;
}

function start_parsing(dirs, window, document, cb) {
    console.error("start_parsing: dirs:", dirs);

    var data = [ ];
    function parse_file(dirs, i, data, next_cb, end_cb) {
	if (i === dirs.length) {
	    end_cb(data);
	    return;
	}

	var _p  = path.join(PATH_BASE, dirs[i], 'index.html');
	fetch_html(_p, function(html) {
	    console.error("Parsing file:", _p);

	    document.innerHTML = html;
	    var $ = window.$;

	    $("#CH_main").html(
		$("#CH_main").html().replace("
", "

")
	    );
	    var dst = $(".docsubtop");
	    var module = path.basename(path.dirname(dirs[i]));
	    var proc = path.basename(dirs[i]);
	    var desc_short = dst.next().text().trim().replace(/\n/g, "\\n");
	    var desc_long  = dst.next().next().text().trim().replace(/\n/g, "\\n");

	    var fq_name = $('.C_doctop').text();
	    var signature = $('.prototype').text().split(';')[0].trim();
	    var description = desc_short + '. ' + desc_long;
	    var title = module + ' ' + proc;
	    var url = URL_BASE + dirs[i];

	    var entry = {
		page: title,
		synopsis: fq_name + "\n" + signature,
		description: description,
		url: url
	    };

	    data.push(entry);

	    if (module[0] == 'c' && module !== 'char_traits') {
		entry = {
		    page: proc,
		    synopsis: fq_name + "\n" + signature,
		    description: description,
		    url: url
		};
		data.push(entry);
	    }

	    // console.error("entry:", entry);

	    next_cb(dirs, i+1, data, next_cb, end_cb);
	});
    }

    parse_file(dirs, 0, data,  parse_file, cb);
}

function parse_all_docs(window, document, cb) {
    start_parsing(get_all_file_paths(), window, document, cb);
}

function dump_to_file(docs) {
    var _d = docs.map(function(d) {
	return [ d.page, '', d.url, d.description,
		 d.synopsis, '', '', 'en' ].join('\t').replace(/\n/g, ' ');
    });
    fs.writeFileSync('c++.docs.txt', _d.join('\n'));
}

function main() {
    create_window(function(window, document) {
	parse_all_docs(window, document, function(data) {
	    dump_to_file(data);
	    console.error("DONE!!");
	});
    });
}

main();

<commit_msg>Fixed parse.js and add more special cases for data duplication<commit_after>var fs    = require('fs');
var jsdom = require('jsdom');
var path  = require('path');
var us    = require('underscore');

var PATH_BASE = './data/www.cplusplus.com/reference/';
var URL_BASE  = 'http://www.cplusplus.com/reference/';
var JQUERY_URL = './jquery-1.5.min.js'; // 'http://code.jquery.com/jquery-1.5.min.js';

/*
function create_window(cb) {
    var document = jsdom.jsdom('');
    var window = document.createWindow();

    jsdom.jQueryify(window, JQUERY_URL, function() {
	cb(window, document);
    });
}
*/

var escaped_one_to_xml_special_map = {
    '&': '&',
    '"': '"',
    ''': "'",
    '<': '<',
    '>': '>'
};

function decodeXml(string) {
    return string.replace(/("|'|<|>|&)/g,
			  function(str, item) {
			      return escaped_one_to_xml_special_map[item];
			  });
}

function create_window(cb) {
    jsdom.env('', [ JQUERY_URL ], function(errors, window) {
	if (errors) {
	    throw new Error(errors[0]);
	}
	cb(window, window.document);
    });
}

function fetch_html(path, cb) {
    var html = fs.readFileSync(path).toString();
    // console.error("html:", html);
    // process.nextTick(function() {
	cb(html);
    // });
}

function get_all_file_paths() {
    function is_a_directory(dir) {
	return dir !== 'algorithm' && fs.statSync(path.join(PATH_BASE, dir)).isDirectory();
    }

    function get_all_subdirs(sdirs) {
	sdirs = us.flatten(sdirs.map(function(dir) {
	    return fs.readdirSync(path.join(PATH_BASE, dir)).map(function(sdir) {
		return path.join(dir, sdir);
	    });
	})).filter(is_a_directory);
	return sdirs;
    }

    var sdirs = get_all_subdirs(get_all_subdirs(get_all_subdirs(['.'])));
    sdirs = sdirs.concat(get_all_subdirs(['algorithm']));
    return sdirs;
}

function start_parsing(dirs, window, document, cb) {
    console.error("start_parsing: dirs:", dirs);

    var data = [ ];
    function parse_file(dirs, i, data) {

	var _p  = path.join(PATH_BASE, dirs[i], 'index.html');
	fetch_html(_p, function(html) {
	    console.error("Parsing file:", _p);

	    document.innerHTML = html;
	    var $ = window.$;

	    $("#CH_main").html(
		$("#CH_main").html().replace("
", "

")
	    );
	    var dst = $(".docsubtop");
	    var module = path.basename(path.dirname(dirs[i]));
	    var proc = path.basename(dirs[i]);
	    var desc_short = dst.next().text().trim().replace(/\n/g, "\\n");
	    var desc_long  = dst.next().next().text().trim().replace(/\n/g, "\\n");

	    var fq_name = $('.C_doctop').text();
	    var signature = $('.prototype').text().split(';')[0].trim();
	    var description = desc_short + '. ' + desc_long;
	    var title = module + ' ' + proc;
	    var url = URL_BASE + dirs[i];

	    var entry = {
		page: title,
		synopsis: fq_name + "\n" + signature,
		description: description,
		url: url
	    };

	    data.push(entry);

	    var global_modules = {
		algorithm: 1,
		functional: 1,
		numeric: 1,
		iterator: 1,
		locale: 1,
		memory: 1,
		stdexcept: 1,
		utility: 1,
		typeinfo: 1,
		"new": 1,
		limits: 1,
		exception: 1
	    };

	    if ((module[0] == 'c' && module !== 'char_traits') ||
		global_modules.hasOwnProperty(global_modules)) {
		entry = {
		    page: proc,
		    synopsis: fq_name + "\n" + signature,
		    description: description,
		    url: url
		};
		data.push(entry);
	    }

	    // console.error("entry:", entry);

	    // next_cb(dirs, i+1, data, next_cb, end_cb);
	});
    }

    for (var i = 0; i < dirs.length; ++i) {
	parse_file(dirs, i, data);
    }
    cb(data);
}

function parse_all_docs(window, document, cb) {
    start_parsing(get_all_file_paths(), window, document, cb);
}

function dump_to_file(docs) {
    var _d = docs.map(function(d) {
	return decodeXml([ d.page, '', d.url, d.description,
			   d.synopsis, '', '', 'en' ].join('\t').replace(/\n/g, ' '));
    });
    fs.writeFileSync('c++.docs.txt', _d.join('\n'));
}

function main() {
    create_window(function(window, document) {
	parse_all_docs(window, document, function(data) {
	    dump_to_file(data);
	    console.error("DONE!!");
	});
    });
}

main();

<|endoftext|>


<commit_before>var VATRates = require('./vat-rates.json').data;

function getVATByCountry(countrycode) {
  if (countrycode === 'GB') {
    countrycode = 'UK';
  }
  var rate = data[countrycode].standard_rate / 100;
  return Promise.resolve(rate);
}

function countryIsInEU(countrycode) {
    var EU = ['AT', 'BE', 'BG', 'CY', 'CZ', 'DE', 'DK', 'EE', 'EL', 'ES', 'FI', 'FR', 'GB', 'HR', 'HU', 'IE', 'IT', 'LT', 'LU', 'LV', 'MT', 'NL', 'PL', 'PT', 'RO', 'SE', 'SI', 'SK'];
    return EU.indexOf(countrycode.toUpperCase()) !== -1;
}

function getCountry(customer) {
  var card = customer.default_card; // jshint ignore:line

  var country = customer.cards.data.reduce(function (last, current) {
    if (current.id === card) {
      return current.country;
    } else {
      return last;
    }
  }, null);

  if (country === null) {
    if (customer.cards.data.length === 1) {
      return customer.cards.data[0].country;
    } else {
      // TODO multipile cards and no default ??
      return customer.cards.data[0].country;
    }
  } else {
    return country;
  }

}

exports.getVATByCountry = getVATByCountry;
exports.countryIsInEU = countryIsInEU;
exports.getCountry = getCountry;
<commit_msg>fixes<commit_after>var Promise = require('promise');
var VATRates = require('./vat-rates.json').data;

function getVATByCountry(countrycode) {
  if (countrycode === 'GB') {
    countrycode = 'UK';
  }
  var rate = VATRates[countrycode].standard_rate / 100;
  return Promise.resolve(rate);
}

function countryIsInEU(countrycode) {
    var EU = ['AT', 'BE', 'BG', 'CY', 'CZ', 'DE', 'DK', 'EE', 'EL', 'ES', 'FI', 'FR', 'GB', 'HR', 'HU', 'IE', 'IT', 'LT', 'LU', 'LV', 'MT', 'NL', 'PL', 'PT', 'RO', 'SE', 'SI', 'SK'];
    return EU.indexOf(countrycode.toUpperCase()) !== -1;
}

function getCountry(customer) {
  var card = customer.default_card; // jshint ignore:line

  var country = customer.cards.data.reduce(function (last, current) {
    if (current.id === card) {
      return current.country;
    } else {
      return last;
    }
  }, null);

  if (country === null) {
    if (customer.cards.data.length === 1) {
      return customer.cards.data[0].country;
    } else {
      // TODO multipile cards and no default ??
      return customer.cards.data[0].country;
    }
  } else {
    return country;
  }

}

exports.getVATByCountry = getVATByCountry;
exports.countryIsInEU = countryIsInEU;
exports.getCountry = getCountry;
<|endoftext|>


<commit_before>$( document ).ready(function() { //initiated when the page is first loaded

	var date = new Date();
	var day_of_month = date.getDate();
	var modal = document.getElementById('dayModal');

	generateMonthView(date.getMonth(), date.getFullYear());

	month_view = [];

	$('.days').click(function(e){

		e.preventDefault();

		$('.days').css('color','white');
		$(this).css('color', 'black');

		modal.style.display = "block";

		var day = parseInt($(this).text());
		var month = date.getMonth();
		var year = date.getFullYear();

		setBrowserDate(day,month,year);
		getEvents(month,day);
	});

	$('.close').click(function(e){

		e.preventDefault();

		modal.style.display = "none";

	});

	$('#button_year').click(function(e){

		e.preventDefault();

		window.location.href = "YearView.html";

    });

	$('.buttonNextMonth').click(function(e){

		e.preventDefault();

		date.setMonth(date.getMonth()+1);
		generateMonthView(date.getMonth(), date.getFullYear());

	});

	$('.buttonPreviousMonth').click(function(e){

		e.preventDefault();

		date.setMonth(date.getMonth()-1);
		generateMonthView(date.getMonth(), date.getFullYear());

	});

});

function generateMonthView(month, year){

	$('.monthHeader').text(getMonthFromNum(month) + " " + year);

	var display_dates = populateMonthArray(month, year)
	var table_id = "";
	var print_white = false;

	for(var i = 0; i < display_dates.length; i++ ){

		table_id = "#day_".concat(i);
		$(table_id).text(display_dates[i]);

		if(display_dates[i] == 1){

			print_white = !print_white;
		}

		if(print_white){
			$(table_id).css('color','white');
		}
		else {
			$(table_id).css('color','#C8C8C8');
		}

	}

	if( display_dates.length <= 35){

		$('#week_5').hide();
	}
	else {

		$('#week_5').show();
	}

}

function getDayFromNum(num){

	return ['Sunday','Monday','Tuesday','Wednesday','Thursday', 'Friday', 'Saturday'][num];
}

function getMonthFromNum(num){

	return ['January','February','March','April','May','June','July','August','September','October','November','December'][num];
}

function getDaysFromMonthNum(num){

	return [31,28,31,30,31,30,31,31,30,31,30,31][num];
}

function getNumFromMonth(month){

	return ['January','February','March','April','May','June','July','August','September','October','November','December'].indexOf(month);
}

function toggleYearView(year) {

    var t = document.getElementById('table');
    var nmm =  document.getElementById('nextMonth');
	var pmm =  document.getElementById('prevMonth');
	var moo = document.getElementById('month_table');

   	t.style.display = "table";
	moo.style.display = 'none';
	pmm.style.display = 'none';
	nmm.style.display = 'none';

	return;
}

function toggleMonthView(month) {

    var mo = document.getElementById('month_table');
    var nm =  document.getElementById('nextMonth');
	var pm =  document.getElementById('prevMonth');
	var y = document.getElementById('table');

	mo.style.display = 'table';
	pm.style.display = 'inline';
	nm.style.display = 'inline';
	y.style.display = "none";

    return;
}

//Information on browser storage was found here: http://www.w3schools.com/html/html5_webstorage.asp
function setBrowserDate(day,month,year){

	if (typeof(Storage) !== "undefined") {

		localStorage.setItem("day", day.toString());
		localStorage.setItem("month", month.toString());
		localStorage.setItem("year", year.toString());
	}
	else {

		//if no browser storage do something
	}
}
function getBrowserDate(day,month,year){

	if (typeof(Storage) !== "undefined") {

		var day = localStorage.getItem("day", day);
		var month = localStorage.getItem("month", month);
		var year = localStorage.getItem("year", year);

		var date = new Date(year, month, day, 0, 0, 0, 0);

		return date;
	}
	else {

		//if no browser storage do something
	}
}
//information for this funciton from http://www.w3schools.com/ajax/default.asp
function getEvents(month,day){
	var xmlhttp = new XMLHttpRequest();
	xmlhttp.onreadystatechange = function() {
		if (this.readyState == 4 && this.status == 200) {
     document.getElementById("viewEvent").innerHTML = this.responseText;
    	}
  };
  xmlhttp.open("GET", "getEvents.php?month="+month+"&day="+day, true);
  xhttp.send();
}

function postEvent(month,day,event){
	var xmlhttp = new XMLHttpRequest();
	xmlhttp.onreadystatechange = function() {
		if (this.readyState == 4 && this.status == 200) {
     document.getElementById("demo").innerHTML = this.responseText;
    	}
 	 };
 	xmlhttp.open("GET", "postEvent.php?month="+month+"&day="+day+"&event="+event, true);
  	xmlhttp.send();
}

function populateMonthArray(month, year){

	var dummy_date = new Date(year, month, 1, 0, 0, 0, 0);
	var first_day_of_week = dummy_date.getDay();
	var last_index = first_day_of_week + getDaysFromMonthNum(month);

	var array = [];

	var num = 1;
	for(var i=first_day_of_week;i< last_index; i++){

		array.push(num);
		num++
	}

	num = getDaysFromMonthNum(dummy_date.getMonth()-1);
	for(var i=first_day_of_week-1; i>=0 ;i--) {

		array.unshift(num);
		num--;
	}
	console.log(array.length);
	num = 1;
	if(array.length >= 36){

		for(var i = last_index + 1; i <= 45; i++ ){

			array.push(num);
			num++;
		}
	}
	else {

		for(var i = last_index + 1; i <= 35; i++){

			array.push(num);
			num++;
		}
	}

	for(var i = 0; i<array.length;i++){

		console.log(array[i]);
	}
	return array;
}<commit_msg>cleaned up a couple things.<commit_after>$( document ).ready(function() { //initiated when the page is first loaded

	var date = new Date();
	var day_of_month = date.getDate();
	var modal = document.getElementById('dayModal');

	generateMonthView(date.getMonth(), date.getFullYear());

	var month_view = [];

	$('.days').click(function(e){

		e.preventDefault();

		$('.days').css('color','white');
		$(this).css('color', 'black');

		modal.style.display = "block";

		var day = parseInt($(this).text());
		var month = date.getMonth();
		var year = date.getFullYear();

		setBrowserDate(day,month,year);
		getEvents(month,day);
	});

	$('.close').click(function(e){

		e.preventDefault();

		modal.style.display = "none";

	});

	$('#button_year').click(function(e){

		e.preventDefault();

		window.location.href = "YearView.html";

    });

	$('.buttonNextMonth').click(function(e){

		e.preventDefault();

		date.setMonth(date.getMonth()+1);
		generateMonthView(date.getMonth(), date.getFullYear());

	});

	$('.buttonPreviousMonth').click(function(e){

		e.preventDefault();

		date.setMonth(date.getMonth()-1);
		generateMonthView(date.getMonth(), date.getFullYear());

	});

});

function generateMonthView(month, year){

	$('.monthHeader').text(getMonthFromNum(month) + " " + year);

	month_view = populateMonthArray(month, year)
	var table_id = "";
	var print_white = false;

	for(var i = 0; i < month_view.length; i++ ){

		table_id = "#day_".concat(i);
		$(table_id).text(month_view[i]);

		if(month_view[i] == 1){

			print_white = !print_white;
		}

		if(print_white){
			$(table_id).css('color','white');
		}
		else {
			$(table_id).css('color','#C8C8C8');
		}

	}

	if( month_view.length <= 35){

		$('#week_5').hide();
	}
	else {

		$('#week_5').show();
	}

}

function getDayFromNum(num){

	return ['Sunday','Monday','Tuesday','Wednesday','Thursday', 'Friday', 'Saturday'][num];
}

function getMonthFromNum(num){

	return ['January','February','March','April','May','June','July','August','September','October','November','December'][num];
}

function getDaysFromMonthNum(num){

	return [31,28,31,30,31,30,31,31,30,31,30,31][num];
}

function getNumFromMonth(month){

	return ['January','February','March','April','May','June','July','August','September','October','November','December'].indexOf(month);
}

function toggleYearView(year) {

    var t = document.getElementById('table');
    var nmm =  document.getElementById('nextMonth');
	var pmm =  document.getElementById('prevMonth');
	var moo = document.getElementById('month_table');

   	t.style.display = "table";
	moo.style.display = 'none';
	pmm.style.display = 'none';
	nmm.style.display = 'none';

	return;
}

function toggleMonthView(month) {

    var mo = document.getElementById('month_table');
    var nm =  document.getElementById('nextMonth');
	var pm =  document.getElementById('prevMonth');
	var y = document.getElementById('table');

	mo.style.display = 'table';
	pm.style.display = 'inline';
	nm.style.display = 'inline';
	y.style.display = "none";

    return;
}

//Information on browser storage was found here: http://www.w3schools.com/html/html5_webstorage.asp
function setBrowserDate(day,month,year){

	if (typeof(Storage) !== "undefined") {

		localStorage.setItem("day", day.toString());
		localStorage.setItem("month", month.toString());
		localStorage.setItem("year", year.toString());
	}
	else {

		//if no browser storage do something
	}
}
function getBrowserDate(day,month,year){

	if (typeof(Storage) !== "undefined") {

		var day = localStorage.getItem("day", day);
		var month = localStorage.getItem("month", month);
		var year = localStorage.getItem("year", year);

		var date = new Date(year, month, day, 0, 0, 0, 0);

		return date;
	}
	else {

		//if no browser storage do something
	}
}
//information for this funciton from http://www.w3schools.com/ajax/default.asp
function getEvents(month,day){
	var xmlhttp = new XMLHttpRequest();
	xmlhttp.onreadystatechange = function() {
		if (this.readyState == 4 && this.status == 200) {
     document.getElementById("viewEvent").innerHTML = this.responseText;
    	}
  };
  xmlhttp.open("GET", "getEvents.php?month="+month+"&day="+day, true);
  xhttp.send();
}

function postEvent(month,day,event){
	var xmlhttp = new XMLHttpRequest();
	xmlhttp.onreadystatechange = function() {
		if (this.readyState == 4 && this.status == 200) {
     document.getElementById("demo").innerHTML = this.responseText;
    	}
 	 };
 	xmlhttp.open("GET", "postEvent.php?month="+month+"&day="+day+"&event="+event, true);
  	xmlhttp.send();
}

function populateMonthArray(month, year){

	var dummy_date = new Date(year, month, 1, 0, 0, 0, 0);
	var first_day_of_week = dummy_date.getDay();
	var last_index = first_day_of_week + getDaysFromMonthNum(month);

	var array = [];

	var num = 1;
	for(var i=first_day_of_week;i< last_index; i++){

		array.push(num);
		num++
	}

	num = getDaysFromMonthNum(dummy_date.getMonth()-1);
	for(var i=first_day_of_week-1; i>=0 ;i--) {

		array.unshift(num);
		num--;
	}
	num = 1;
	if(array.length >= 36){

		for(var i = last_index + 1; i <= 45; i++ ){

			array.push(num);
			num++;
		}
	}
	else {

		for(var i = last_index + 1; i <= 35; i++){

			array.push(num);
			num++;
		}
	}
	return array;
}<|endoftext|>


<commit_before>
var AST    = require('../ast'),
    types  = require('../types'),
    repeat = require('../util').repeat

// Context of the compiler as it's generating code ----------------------------

function Context () {
  // Keeping track of names that conflict and need to be munged/aliased.
  this.conflicts = {}
  this._indent = 0
}
Context.prototype.incrementIndent = function () { this._indent += 2 }
Context.prototype.decrementIndent = function () { this._indent -= 2 }
Context.prototype.indent = function (additionalIndent) {
  if (additionalIndent === undefined) { additionalIndent = 0 }
  return repeat(' ', this._indent + additionalIndent)
}

function wrapContextIndent(func) {
  return function (context) {
    context.incrementIndent()
    var ret = func.call(this, context)
    context.decrementIndent()
    return ret
  }
}

// JS code-generating compiler ------------------------------------------------

AST.Root.prototype.compile = function () {
  // Compilation context
  var context = new Context()
  return this.statements.map(function compile_statements(stmt) {
    return stmt.compile(context)
  }).join('')
}

AST.Binary.prototype.compile = function (context, opts) {
  var lexpr = this.lexpr.compile(context)
  var rexpr = this.rexpr.compile(context)
  var ret   = lexpr+' '+this.op+' '+rexpr
  if (opts && opts.statement === true) { ret += ";\n" }
  return ret
}

AST.Literal.prototype.compile  = function (context) {
  return this.value.toString()
}

AST.Assignment.prototype.compile = function (context, opts) {
  var term = ";\n"
  if (opts && opts.omitTerminator === true) { term = '' }
  if (this.type === 'var' || this.type === 'let') {
    // TODO: Register name in context scope and check for conflicts.
    var lvalue = this.lvalue.name
    if (this.rvalue !== false) {
      var rvalue = this.rvalue.compile(context)
      return 'var '+lvalue+' '+this.op+' '+rvalue+term
    } else {
      return 'var '+lvalue+term
    }
  } else {
    // TODO: Handle more complex path assignments
    // throw new Error('Compilation of path-assignments not yet implemented')
    var lvalue = this.lvalue.name
    this.lvalue.path.forEach(function (item) {
      lvalue += item.compile(context)
    })
    var rvalue = this.rvalue.compile(context)
    return lvalue+' '+this.op+' '+rvalue+term
  }
}

AST.Function.prototype.compile = function (context) {
  // Skip compilation for functions that are children of multi types
  if (this.isChildOfMulti()) { return "" }

  var args = this.args.map(function (arg) { return arg.name }),
      ret  = 'function ('+args.join(', ')+") {\n",
      defs = ''
  // Build assignments for any default arguments
  for (var i = args.length - 1; i >= 0; i--) {
    var arg  = this.args[i],
        name = arg.name,
        def  = arg.def
    if (def) {
      var value = def.compile(context),
          ind   = context.indent(2)
      // Prepend the default to the body
      defs = ind+'if ('+name+' === undefined) { '+name+' = '+value+"; }\n"+defs
    }
  }// for args
  ret += defs
  ret += this.block.compile(context)
  ret += "}"
  // Name property indicates it's a function statement
  if (this.name) {
    ret += "\n"
  }
  return ret
}

AST.Multi.prototype.compile = function (context) {
  // console.log(this)
  var args = this.args.map(function (arg) { return arg.name }),
      name = this.name
  // Build function definition
  var ret = 'function '+name+' ('+args.join(', ')+") {\n"
  context.incrementIndent()

  // Figure out the branches for the dispatcher
  var def = [], cond = []
  for (var i = this.type.functionNodes.length - 1; i >= 0; i--) {
    var fn = this.type.functionNodes[i]
    fn.childName = name+'_'+(i+1)
    if (fn.when) {
      cond.push(fn)
    } else {
      // If there's no `when` condition then it's a default
      def.push(fn)
    }
  }
  if (def.length > 1) {
    var n = def.length
    throw new TypeError('Multi has more than 1 default branch (has '+n+')', this)
  }
  // De-array default to just the node or null
  def = (def.length === 0) ? null : def[0]

  // Build the dispatcher
  var ind = context.indent()
  ret += ind+"switch (false) {\n"
  cond.forEach(function (condFunction) {
    var childName = condFunction.childName
    ret += ind+"case !("+condFunction.when.compile(context)+"):\n"
    ret += context.indent(2)+"return "+childName+"("+args.join(", ")+");\n"
  })
  ret += ind+"default:\n"
  var defInd = context.indent(2)
  if (def) {
    ret += defInd+"return "+def.childName+"("+args.join(", ")+");\n"
  } else {
    ret += defInd+"throw new Error('Fell through to default branch');\n"
  }
  ret += ind+"}\n"

  // Build all of the implementation functions
  ind = context.indent()
  var i = 1
  this.type.functionNodes.forEach(function (functionNode) {
    var functionName = functionNode.childName,
        functionArgs = functionNode.args.map(function (arg) { return arg.name })
    ret += ind+'function '+functionName+" ("+functionArgs.join(', ')+") {\n"
    ret += functionNode.block.compile(context)
    ret += ind+"}\n"

    i += 1
  })

  context.decrementIndent()
  ret += context.indent()+"}\n"
  return ret
}

AST.Class.prototype.compile = function (context) {
  var klass = this.type,
      name  = this.name
  // Generate the simple class function
  // TODO: Multiple-dispatch initializers
  var ret = "function "+name+" () {\n"
  // Compile the first initializer
  var initializer = null
  for (var i = 0; i < this.definition.statements.length; i++) {
    var node = this.definition.statements[i]
    if (node instanceof AST.Init) {
      if (initializer !== null) {
        throw new Error("Multiple initializers not yet implemented; in class "+name)
      }
      initializer = node
    }
    if (!(node instanceof AST.Function)) { continue }
  }
  if (initializer) {
    ret += initializer.block.compile(context)
  }
  ret += context.indent()+"}\n",
  // Now add all the instance methods
  this.definition.statements.forEach(function (node) {
    if (!(node instanceof AST.Function)) { return }
    var methodName = node.name
    ret += name+".prototype."+methodName+" = "+node.compile(context)
  })
  return ret
}

AST.New.prototype.compile = function (context) {
  var name = this.name,
      args = this.args.map(function (arg) {
        return arg.compile(context)
      }).join(', ')
  return "(new "+name+"("+args+"))"
}

AST.Call.prototype.compile = function (context) {
  var args = this.args.map(function (arg) {
    return arg.compile(context)
  })
  return '('+args.join(', ')+')'
}

AST.Property.prototype.compile = function (context) {
  return '.'+this.name
}

AST.If.prototype.compile = function (context) {
  var ind = context.indent()
  var ret = 'if ('+this.cond.compile()+") {\n"
  ret += this.block.compile(context)
  ret += ind+"}\n"
  return ret
}

AST.While.prototype.compile = function (context) {
  var ind = context.indent()
  var ret = 'while ('
  ret += this.expr.compile(context, {omitTerminator: true})
  ret += ') {\n'
  ret += this.block.compile(context)
  ret += ind + "}\n"
  return ret
}

AST.For.prototype.compile = function (context) {
  var cond = this.cond
  var ind  = context.indent()
  var ret  = 'for ('
  ret += this.init.compile(context, {omitTerminator: true})+'; '
  ret += (cond ? cond.compile(context) : '')+'; '
  ret += this.after.compile(context, {omitTerminator: true})+") {\n"
  ret += this.block.compile(context)
  ret += ind+"}\n"
  return ret
}

AST.Chain.prototype.compile = function (context) {
  var ret = this.name
  this.tail.forEach(function (item) {
    ret += item.compile(context)
  })
  return ret
}

AST.Return.prototype.compile  = function (context) {
  return 'return '+this.expr.compile(context)+";\n"
}

AST.Block.prototype.compile = wrapContextIndent(function (context) {
  var ret = []
  var ind = context.indent()
  this.statements.forEach(function (stmt) {
    var opts = {}
    if (stmt instanceof AST.Binary) {
      opts.statement = true
    }
    ret.push(ind+stmt.compile(context, opts))
  })
  return ret.join('')
})
<commit_msg>Refactor compilation of initializers in classes<commit_after>
var AST    = require('../ast'),
    types  = require('../types'),
    repeat = require('../util').repeat

// Context of the compiler as it's generating code ----------------------------

function Context () {
  // Keeping track of names that conflict and need to be munged/aliased.
  this.conflicts = {}
  this._indent = 0
}
Context.prototype.incrementIndent = function () { this._indent += 2 }
Context.prototype.decrementIndent = function () { this._indent -= 2 }
Context.prototype.indent = function (additionalIndent) {
  if (additionalIndent === undefined) { additionalIndent = 0 }
  return repeat(' ', this._indent + additionalIndent)
}

function wrapContextIndent(func) {
  return function (context) {
    context.incrementIndent()
    var ret = func.call(this, context)
    context.decrementIndent()
    return ret
  }
}

// JS code-generating compiler ------------------------------------------------

AST.Root.prototype.compile = function () {
  // Compilation context
  var context = new Context()
  return this.statements.map(function compile_statements(stmt) {
    return stmt.compile(context)
  }).join('')
}

AST.Binary.prototype.compile = function (context, opts) {
  var lexpr = this.lexpr.compile(context)
  var rexpr = this.rexpr.compile(context)
  var ret   = lexpr+' '+this.op+' '+rexpr
  if (opts && opts.statement === true) { ret += ";\n" }
  return ret
}

AST.Literal.prototype.compile  = function (context) {
  return this.value.toString()
}

AST.Assignment.prototype.compile = function (context, opts) {
  var term = ";\n"
  if (opts && opts.omitTerminator === true) { term = '' }
  if (this.type === 'var' || this.type === 'let') {
    // TODO: Register name in context scope and check for conflicts.
    var lvalue = this.lvalue.name
    if (this.rvalue !== false) {
      var rvalue = this.rvalue.compile(context)
      return 'var '+lvalue+' '+this.op+' '+rvalue+term
    } else {
      return 'var '+lvalue+term
    }
  } else {
    // TODO: Handle more complex path assignments
    // throw new Error('Compilation of path-assignments not yet implemented')
    var lvalue = this.lvalue.name
    this.lvalue.path.forEach(function (item) {
      lvalue += item.compile(context)
    })
    var rvalue = this.rvalue.compile(context)
    return lvalue+' '+this.op+' '+rvalue+term
  }
}

AST.Function.prototype.compile = function (context) {
  // Skip compilation for functions that are children of multi types
  if (this.isChildOfMulti()) { return "" }

  var args = this.args.map(function (arg) { return arg.name }),
      ret  = 'function ('+args.join(', ')+") {\n",
      defs = ''
  // Build assignments for any default arguments
  for (var i = args.length - 1; i >= 0; i--) {
    var arg  = this.args[i],
        name = arg.name,
        def  = arg.def
    if (def) {
      var value = def.compile(context),
          ind   = context.indent(2)
      // Prepend the default to the body
      defs = ind+'if ('+name+' === undefined) { '+name+' = '+value+"; }\n"+defs
    }
  }// for args
  ret += defs
  ret += this.block.compile(context)
  ret += "}"
  // Name property indicates it's a function statement
  if (this.name) {
    ret += "\n"
  }
  return ret
}

AST.Multi.prototype.compile = function (context) {
  // console.log(this)
  var args = this.args.map(function (arg) { return arg.name }),
      name = this.name
  // Build function definition
  var ret = 'function '+name+' ('+args.join(', ')+") {\n"
  context.incrementIndent()

  // Figure out the branches for the dispatcher
  var def = [], cond = []
  for (var i = this.type.functionNodes.length - 1; i >= 0; i--) {
    var fn = this.type.functionNodes[i]
    fn.childName = name+'_'+(i+1)
    if (fn.when) {
      cond.push(fn)
    } else {
      // If there's no `when` condition then it's a default
      def.push(fn)
    }
  }
  if (def.length > 1) {
    var n = def.length
    throw new TypeError('Multi has more than 1 default branch (has '+n+')', this)
  }
  // De-array default to just the node or null
  def = (def.length === 0) ? null : def[0]

  // Build the dispatcher
  var ind = context.indent()
  ret += ind+"switch (false) {\n"
  cond.forEach(function (condFunction) {
    var childName = condFunction.childName
    ret += ind+"case !("+condFunction.when.compile(context)+"):\n"
    ret += context.indent(2)+"return "+childName+"("+args.join(", ")+");\n"
  })
  ret += ind+"default:\n"
  var defInd = context.indent(2)
  if (def) {
    ret += defInd+"return "+def.childName+"("+args.join(", ")+");\n"
  } else {
    ret += defInd+"throw new Error('Fell through to default branch');\n"
  }
  ret += ind+"}\n"

  // Build all of the implementation functions
  ind = context.indent()
  var i = 1
  this.type.functionNodes.forEach(function (functionNode) {
    var functionName = functionNode.childName,
        functionArgs = functionNode.args.map(function (arg) { return arg.name })
    ret += ind+'function '+functionName+" ("+functionArgs.join(', ')+") {\n"
    ret += functionNode.block.compile(context)
    ret += ind+"}\n"

    i += 1
  })

  context.decrementIndent()
  ret += context.indent()+"}\n"
  return ret
}

AST.Class.prototype.compile = function (context) {
  var klass = this.type,
      name  = this.name
  // Generate the simple class function
  // TODO: Multiple-dispatch initializers
  var ret = "function "+name+" () {\n"
  // Compile the first initializer
  var initializers = []
  for (var i = 0; i < this.definition.statements.length; i++) {
    var node = this.definition.statements[i]
    if (node instanceof AST.Init) {
      initializers.push(node)
    }
  }
  if (initializers.length > 1) {
    throw new Error("Multiple initializers not yet implemented; in class "+name)
  }
  if (initializers.length === 1) {
    ret += initializers[0].block.compile(context)
  }
  ret += context.indent()+"}\n",
  // Now add all the instance methods
  this.definition.statements.forEach(function (node) {
    if (!(node instanceof AST.Function)) { return }
    var methodName = node.name
    ret += name+".prototype."+methodName+" = "+node.compile(context)
  })
  return ret
}

AST.New.prototype.compile = function (context) {
  var name = this.name,
      args = this.args.map(function (arg) {
        return arg.compile(context)
      }).join(', ')
  return "(new "+name+"("+args+"))"
}

AST.Call.prototype.compile = function (context) {
  var args = this.args.map(function (arg) {
    return arg.compile(context)
  })
  return '('+args.join(', ')+')'
}

AST.Property.prototype.compile = function (context) {
  return '.'+this.name
}

AST.If.prototype.compile = function (context) {
  var ind = context.indent()
  var ret = 'if ('+this.cond.compile()+") {\n"
  ret += this.block.compile(context)
  ret += ind+"}\n"
  return ret
}

AST.While.prototype.compile = function (context) {
  var ind = context.indent()
  var ret = 'while ('
  ret += this.expr.compile(context, {omitTerminator: true})
  ret += ') {\n'
  ret += this.block.compile(context)
  ret += ind + "}\n"
  return ret
}

AST.For.prototype.compile = function (context) {
  var cond = this.cond
  var ind  = context.indent()
  var ret  = 'for ('
  ret += this.init.compile(context, {omitTerminator: true})+'; '
  ret += (cond ? cond.compile(context) : '')+'; '
  ret += this.after.compile(context, {omitTerminator: true})+") {\n"
  ret += this.block.compile(context)
  ret += ind+"}\n"
  return ret
}

AST.Chain.prototype.compile = function (context) {
  var ret = this.name
  this.tail.forEach(function (item) {
    ret += item.compile(context)
  })
  return ret
}

AST.Return.prototype.compile  = function (context) {
  return 'return '+this.expr.compile(context)+";\n"
}

AST.Block.prototype.compile = wrapContextIndent(function (context) {
  var ret = []
  var ind = context.indent()
  this.statements.forEach(function (stmt) {
    var opts = {}
    if (stmt instanceof AST.Binary) {
      opts.statement = true
    }
    ret.push(ind+stmt.compile(context, opts))
  })
  return ret.join('')
})
<|endoftext|>


<commit_before>var inherits = require('util').inherits,
    Task = require('./Task'),
    gulp = require('gulp'),
    manifest = require('gulp-manifest'),
    Promise = require('bluebird');

var ManifestTask = function (buildHelper) {
    Task.call(this, buildHelper);
};

inherits(ManifestTask, Task);

ManifestTask.prototype.command = "manifest";
ManifestTask.prototype.availableToModule = false;
ManifestTask.prototype.action = function () {
    if (!this._buildHelper.isRelease() || !this._buildHelper.options.manifest) return Promise.resolve();
    gulp.src(this._buildHelper.getDistDirectory() + '**/*')
        .pipe(manifest(this._buildHelper.options.manifest))
        .pipe(gulp.dest(this._buildHelper.getDistDirectory()));
};

module.exports = ManifestTask;<commit_msg>Fix manifest task logging<commit_after>var inherits = require('util').inherits,
    Task = require('./Task'),
    gulp = require('gulp'),
    manifest = require('gulp-manifest'),
    Promise = require('bluebird');

var ManifestTask = function (buildHelper) {
    Task.call(this, buildHelper);
};

inherits(ManifestTask, Task);

ManifestTask.prototype.command = "manifest";
ManifestTask.prototype.availableToModule = false;
ManifestTask.prototype.action = function () {
    if (!this._buildHelper.isRelease() || !this._buildHelper.options.manifest) return Promise.resolve();
    return gulp.src(this._buildHelper.getDistDirectory() + '**/*')
        .pipe(manifest(this._buildHelper.options.manifest))
        .pipe(gulp.dest(this._buildHelper.getDistDirectory()));
};

module.exports = ManifestTask;<|endoftext|>


<commit_before>var _ = require('lodash')
  , through = require('through2')
  , walk = require('acorn/util/walk')
  , path = require('path')
  , Module = require('re-define-module')
  , generate = require('escodegen').generate

module.exports = function(config, writer) {
  return through.obj(function(file, enc, next) {
    if(!file.isAST() || file.stopProcessing) {
      this.push(file)
      next()
      return
    }

    var deps = []

    walk.simple(file.contents, {
      CallExpression: function(node) {
        var callee = node.callee
        if(callee && callee.name === 'require') {
          var args = node.arguments

          if(!args) return

          if(args.length === 1 && args[0].type === 'Literal') {
            var req = args[0].value

            if(config.map && config.map[req]) req = config.map[req]

            var dep = Module({base: file.base , requiredAs: req })

            var _filename = hasExt(req) ? req : req + '.js'
              , _path = path.resolve(path.dirname(file.path), _filename)

            if(req[0] != '.') _path = req

            dep.path = _path

            if(file.pkgName) dep.pkgName = file.pkgName
            if(file.base) dep.base = file.base

            args[0].value = dep.name

            dep.revert = function() {
              args[0].value = req
              dep.name = req
            }
            dep.update = function(name) {
              args[0].value = name
              dep.name = name
            }

            deps.push(dep)
          } else {
            JSON.parse(config.showWarnings) && console.log('//warning: re-define rewrite only static require calls', file, file.path, generate(node))
          }
        }
      }
    })

    function hasExt(val) { return !!path.extname(val) }

    _.each(deps, function(d) { writer.write(d) })
    file.dependencies = deps

    this.push(file)
    next()
  })
}

<commit_msg>resolving require when pointing to dir (dirname/index.js)<commit_after>var _ = require('lodash')
  , through = require('through2')
  , walk = require('acorn/util/walk')
  , path = require('path')
  , Module = require('re-define-module')
  , generate = require('escodegen').generate

module.exports = function(config, writer) {
  return through.obj(function(file, enc, next) {
    if(!file.isAST() || file.stopProcessing) {
      this.push(file)
      next()
      return
    }

    var deps = []

    walk.simple(file.contents, {
      CallExpression: function(node) {
        var callee = node.callee
        if(callee && callee.name === 'require') {
          var args = node.arguments

          if(!args) return

          if(args.length === 1 && args[0].type === 'Literal') {
            var req = args[0].value

            if(/.*\/$/g.test(req)) req = req + 'index.js' //require('./lib/')
            if(config.map && config.map[req]) req = config.map[req]

            var dep = Module({base: file.base , requiredAs: req })

            var _filename = hasExt(req) ? req : req + '.js'
              , _path = path.resolve(path.dirname(file.path), _filename)

            if(req[0] != '.') _path = req

            dep.path = _path

            if(file.pkgName) dep.pkgName = file.pkgName
            if(file.base) dep.base = file.base

            args[0].value = dep.name

            dep.revert = function() {
              args[0].value = req
              dep.name = req
            }
            dep.update = function(name) {
              args[0].value = name
              dep.name = name
            }

            deps.push(dep)
          } else {
            JSON.parse(config.showWarnings) && console.log('//warning: re-define rewrite only static require calls', file, file.path, generate(node))
          }
        }
      }
    })

    function hasExt(val) { return !!path.extname(val) }

    _.each(deps, function(d) { writer.write(d) })
    file.dependencies = deps

    this.push(file)
    next()
  })
}

<|endoftext|>


<commit_before>"use strict";

module.exports = function(api) {
  const presets = [
    [
      "@babel/preset-env",
      {
        targets: {
          browsers: ">= 0.1%, last 1 version, not dead, current node"
        },
        modules: api.env("webpack") ? false : "commonjs",
        shippedProposals: true,
        useBuiltIns: "usage"
      }
    ]
  ];

  const plugins = [
    ["@babel/plugin-proposal-nullish-coalescing-operator", { loose: true }],
    "@babel/plugin-proposal-export-default-from",
    "@babel/plugin-proposal-export-namespace-from",
    "lodash",
    !api.env("webpack") && "babel-plugin-dynamic-import-node"
  ].filter(Boolean);

  return { presets, plugins };
};
<commit_msg>fix(browsers): attempt to fix issue with travis build by excluding ie 11<commit_after>"use strict";

module.exports = function(api) {
  const presets = [
    [
      "@babel/preset-env",
      {
        targets: {
          browsers: ">= 0.1%, last 1 version, not ie 11, not dead, current node"
        },
        modules: api.env("webpack") ? false : "commonjs",
        shippedProposals: true,
        useBuiltIns: "usage"
      }
    ]
  ];

  const plugins = [
    ["@babel/plugin-proposal-nullish-coalescing-operator", { loose: true }],
    "@babel/plugin-proposal-export-default-from",
    "@babel/plugin-proposal-export-namespace-from",
    "lodash",
    !api.env("webpack") && "babel-plugin-dynamic-import-node"
  ].filter(Boolean);

  return { presets, plugins };
};
<|endoftext|>


<commit_before>
/**
 * Module dependencies.
 */

var Transport = require('../transport')
  , XHR = require('./polling-xhr')
  , JSON = require('./polling-jsonp')
  , util = require('../util')
  , parser = require('../parser')
  , global = this

/**
 * Module exports.
 */

module.exports = Polling;

/**
 * Polling interface.
 *
 * @param {Object} opts
 * @api private
 */

function Polling (opts) {
  Transport.call(this, opts);
}

/**
 * Inherits from Transport.
 */

util.inherits(Polling, Transport);

/**
 * Transport name.
 */

Polling.prototype.name = 'polling';

/**
 * Opens the socket (triggers polling). We write a PING message to determine
 * when the transport is open.
 *
 * @api private
 */

Polling.prototype.doOpen = function () {
  this.poll();
};

/**
 * Pauses polling.
 *
 * @param {Function} callback upon flush
 * @api private
 */

Polling.prototype.pause = function (onFlush) {
  this.paused = true;

  var pending = 0;

  if (this.polling) {
    pending++;
    this.once('data', function () {
      --pending || onFlush();
    });
  }

  if (this.buffer) {
    pending++;
    this.once('flush', function () {
      --pending || onFlush();
    });
  }
};

/**
 * Starts polling cycle.
 *
 * @api public
 */

Polling.prototype.poll = function () {
  if (!this.paused) {
    this.polling = true;
    this.doPoll();
    this.emit('poll');
  }
};

/**
 * Overloads onData to detect payloads.
 *
 * @api private
 */

Polling.prototype.onData = function (data) {
  var packets = parser.decodePayload(data);

  for (var i = 0, l = packets.length; i < l; i++) {
    // if its a pong to our initial ping we consider the connection open
    if ('opening' == this.readyState) {
      if ('pong' == packets[i].type) {
        this.onOpen();
        continue;
      } else {
        this.error('protocol violation');
        return;
      }
    }

    // if its a close packet, we close the ongoing requests
    if ('close' == packets[i].type) {
      // doClose will cancel existing requests, and then fire a close packet
      // to signal the server we're closed, since we can't kill the socket/s
      this.doClose();
      this.onClose();
      return;
    }

    // otherwise bypass onData and handle the message
    this.onPacket(packets[i]);
  }

  // if we got data we're not polling
  this.polling = false;

  // trigger next poll
  this.poll();
};

/**
 * For polling, send a close packet.
 *
 * @api private
 */

Polling.prototype.doClose = function () {
  // we mute existing buffers and bypass buffers
  this.write({ type: 'close' });
};

/**
 * Writes a packets payload.
 *
 * @param {Array} data packets
 * @api private
 */

Polling.prototype.writeMany = function (packets) {
  this.doWrite(parser.encodePayload(packets));
};

/**
 * Writes a single-packet payload.
 *
 * @parma {Object} data packet
 * @api private
 */

Polling.prototype.write = function (packet) {
  this.writeMany([packet]);
};

/**
 * Generates uri for connection.
 *
 * @api private
 */

Polling.prototype.uri = function () {
  var opts = this.options
    , query = util.qs(opts.query)
    , schema = opts.secure ? 'https' : 'http'
    , port = ''

  // avoid port if default for schema
  if (('https' == schema && opts.port != 443)
    || ('http' == schema && opts.port != 80)) {
    port = ':' + opts.port;
  }

  // prepend ? to query
  if (query.length) {
    query = '?' + query;
  }

  return schema + opts.host + port + opts.path + query;
};
<commit_msg>Fixed Polling data handler<commit_after>
/**
 * Module dependencies.
 */

var Transport = require('../transport')
  , XHR = require('./polling-xhr')
  , JSON = require('./polling-jsonp')
  , util = require('../util')
  , parser = require('../parser')
  , global = this

/**
 * Module exports.
 */

module.exports = Polling;

/**
 * Polling interface.
 *
 * @param {Object} opts
 * @api private
 */

function Polling (opts) {
  Transport.call(this, opts);
}

/**
 * Inherits from Transport.
 */

util.inherits(Polling, Transport);

/**
 * Transport name.
 */

Polling.prototype.name = 'polling';

/**
 * Opens the socket (triggers polling). We write a PING message to determine
 * when the transport is open.
 *
 * @api private
 */

Polling.prototype.doOpen = function () {
  this.poll();
};

/**
 * Pauses polling.
 *
 * @param {Function} callback upon flush
 * @api private
 */

Polling.prototype.pause = function (onFlush) {
  this.paused = true;

  var pending = 0;

  if (this.polling) {
    pending++;
    this.once('data', function () {
      --pending || onFlush();
    });
  }

  if (this.buffer) {
    pending++;
    this.once('flush', function () {
      --pending || onFlush();
    });
  }
};

/**
 * Starts polling cycle.
 *
 * @api public
 */

Polling.prototype.poll = function () {
  if (!this.paused) {
    this.polling = true;
    this.doPoll();
    this.emit('poll');
  }
};

/**
 * Overloads onData to detect payloads.
 *
 * @api private
 */

Polling.prototype.onData = function (data) {
  // if we got data we're not polling
  this.polling = false;

  // decode payload
  var packets = parser.decodePayload(data);

  for (var i = 0, l = packets.length; i < l; i++) {
    // if its the first message we consider the trnasport open
    if ('opening' == this.readyState) {
      this.onOpen();
    }

    // if its a close packet, we close the ongoing requests
    if ('close' == packets[i].type) {
      this.onClose();
      return;
    }

    // otherwise bypass onData and handle the message
    this.onPacket(packets[i]);
  }

  if ('open' == this.readyState) {
    // trigger next poll
    this.poll();
  }
};

/**
 * For polling, send a close packet.
 *
 * @api private
 */

Polling.prototype.doClose = function () {
  // we mute existing buffers and bypass buffers
  this.write({ type: 'close' });
};

/**
 * Writes a packets payload.
 *
 * @param {Array} data packets
 * @api private
 */

Polling.prototype.writeMany = function (packets) {
  this.doWrite(parser.encodePayload(packets));
};

/**
 * Writes a single-packet payload.
 *
 * @parma {Object} data packet
 * @api private
 */

Polling.prototype.write = function (packet) {
  this.writeMany([packet]);
};

/**
 * Generates uri for connection.
 *
 * @api private
 */

Polling.prototype.uri = function () {
  var opts = this.options
    , query = util.qs(opts.query)
    , schema = opts.secure ? 'https' : 'http'
    , port = ''

  // avoid port if default for schema
  if (('https' == schema && opts.port != 443)
    || ('http' == schema && opts.port != 80)) {
    port = ':' + opts.port;
  }

  // prepend ? to query
  if (query.length) {
    query = '?' + query;
  }

  return schema + opts.host + port + opts.path + query;
};
<|endoftext|>


<commit_before>'use strict';

var async = require('async');
var _ = require('lodash');
var moment = require('moment');

function updateApplication(args, callback) {
  var seneca = this;
  var plugin = args.role;
  var ENTITY_NS = 'cd/applications';
  var ATTENDANCE_ENTITY_NS = 'cd/attendance';
  var applications = seneca.make$(ENTITY_NS);

  var application = args.application;

  async.waterfall([
    updateApplication,
    sendEmail
  ], callback);

  function updateApplication(done) {
    applications.save$(application, function(err, application) {
      if (err) return done(err);
      done(null, application);
    });
  }

  function sendEmail(application, done) {
    if(application.status !== 'approved') return done(null, application);
    //Only send an email if the application is approved.
    async.waterfall([
      loadUser,
      loadEvent,
      saveAttendanceRecord,
      sendEmail
    ], function (err, res) {
      if(err) return done(null, {error: err});
      return done(null, res);
    });

    function loadUser(cb) {
      seneca.act({role:'cd-users', cmd:'load', id:application.userId || application.user_id}, function (err, response) {
        if(err) return cb(err);
        return cb(null, response);
      });
    }

    function loadEvent(user, cb) {
      seneca.act({role:plugin, cmd:'getEvent', id:application.eventId || application.event_id}, function (err, response) {
        if(err) return cb(err);
        return cb(null, user, response);
      });
    }

    function saveAttendanceRecord(user, event, cb) {
      if(event.type === 'recurring') {
        //Save attendance record for each event date
        var eventDates = event.dates;
        async.each(eventDates, function (eventDate, cb) {
          var attendance = {
            user_id: user.id,
            event_id: event.id,
            event_date: eventDate,
            attended: false
          };
          seneca.act({role: plugin, cmd:'saveAttendance', attendance: attendance}, cb);
        }, function (err) {
          if(err) return cb(err);
          return cb(null, user, event);
        });
      } else {
        //One-off event
        var eventDate = _.first(event.dates);
        var attendance = {
          user_id: user.id,
          event_id: event.id,
          event_date: eventDate,
          attended: false
        };
        seneca.act({role: plugin, cmd: 'saveAttendance', attendance: attendance}, function (err, response) {
          if(err) return cb(err);
          return cb(null, user, event);
        });
      }
    }

    function sendEmail(user, event, cb) {
      var recipients = [];
      if(!user.email) { //Approving attendee-u13, retrieve parent email addresses.
        seneca.act({role: 'cd-profiles', cmd: 'list', query: {userId:user.id}}, function (err, response) {
          if(err) return cb(err);
          async.each(response.parents, function (parentUserId, cb) {
            seneca.act({role: 'cd-profiles', cmd: 'list', query: {userId: parentUserId}}, function (err, response) {
              if(err) return cb(err);
              var parentEmail = response.email;
              recipients.push(parentEmail);
              cb();
            });
          }, prepareEmails)
        });
      } else {
        recipients.push(user.email);
        prepareEmails();
      }

      function prepareEmails() {
        //Send approval email to all recipients
        if(event.type === 'recurring') {
          //Recurring event
          var code = 'recurring-event-application-approved';
          var firstDate = _.first(event.dates);
          var eventStartDate = moment(firstDate).format('MMMM Do YYYY, HH:mm');
          var eventEndDate = moment(_.last(event.dates)).format('MMMM Do YYYY, HH:mm');
          //TODO: Translate weekdays.
          var weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
          var eventDay = weekdays[moment(firstDate).weekday()];
          var content = {
            userName: user.name,
            eventName: event.name,
            eventStartDate: eventStartDate,
            eventEndDate: eventEndDate,
            eventDay: eventDay,
            year: moment(new Date()).format('YYYY')
          };
          send(code, content);
        } else {
          //One-off event
          var code = 'one-off-event-application-approved';
          var eventDate = moment(_.first(event.dates)).format('MMMM Do YYYY, HH:mm');
          var content = {
            userName: user.name,
            eventName: event.name,
            eventDate: eventDate,
            year: moment(new Date()).format('YYYY')
          };
          send(code, content);
        }

        function send(code, content) {
          async.each(recipients, function (recipient, cb) {
            var payload = {
              to: recipient,
              code: code,
              content: content
            };
            seneca.act({role:'cd-dojos', cmd:'send_email', payload:payload}, cb);
          }, cb);
        }
      }
    }

  }
}

module.exports = updateApplication;
<commit_msg>Localise email templates<commit_after>'use strict';

var async = require('async');
var _ = require('lodash');
var moment = require('moment');
var fs = require('fs');
var path = require('path');
var DEFAULT_LANG = 'en_US';

function updateApplication(args, callback) {
  var seneca = this;
  var plugin = args.role;
  var ENTITY_NS = 'cd/applications';
  var ATTENDANCE_ENTITY_NS = 'cd/attendance';
  var applications = seneca.make$(ENTITY_NS);
  var so = seneca.options();
  var application = args.application;

  async.waterfall([
    updateApplication,
    sendEmail
  ], callback);

  function updateApplication(done) {
    applications.save$(application, function(err, application) {
      if (err) return done(err);
      done(null, application);
    });
  }

  function sendEmail(application, done) {
    if(application.status !== 'approved') return done(null, application);
    //Only send an email if the application is approved.
    async.waterfall([
      loadUser,
      loadEvent,
      saveAttendanceRecord,
      sendEmail
    ], function (err, res) {
      if(err) return done(null, {error: err});
      return done(null, res);
    });

    function loadUser(cb) {
      seneca.act({role:'cd-users', cmd:'load', id:application.userId || application.user_id}, function (err, response) {
        if(err) return cb(err);
        return cb(null, response);
      });
    }

    function loadEvent(user, cb) {
      seneca.act({role:plugin, cmd:'getEvent', id:application.eventId || application.event_id}, function (err, response) {
        if(err) return cb(err);
        return cb(null, user, response);
      });
    }

    function saveAttendanceRecord(user, event, cb) {
      if(event.type === 'recurring') {
        //Save attendance record for each event date
        var eventDates = event.dates;
        async.each(eventDates, function (eventDate, cb) {
          var attendance = {
            user_id: user.id,
            event_id: event.id,
            event_date: eventDate,
            attended: false
          };
          seneca.act({role: plugin, cmd:'saveAttendance', attendance: attendance}, cb);
        }, function (err) {
          if(err) return cb(err);
          return cb(null, user, event);
        });
      } else {
        //One-off event
        var eventDate = _.first(event.dates);
        var attendance = {
          user_id: user.id,
          event_id: event.id,
          event_date: eventDate,
          attended: false
        };
        seneca.act({role: plugin, cmd: 'saveAttendance', attendance: attendance}, function (err, response) {
          if(err) return cb(err);
          return cb(null, user, event);
        });
      }
    }

    function sendEmail(user, event, cb) {
      var recipients = [];
      if(!user.email) { //Approving attendee-u13, retrieve parent email addresses.
        seneca.act({role: 'cd-profiles', cmd: 'list', query: {userId:user.id}}, function (err, response) {
          if(err) return cb(err);
          async.each(response.parents, function (parentUserId, cb) {
            seneca.act({role: 'cd-profiles', cmd: 'list', query: {userId: parentUserId}}, function (err, response) {
              if(err) return cb(err);
              var parentEmail = response.email;
              recipients.push(parentEmail);
              cb();
            });
          }, prepareEmails)
        });
      } else {
        recipients.push(user.email);
        prepareEmails();
      }

      function prepareEmails() {
        //Send approval email to all recipients
        if(event.type === 'recurring') {
          //Recurring event
          var code = 'recurring-event-application-approved';
          var firstDate = _.first(event.dates);
          var eventStartDate = moment(firstDate).format('MMMM Do YYYY, HH:mm');
          var eventEndDate = moment(_.last(event.dates)).format('MMMM Do YYYY, HH:mm');
          //TODO: Translate weekdays.
          var weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
          var eventDay = weekdays[moment(firstDate).weekday()];
          var content = {
            userName: user.name,
            eventName: event.name,
            eventStartDate: eventStartDate,
            eventEndDate: eventEndDate,
            eventDay: eventDay,
            year: moment(new Date()).format('YYYY')
          };
          send(code, content);
        } else {
          //One-off event
          var code = 'one-off-event-application-approved-' + args.locality;
          var templates = {};

          try {
            templates.html = fs.statSync(path.join(so.mail.folder, code, 'html.ejs'));
            templates.text = fs.statSync(path.join(so.mail.folder, code, 'text.ejs'));
          } catch(err){
            code = 'one-off-event-application-approved-' + DEFAULT_LANG;
          }

          var eventDate = moment(_.first(event.dates)).format('MMMM Do YYYY, HH:mm');
          var content = {
            userName: user.name,
            eventName: event.name,
            eventDate: eventDate,
            year: moment(new Date()).format('YYYY')
          };
          send(code, content);
        }

        function send(code, content) {
          async.each(recipients, function (recipient, cb) {
            var payload = {
              to: recipient,
              code: code,
              content: content
            };
            seneca.act({role:'cd-dojos', cmd:'send_email', payload:payload}, cb);
          }, cb);
        }
      }
    }

  }
}

module.exports = updateApplication;
<|endoftext|>


<commit_before>var ImageSequence = function (target, options) {

  target.imagesequence = this;

  this.target = target;
  this.src = options.src;
  this.width = options.width;
  this.height = options.height;
  this.image = new Image();
  this.step = 1;
  this.loop = false;
  this.running = false;
  if (options.loop) {
    this.loop = true;
  }
  this.autoplay = false;
  if (options.autoplay) {
    this.autoplay = true;
  }
  if (options.rewind) {
    this.step = -1;
  }
  this.shouldPlay = this.autoplay;

  var _this = this;
  var animation-ended = new Event('animation-ended');

  this.init = function () {
    if(_this.sequence) {
      _this.sequencer();
    } else {
      _this.image.src = _this.src;
      _this.target.html(_this.image);
    }
    _this.currentFrame = 0;
    _this.target.css('overflow','hidden');
  };

  this.run = function () {
    _this.running = true;
    setTimeout(function () {
      if(_this.shouldPlay){
        _this.nextFrame();
        _this.run();
      }
    }, 40);
    // This needs to be replaced by a callback of sorts.
    setTimeout(function () { _this.running = false; }, 200);
  };

  this.play = function () {
    _this.step = 1;
    _this.shouldPlay = true;
    if(_this.running === false) {
      _this.run();
    }
  };

  this.pause = function () {
    _this.step = 0;
  };

  this.rewind = function () {
    _this.step = -1;
    _this.shouldPlay = true;
    if(_this.running === false) {
      _this.run();
    }
  };

  this.drawCurrentFrame = function () {
    var targetWidth = _this.target.width();
    var targetHeight = _this.target.height();

    var scaleX = targetWidth / _this.width;
    var scaleY = targetHeight / _this.height;
    var scale = Math.max(scaleX, scaleY);

    var frameWidth = _this.width * scale;
    var frameHeight = _this.height * scale;

    var x = (targetWidth - frameWidth) / 2;
    var y = (targetHeight - frameHeight) / 2;

    // Animation
    x -= _this.currentFrame * frameWidth;

    $(_this.image).css({
      'transform' : "translate3d(" + x + "px,"+ y +"px,0) scale(" + scale + ", " + scale + ")",
      'transform-origin' : 'left top'
    });
  };

  /*
  Not necessarily 1, 2, 3...
  Can be 8, 7, 6...
  Could also be 0, 5, 10, 15...
  */
  this.nextFrame = function () {
    _this.currentFrame = _this.currentFrame + _this.step;
    if (_this.currentFrame >= _this.countFrames()) {
      // On the right, end of sequence
      if (_this.loop) {
        _this.currentFrame -= _this.countFrames();
      } else {
        _this.currentFrame = _this.countFrames() - 1;
        _this.shouldPlay = false;
        document.dispatchEvent(animation-ended);
      }
    } else if (_this.currentFrame < 0) {
      // On the left, beginning of sequence
      if(_this.loop){
        _this.currentFrame += _this.countFrames();
      } else {
        _this.currentFrame = 0;
        _this.shouldPlay = false;
      }
    }
    _this.drawCurrentFrame();
  };

  this.countFrames = function () {
    return _this.image.naturalWidth / _this.width;
  };

  this.init();
  if(_this.autoplay){
    this.run();
  }
};

if($) {
  $.fn.imagesequence = function (options) {
    return new ImageSequence(this, options);
  };
}
<commit_msg>Change event name<commit_after>var ImageSequence = function (target, options) {

  target.imagesequence = this;

  this.target = target;
  this.src = options.src;
  this.width = options.width;
  this.height = options.height;
  this.image = new Image();
  this.step = 1;
  this.loop = false;
  this.running = false;
  if (options.loop) {
    this.loop = true;
  }
  this.autoplay = false;
  if (options.autoplay) {
    this.autoplay = true;
  }
  if (options.rewind) {
    this.step = -1;
  }
  this.shouldPlay = this.autoplay;

  var _this = this;
  var animationEnded = new Event('animation-ended');

  this.init = function () {
    if(_this.sequence) {
      _this.sequencer();
    } else {
      _this.image.src = _this.src;
      _this.target.html(_this.image);
    }
    _this.currentFrame = 0;
    _this.target.css('overflow','hidden');
  };

  this.run = function () {
    _this.running = true;
    setTimeout(function () {
      if(_this.shouldPlay){
        _this.nextFrame();
        _this.run();
      }
    }, 40);
    // This needs to be replaced by a callback of sorts.
    setTimeout(function () { _this.running = false; }, 200);
  };

  this.play = function () {
    _this.step = 1;
    _this.shouldPlay = true;
    if(_this.running === false) {
      _this.run();
    }
  };

  this.pause = function () {
    _this.step = 0;
  };

  this.rewind = function () {
    _this.step = -1;
    _this.shouldPlay = true;
    if(_this.running === false) {
      _this.run();
    }
  };

  this.drawCurrentFrame = function () {
    var targetWidth = _this.target.width();
    var targetHeight = _this.target.height();

    var scaleX = targetWidth / _this.width;
    var scaleY = targetHeight / _this.height;
    var scale = Math.max(scaleX, scaleY);

    var frameWidth = _this.width * scale;
    var frameHeight = _this.height * scale;

    var x = (targetWidth - frameWidth) / 2;
    var y = (targetHeight - frameHeight) / 2;

    // Animation
    x -= _this.currentFrame * frameWidth;

    $(_this.image).css({
      'transform' : "translate3d(" + x + "px,"+ y +"px,0) scale(" + scale + ", " + scale + ")",
      'transform-origin' : 'left top'
    });
  };

  /*
  Not necessarily 1, 2, 3...
  Can be 8, 7, 6...
  Could also be 0, 5, 10, 15...
  */
  this.nextFrame = function () {
    _this.currentFrame = _this.currentFrame + _this.step;
    if (_this.currentFrame >= _this.countFrames()) {
      // On the right, end of sequence
      if (_this.loop) {
        _this.currentFrame -= _this.countFrames();
      } else {
        _this.currentFrame = _this.countFrames() - 1;
        _this.shouldPlay = false;
        document.dispatchEvent(animation-ended);
      }
    } else if (_this.currentFrame < 0) {
      // On the left, beginning of sequence
      if(_this.loop){
        _this.currentFrame += _this.countFrames();
      } else {
        _this.currentFrame = 0;
        _this.shouldPlay = false;
      }
    }
    _this.drawCurrentFrame();
  };

  this.countFrames = function () {
    return _this.image.naturalWidth / _this.width;
  };

  this.init();
  if(_this.autoplay){
    this.run();
  }
};

if($) {
  $.fn.imagesequence = function (options) {
    return new ImageSequence(this, options);
  };
}
<|endoftext|>


<commit_before>// @flow
import moduleSpecs from '../module/schemas/1.json'

export type ModuleType = 'magdeck' | 'tempdeck'

// use a name like 'magdeck' to get displayName for app
export function getModuleDisplayName(name: ModuleType): string {
  const displayName = moduleSpecs[name].displayName

  return displayName
}
<commit_msg>fix(shared_data): Fix module path in shared data (#3556)<commit_after>// @flow
import moduleSpecs from '../module/definitions/1.json'

export type ModuleType = 'magdeck' | 'tempdeck'

// use a name like 'magdeck' to get displayName for app
export function getModuleDisplayName(name: ModuleType): string {
  const displayName = moduleSpecs[name].displayName

  return displayName
}
<|endoftext|>