<commit_before>/* jslint node: true, esnext: true */
"use strict";

const Interceptor = require('kronos-interceptor').Interceptor;
const parserFactory = require('./tokens2obj');

/**
 * This interceptor cares about the handling of the messages.
 * It will add the hops and copies the messages
 */
class Tokens2ObjectInterceptor extends Interceptor {

	static get name() {
		return "line-tokens2obj";
	}

	get type() {
		return Tokens2ObjectInterceptor.type;
	}

	receive(request, oldRequest) {
		if (request.payload) {
			const streamFilter = parserFactory(this.config.config, true);
			const stream = request.payload;
			request.payload = stream.pipe(streamFilter);
		}
		return this.connected.receive(request, oldRequest);
	}
}
exports.Interceptor = Tokens2ObjectInterceptor;
<commit_msg>fix(interceptor): Fix the name and type of the interceptor<commit_after>/* jslint node: true, esnext: true */
"use strict";

const Interceptor = require('kronos-interceptor').Interceptor;
const parserFactory = require('./tokens2obj');

/**
 * This interceptor cares about the handling of the messages.
 * It will add the hops and copies the messages
 */
class Tokens2ObjectInterceptor extends Interceptor {

	static get name() {
		return "line-tokens2obj";
	}

	get type() {
		return Tokens2ObjectInterceptor.name;
	}

	receive(request, oldRequest) {
		if (request.payload) {
			const streamFilter = parserFactory(this.config.config, true);
			const stream = request.payload;
			request.payload = stream.pipe(streamFilter);
		}
		return this.connected.receive(request, oldRequest);
	}
}
exports.Interceptor = Tokens2ObjectInterceptor;
<|endoftext|>


<commit_before>//////////////////////////////////////////////////////////////////////////////////////////////////////
//   (C)opyright Heark Gaming Co.                                                                   //
//   RPG Script v0.6                                                                                //
//   This is the updated version of Heark's RPG Script                                              //
// See Original script here: https://raw.githubusercontent.com/Heark/rpgtextbased/master/scripts.js //
//   Authored on 9/??/2014                                                                          //
//////////////////////////////////////////////////////////////////////////////////////////////////////

// info gather
var name = prompt("what is your name?")

// creating players
var player = function(name, health, attack, defense, specialattack, specialdefense){
    this.name = name;
    this.health = health;
    this.attack = attack;
    this.defense = defense;
    this.specialattack = specialattack;
    this.specialdefense = specialdefense;
}
// moves
var move = function(name, damage, accuracy){
    this.name = name;
    this.damage = damage;
    this.accuracy = accuracy;
}
var healmove = function(range, accuracy){
    this.range = range;
    this.accuracy = accuracy;
}
// creating enemies
var enemy = function(name, health, attack, defense, specialattack, specialdefense){
    this.name = name;
    this.health = health;
    this.attack = attack;
    this.defense = defense;
    this.specialattack = specialattack;
    this.specialdefense = specialdefense;
}
var evilcat = new enemy("Evil Cat", 40, 3, 4, 3, 4)
var dragon = new enemy("Dragon", 135, 5, 4, 3, 4)
var orc = new enemy("Orc", 85, 1, 1, 1, 1)
var ogre = new enemy("Ogre", 105, 3, 4, 4, 5)
// creating the skills
var punch = new move("Punch",10,100)
var kick = new move("Kick",15,85)
var wisp = new move("wisp",12,100)
var minorheal = new healmove(5,100)
var scratch = new move("Scratch",2,100)
// class creation
var classmessage = alert("Availiable classes are: Paladin, Mage, Marksman")
var userclass = prompt("Please Choose your class.")
if (userclass == "Paladin" || "paladin"){
    var user = new player(100, 12, 10, 5, 6)
    var skills = [punch, kick]
}
else if (userclass == "Mage" || "mage"){
    var user = new player(100, 6, 6, 14, 11)
    var skills = [wisp, minorheal]
}
// items
var item = function(name, description, damage, heal){
    this.name = name;
    this.description = description;
    this.damage = damage;
    this.heal = heal;
}
var minorpotion = new item("Minor Potion", "Heal by 45pts", 0, 45);
var majorpotion = new item("Major Potion", "Heal by 85pts", 0, 85);
var bomb = new item("Bomb", "Explodes and does 30 damage to one enemy.", 30, 0);

// inventory
var inventory = [];

// battle mod
var randnum = Math.floor(Math.random(10)*10);

// battle script
// Part 1

console.log('Cat appeared!')
var battle = function(enemy, player){

}
if (randnum > 5){
    catbattle = true
} else {
    console.log("No Fight!");
}
if (catbattle = true){
    console.log('Cat appeared!');
}
    Array.prototype.contains = function(elem)
{
   for (var i in this)
   {
       if (this[i] == elem) return true;
   }
   return false;
}
if (catbattle = true) do {
    var input = prompt("What do you do!?");
console.log("Commands: Inventory, " +skills.name+ ".");
if (input == "Inventory"){
    alert("Your Items are" +inventory.name+ ".");
    var iteminput = prompt("What Item would you like to use?");
    if (iteminput == "Bomb"){
        if (inventory.contains(bomb)){
            console.log("You threw a bomb at" +evilcat.name+ ".");
            evilcat.health = evilcat.health - bomb.damage;
        }
    }
}
else { console.log("You don't have this item!");
input;
    }
}
while (evilcat.health <= 0);

<commit_msg>Update scripts.js<commit_after>//////////////////////////////////////////////////////////////////////////////////////////////////////
//   (C)opyright Heark Gaming Co.                                                                   //
//   RPG Script v0.6                                                                                //
//   This is the updated version of Heark's RPG Script                                              //
// See Original script here: https://raw.githubusercontent.com/Heark/rpgtextbased/master/scripts.js //
//   Authored on 9/??/2014                                                                          //
//////////////////////////////////////////////////////////////////////////////////////////////////////

// info gather
var name = prompt("what is your name?")

// creating players
var player = function(name, health, attack, defense, specialattack, specialdefense){
    this.name = name;
    this.health = health;
    this.attack = attack;
    this.defense = defense;
    this.specialattack = specialattack;
    this.specialdefense = specialdefense;
}
// moves
var move = function(name, damage, accuracy){
    this.name = name;
    this.damage = damage;
    this.accuracy = accuracy;
}
var healmove = function(range, accuracy){
    this.range = range;
    this.accuracy = accuracy;
}
// creating enemies
var enemy = function(name, health, attack, defense, specialattack, specialdefense){
    this.name = name;
    this.health = health;
    this.attack = attack;
    this.defense = defense;
    this.specialattack = specialattack;
    this.specialdefense = specialdefense;
}
var evilcat = new enemy("Evil Cat", 40, 3, 4, 3, 4)
var dragon = new enemy("Dragon", 135, 5, 4, 3, 4)
var orc = new enemy("Orc", 85, 1, 1, 1, 1)
var ogre = new enemy("Ogre", 105, 3, 4, 4, 5)
// creating the skills
var punch = new move("Punch",10,100)
var kick = new move("Kick",15,85)
var wisp = new move("wisp",12,100)
var minorheal = new healmove(5,100)
var scratch = new move("Scratch",2,100)
// class creation
var classmessage = alert("Availiable classes are: Paladin, Mage, Marksman")
var userclass = prompt("Please Choose your class.")
if (userclass == "Paladin" || "paladin"){
    var user = new player(100, 12, 10, 5, 6)
    var skills = [punch, kick]
}
else if (userclass == "Mage" || "mage"){
    var user = new player(100, 6, 6, 14, 11)
    var skills = [wisp, minorheal]
}
// items
var item = function(name, description, damage, heal){
    this.name = name;
    this.description = description;
    this.damage = damage;
    this.heal = heal;
}
var minorpotion = new item("Minor Potion", "Heal by 45pts", 0, 45);
var majorpotion = new item("Major Potion", "Heal by 85pts", 0, 85);
var bomb = new item("Bomb", "Explodes and does 30 damage to one enemy.", 30, 0);

// inventory
var inventory = [];

// battle mod
var randnum = Math.floor(Math.random(10)*10);

// battle script
// Part 1

console.log('Cat appeared!')
var battle = function(enemy, player){

}
if (randnum > 5){
    catbattle = true
} else {
    console.log("No Fight!");
}
if (catbattle = true){
    console.log('Cat appeared!');
}
    Array.prototype.contains = function(elem)
{
   for (var i in this)
   {
       if (this[i] == elem) return true;
   }
   return false;
}
if (catbattle = true) do {
    var input = prompt("What do you do!?");
if (input == "Inventory"){
    console.log("Commands: Inventory, " +skills.name+ ".");
    alert("Your Items are" +inventory.name+ ".");
    var iteminput = prompt("What Item would you like to use?");
    if (iteminput == "Bomb"){
        if (inventory.contains(bomb)){
            console.log("You threw a bomb at" +evilcat.name+ ".");
            evilcat.health = evilcat.health - bomb.damage;
        }
    }
}
else { console.log("You don't have this item!");
input;
    }
}
while (evilcat.health <= 0);

<|endoftext|>


<commit_before>var fs = require('fs'),
    shelljs = require('shelljs/global'),
    argv = require('optimist').boolean(['no-cordova', 'sass', 'list', 'w']).argv,
    prompt = require('prompt'),
    colors = require('colors'),
    Q = require('q'),
    open = require('open'),
    IonicTemplates = require('./templates').IonicTask,
    IonicStore = require('./store').IonicStore,
    Task = require('./task').Task;
    IonicStats = require('./stats').IonicStats,
    cliLib = require('ionic-app-lib'),
    Start = cliLib.start,
    Utils = cliLib.utils;

var IonicTask = function() {};
IonicTask.prototype = new Task();

IonicTask.prototype.run = function run(ionic) {

  if (argv.list || argv.l) {
    new IonicTemplates().run(ionic);
    return;
  }

  if (argv._.length < 2) {
    return this.ionic.fail('Invalid command', 'start');
  }

  if (argv._[1] == '.') {
    console.log('Please name your Ionic project something meaningful other than \'.\''.red);
    return
  }

  var promptPromise,
      options = Utils.preprocessCliOptions(argv),
      startingApp = true;
  // Grab the app's relative directory name

  if (fs.existsSync(options.targetPath)) {
    promptPromise = Start.promptForOverwrite(options.targetPath);
  } else {
    promptPromise = Q(true);
  }

  promptPromise
  .then(function(promptToContinue) {
    if (!promptToContinue) {
      startingApp = false;
      console.log('\nIonic start cancelled by user.\n'.red.bold);
      return;
    }
    return Start.startApp(options);
  })
  .then(function() {
    if (startingApp) {
      Start.printQuickHelp(options);
      ionic.printNewsUpdates(true);
      return Start.promptLogin(options);
    }
  })
  .catch(function(error) {
    Utils.fail(error);
    // console.log('', error);
    // console.log(error.stack);
  });

  IonicStats.t();
};

exports.IonicTask = IonicTask;
<commit_msg>Taking args out from start, passing as parameter. returning promise for run<commit_after>var fs = require('fs'),
    shelljs = require('shelljs/global'),
    // argv = require('optimist').boolean(['no-cordova', 'sass', 'list', 'w']).argv,
    prompt = require('prompt'),
    colors = require('colors'),
    Q = require('q'),
    open = require('open'),
    IonicTemplates = require('./templates').IonicTask,
    IonicStore = require('./store').IonicStore,
    Task = require('./task').Task;
    IonicStats = require('./stats').IonicStats,
    cliLib = require('ionic-app-lib'),
    Start = cliLib.start,
    Utils = cliLib.utils;

var IonicTask = function() {};
IonicTask.prototype = new Task();

IonicTask.prototype.run = function run(ionic, argv) {

  if (argv.list || argv.l) {
    new IonicTemplates().run(ionic);
    return;
  }

  if (argv._.length < 2) {
    return ionic.fail('Invalid command', 'start');
  }

  if (argv._[1] == '.') {
    console.log('Please name your Ionic project something meaningful other than \'.\''.red);
    return
  }

  var promptPromise,
      options = Utils.preprocessCliOptions(argv),
      startingApp = true;
  // Grab the app's relative directory name

  IonicStats.t();

  if (fs.existsSync(options.targetPath)) {
    promptPromise = Start.promptForOverwrite(options.targetPath);
  } else {
    promptPromise = Q(true);
  }

  console.log(options);

  return promptPromise
  .then(function(promptToContinue) {
    if (!promptToContinue) {
      startingApp = false;
      console.log('\nIonic start cancelled by user.\n'.red.bold);
      return;
    }
    return Start.startApp(options);
  })
  .then(function() {
    if (startingApp) {
      Start.printQuickHelp(options);
      ionic.printNewsUpdates(true);
      return Start.promptLogin(options);
    }
  })
  .catch(function(error) {
    Utils.fail(error);
  });
};

exports.IonicTask = IonicTask;
<|endoftext|>


<commit_before>#!/usr/bin/env node

var http = require('http'),
    cluster = require('cluster'),
    numCPU = Math.floor(require('os').cpus().length / 2),
    env = process.env.NODE_ENV || 'development',
    i = 0;

// Make sure we always have at least 2 workers.
if (numCPU < 2) { numCPU = 2; }

// We only need 2 workers in development mode.
if (env === 'development') { numCPU = 2; }

if (cluster.isMaster){
    for (i; i<numCPU; i++){
        cluster.fork();
    }

    cluster.on('fork', function(worker){
        console.info('* forked worker %s', worker.process.pid);
    });

    cluster.on('exit', function(worker, code, signal){
        console.info('# worker %s died [%s]. Spawning new!', worker.process.pid, code);
        cluster.fork();
    });
} else {
    // -- database
    var mongoose = require('mongoose'),
        settings = require('./server/settings'),
        app = require('./server/app');

    app.db = mongoose.connect(settings.mongo.servers.join(','), {replSet: {rs_name: settings.mongo.replset}});

    // -- handle node exceptions
    process.on('uncaughtException', function(err){
        console.error(new Date().toString(), 'uncaughtException', err.message);
        console.error(err.stack);
        process.exit(1);
    });

    // -- start server
    http.createServer(app).listen(app.conf.port, function(){
        console.log("Express server listening on port %d in %s mode", app.conf.port, app.settings.env);
    });
}
<commit_msg>Use one process<commit_after>#!/usr/bin/env node

var http = require('http'),
    cluster = require('cluster'),
    numCPU = 1; //Math.floor(require('os').cpus().length / 2),
    env = process.env.NODE_ENV || 'development',
    i = 0;

// Make sure we always have at least 2 workers.
//if (numCPU < 2) { numCPU = 2; }

// We only need 2 workers in development mode.
if (env === 'development') { numCPU = 2; }

if (cluster.isMaster){
    for (i; i<numCPU; i++){
        cluster.fork();
    }

    cluster.on('fork', function(worker){
        console.info('* forked worker %s', worker.process.pid);
    });

    cluster.on('exit', function(worker, code, signal){
        console.info('# worker %s died [%s]. Spawning new!', worker.process.pid, code);
        cluster.fork();
    });
} else {
    // -- database
    var mongoose = require('mongoose'),
        settings = require('./server/settings'),
        app = require('./server/app');

    app.db = mongoose.connect(settings.mongo.servers.join(','), {replSet: {rs_name: settings.mongo.replset}});

    // -- handle node exceptions
    process.on('uncaughtException', function(err){
        console.error(new Date().toString(), 'uncaughtException', err.message);
        console.error(err.stack);
        process.exit(1);
    });

    // -- start server
    http.createServer(app).listen(app.conf.port, function(){
        console.log("Express server listening on port %d in %s mode", app.conf.port, app.settings.env);
    });
}
<|endoftext|>


<commit_before>if (typeof window.require === 'function') require('./style.sass')

var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']

var longMonths = [0, 2, 4, 6, 7, 9, 11]

function adjustedDateObj(dateObj, delta) {
	var month = dateObj.month, year = dateObj.year
	month += delta

	var over = month > 11
	var under = month < 0

	return {
		month: over ? 0 : under ? 11 : month,
		year: over ? year + 1 : under ? year - 1 : year
	}
}

function lastDateInMonth(dateObj, delta) {
	var obj = adjustedDateObj(dateObj, delta)
	if (longMonths.indexOf(obj.month) > -1) return 31
	if (obj.month === 1) {
		if (!(obj.year % 400)) return 29
		if (!(obj.year % 100)) return 28
		return (obj.year % 4) ? 28 : 29
	}

	return 30
}

function daysFromLastMonth(dateObj){
	var month = dateObj.month, year = dateObj.year
	var day = (new Date(year, month, 1)).getDay()
	var array = []
	if (day > 0) {
		var len = lastDateInMonth(dateObj, -1)
		for (var i=len-day+1; i<=len; i++) { array.push(i) }
	}
	return array
}

function daysFromThisMonth(dateObj) {
	var max = lastDateInMonth(dateObj, 0)
	var array = []
	for (var i=1; i<=max; i++) {
		array.push(i)
	}
	return array
}

function daysFromNextMonth(dateObj) {
	var month = dateObj.month, year = dateObj.year
	var lastDate = lastDateInMonth(dateObj, 0)
	var day = (new Date(year, month, lastDate)).getDay()
	var array = []
	if (day < 6) {
		for (var i=1; i<=6-day; i++) { array.push(i) }
	}
	return array
}

function setMonth(state, delta) {
	state.dateObj = adjustedDateObj(state.dateObj, delta)
}

function displayDate(date) {
	return days[date.getDay()].substring(0, 3) + ' ' + months[date.getMonth()] + ' ' + date.getDate() + ' ' + date.getFullYear()
}

function classForDateBox(vnode, date) {
	// TODO: if the chosen date is visible but in 'other' month, it should still get the 'chosen' class
	var dateObj = vnode.state.dateObj
	if (dateObj.year !== vnode.state.date.getFullYear() ||
		dateObj.month !== vnode.state.date.getMonth()) return ''

	return (vnode.state.date.getDate() === date) ? 'chosen' : ''
}

function defaultDate(){
	var now = new Date()
	now.setHours(0, 0, 0, 0)
	return now
}

function chooseDate(vnode, e) {
	var box = e.target
	var date = parseInt(box.textContent)

	if (box.classList.contains('not-this-month')) {

		if (date > 6) { // 6 === max days to display from prev or next month
			setMonth(vnode.state, -1)
		}
		else if (date <= 6) {
			setMonth(vnode.state, 1)
		}
	}
	vnode.state.date.setYear(vnode.state.dateObj.year)
	vnode.state.date.setMonth(vnode.state.dateObj.month)
	vnode.state.date.setDate(date)

	vnode.state.active = false

	if (vnode.attrs.commit) vnode.attrs.commit(vnode.state.date)
}

var DatePicker = {
	active: false,
	oninit: function (vnode) {
		vnode.state.date = vnode.attrs.date || defaultDate()
		vnode.state.dateObj = {
			month: vnode.state.date.getMonth(),
			year: vnode.state.date.getFullYear()
		}
	},
	view: function (vnode) {
		var dateObj = vnode.state.dateObj
		return m('.container'
			, m('.mithril-date-picker'

				// chosen/default date display
				, m('button.current-date'
					, {
						onclick: function () {
							vnode.state.active = !vnode.state.active
							vnode.state.dateObj = {
								month: vnode.state.date.getMonth(),
								year: vnode.state.date.getFullYear()
							}
						}
					}
					, displayDate(vnode.state.date)
				)
				, vnode.state.active

					// calendar/picker
					? m('.calendar.incoming'
						, {
							oncreate: function (vnode) {
								requestAnimationFrame(function () { vnode.dom.classList.remove('incoming') })
							},
							onbeforeremove: function (vnode) {
								vnode.dom.classList.add('incoming')
								return new Promise(function (done) {
									setTimeout(done, 200)
								})
							}
						}

						// header
						, m('.month-header'
							, m('button.prev'
								, { onclick: setMonth.bind(null, vnode.state, -1) }
							)
							, m('button.month-year', months[dateObj.month] + ' ' + dateObj.year)
							, m('button.next'
								, { onclick: setMonth.bind(null, vnode.state, 1) }
							)
						)

						// weekday column labels
						, m('.weekdays'
							, days.map(function (day) {
								return m('.day.dummy', day.substring(0, 1))
							})
						)

						// clickable day blocks
						, m('.weekdays'
							, { onclick: chooseDate.bind(null, vnode) }
							, daysFromLastMonth(dateObj).map(function (date) {
								return m('button.day.not-this-month', date)
							})
							, daysFromThisMonth(dateObj).map(function (date) {
								return m('button.day'
									, { class: classForDateBox(vnode, date) }
									, m('.number', date)
								)
							})
							, daysFromNextMonth(dateObj).map(function (date) {
								return m('button.day.not-this-month', date)
							})
						)
					)
					: null
			)
		)
	}
}

if (typeof window.module === 'object') module.exports = DatePicker
else window.DatePicker = DatePicker<commit_msg>mild refactor: moved to global State added YearView broke into sub-components fixed backing-into-February bug<commit_after>;(function (window) {
	if (typeof window.require === 'function') require('./style.sass')

	var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
	var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
	var longMonths = [0, 2, 4, 6, 7, 9, 11]

	var State = {
		date: null,
		viewObj: {},
		active: false,
		yearView: false,
		chooseDate: function (vnode, e) {
			var box = e.target
			var date = parseInt(box.textContent)

			if (box.classList.contains('not-this-month')) {
				State.stepMonth(otherMonthIsPrev(date) ? -1 : 1)
			}

			State.date.setFullYear(State.viewObj.year, State.viewObj.month, date)

			if (vnode.attrs.commit) vnode.attrs.commit(State.date)

			State.active = false
		},
		jumpToMonth: function (month) {
			State.viewObj.month = month
			State.yearView = false
		},
		stepMonth: function(delta) {
			State.viewObj = adjustedViewObj(State.viewObj, delta)
		},
		stepYear: function (delta) {
			State.viewObj.year += delta
		}
	}

	var fadeComponent = function(){
		return {
			oncreate: function (vnode) {
				requestAnimationFrame(function () { vnode.dom.classList.remove('incoming') })
			},
			onbeforeremove: function (vnode) {
				vnode.dom.classList.add('incoming')
				return new Promise(function (done) {
					setTimeout(done, 2000)
				})
			}
		}
	}

	function adjustedViewObj(viewObj, delta) {
		var month = viewObj.month, year = viewObj.year
		month += delta

		var over = month > 11
		var under = month < 0

		return {
			month: over ? 0 : under ? 11 : month,
			year: over ? year + 1 : under ? year - 1 : year
		}
	}

	function lastDateInMonth(viewObj, delta) {
		var obj = adjustedViewObj(viewObj, delta)
		if (longMonths.indexOf(obj.month) > -1) return 31
		if (obj.month === 1) {
			if (!(obj.year % 400)) return 29
			if (!(obj.year % 100)) return 28
			return (obj.year % 4) ? 28 : 29
		}

		return 30
	}

	function daysFromLastMonth(viewObj){
		var month = viewObj.month, year = viewObj.year
		var day = (new Date(year, month, 1)).getDay()
		var array = []
		if (day > 0) {
			var len = lastDateInMonth(viewObj, -1)
			for (var i=len-day+1; i<=len; i++) { array.push(i) }
		}
		return array
	}

	function daysFromThisMonth(viewObj) {
		var max = lastDateInMonth(viewObj, 0)
		var array = []
		for (var i=1; i<=max; i++) {
			array.push(i)
		}
		return array
	}

	function daysFromNextMonth(viewObj) {
		var month = viewObj.month, year = viewObj.year
		var lastDate = lastDateInMonth(viewObj, 0)
		var day = (new Date(year, month, lastDate)).getDay()
		var array = []
		if (day < 6) {
			for (var i=1; i<=6-day; i++) { array.push(i) }
		}
		return array
	}

	function displayDate(date) {
		return days[date.getDay()].substring(0, 3) + ' ' + months[date.getMonth()] + ' ' + date.getDate() + ' ' + date.getFullYear()
	}

	function classForDateBox(date) {
		// TODO: if the chosen date is visible but in 'other' month, it should still get the 'chosen' class
		var viewObj = State.viewObj
		if (viewObj.year !== State.date.getFullYear() ||
			viewObj.month !== State.date.getMonth()) return ''

		return (State.date.getDate() === date) ? 'chosen' : ''
	}

	function classForMonthBox(month) {
		return (State.date.getMonth() === month && State.date.getFullYear() === State.viewObj.year) ? 'chosen' : ''
	}

	function defaultDate(){
		var now = new Date()
		now.setHours(0, 0, 0, 0)
		return now
	}

	function otherMonthIsPrev(n) {
		return n > 6 // 6 === max days to display from prev or next month
	}

	var DatePicker = {
		active: false,
		oninit: function (vnode) {
			State.date = vnode.attrs.date || defaultDate()
			State.viewObj = {
				month: State.date.getMonth(),
				year: State.date.getFullYear()
			}
		},
		view: function (vnode) {
			var viewObj = State.viewObj
			return m('.container'
				, m('.mithril-date-picker'

					// chosen/default date display
					, m('button.current-date'
						, {
							onclick: function () {
								State.active = !State.active
								State.yearView = false
								State.viewObj = {
									month: State.date.getMonth(),
									year: State.date.getFullYear()
								}
							}
						}
						, displayDate(State.date)
					)
					, State.active
						? State.yearView
							? m(YearView, { viewObj: viewObj })
							: m(MonthView, { viewObj: viewObj })
						: null
				)
			)
		}
	}

	var Header = {
		view: function (vnode) {
			return m('header'
				, m('button.prev'
					, { onclick: vnode.attrs.stepFn.bind(null, -1) }
				)
				, m('button.month-year'
					, { onclick: function(){ State.yearView = !State.yearView } }
					, vnode.attrs.text
				)
				, m('button.next'
					, { onclick: vnode.attrs.stepFn.bind(null, 1) }
				)
			)
		}
	}

	var YearView = fadeComponent()
	YearView.view = function (vnode) {
		return m('.calendar.incoming'
			, m(Header, { stepFn: State.stepYear, text: vnode.attrs.viewObj.year })
			, m('.months'
				, months.map(function (month, idx) {
					return m('button.month'
						, {
							class: classForMonthBox(idx),
							onclick: State.jumpToMonth.bind(null, idx)
						}
						, m('.number', month.substring(0, 3))
					)
				})
			)
		)
	}

	var MonthView = fadeComponent()
	MonthView.view = function (vnode) {
		var viewObj = vnode.attrs.viewObj
		return m('.calendar.incoming'
			, m(Header, { stepFn: State.stepMonth, text: months[viewObj.month] + ' ' + viewObj.year })
			, m('.weekdays'
				, days.map(function (day) {
					return m('.day.dummy', day.substring(0, 1))
				})
			)
			, m('.weekdays'
				, { onclick: State.chooseDate.bind(null, vnode) }
				, daysFromLastMonth(viewObj).map(function (date) {
					return m('button.day.not-this-month', date)
				})
				, daysFromThisMonth(viewObj).map(function (date) {
					return m('button.day'
						, { class: classForDateBox(vnode, date) }
						, m('.number', date)
					)
				})
				, daysFromNextMonth(viewObj).map(function (date) {
					return m('button.day.not-this-month', date)
				})
			)
		)
	}

	if (typeof window.module === 'object') module.exports = DatePicker
	else window.DatePicker = DatePicker
})(window)

<|endoftext|>


<commit_before>
var eval2 = function (data) {
    if (typeof data === 'string') data = data.replace(/(\r\n|\r|\n)$/, '');
    if (!data) return null;
    if (/^(true|TRUE|True)$/.test(data)) data = true;
    else if (/^(False|false|FALSE)$/.test(data)) data = false;
    else if (/^(NULL|null|Null)$/.test(data)) data = null;
    else if (
        /^[\+\-]?(\d+|\d*\.\d+|\d+\.)(e[\-\+]?\d+)?$/i.test(data) ||
        /^(0b[01]+|0x[\da-f]+|0o[0-7]+)$/i.test(data)
    ) data = parseNumber(data);
    else data = strings.decode(data);
    return data;
};
var scan = function (text) {
    var rows = text.split(/\r\n|\r|\n/);
    var rowtype = 0;
    var data = '';
    var span = 0;
    var prop;
    var parents = [];
    var jsonlikes = [];
    var push = function (value) {
        if (data && prop === undefined && jsonlikes[jsonlikes.length - 1] === '{') {
            prop = strings.decode(data);
            data = '';
        }
        if (!value) value = eval2(data);
        data = '';
        while (parents.length) {
            if (parents[parents.length - 1]) break;
            parents.pop();
        }
        if (prop !== undefined) {
            if (!parents.length) parents.push({});
            var parent = parents[parents.length - 1];
            if (parent instanceof Array) {
                parent.push({});
                parent = parent[parent.length - 1];
                parents[span] = parent;
            }
            parent[prop] = value;
        } else {
            var parent = parents[parents.length - 1];
            if (parent instanceof Array) parent.push(value);
            else parents[span] = value;
        }
        prop = undefined;
    };
    var unshift = function (size, row) {
        if (!row) return;
        row = new Array(size + 1).join(" ") + row;
        rows.unshift(row);
    };
    while (rows.length) {
        var row = rows.shift();
        if (/^['"]$/.test(rowtype)) {
            if (jsonlikes.length) {
                var reg = new RegExp(/\\[\s\S]|/.source + rowtype, 'g');
                var index = -1;
                do {
                    var res = reg.exec(row);
                    if (res && res[0] === rowtype) {
                        index = res.index;
                        break;
                    }
                } while (res);
            } else {
                index = row.indexOf(rowtype);
            }
            if (index < 0) {
                data += row + "\r\n";
                continue;
            }
            data += row.slice(0, index + +!!jsonlikes.length);
            row = row.slice(index + 1)
            unshift(spacesize, row);
            rowtype = 0;
            continue;
        }
        var spacesize = /^\s*/.exec(row)[0].length;
        if (spacesize === row.length) {
            rowtype = 0;
            continue;
        }
        if (!data && !prop && !jsonlikes.length) {
            span = spacesize;
            parents = parents.slice(0, span + 1);
        }

        row = row.trim();
        if (rowtype === '|') {
            rowtype = spacesize;
            continue;
        }
        if (rowtype && spacesize >= rowtype) {
            data += row + "\r\n";
            continue;
        }
        rowtype = 0;
        if (/^#/.test(row)) {
            // comment
            continue;
        }
        if (/^["']/.test(row)) {
            rowtype = row[0];
            if (jsonlikes.length) {
                data += row[0];
            }
            row = row.slice(1);
            unshift(0, row);
            continue;
        }
        if (/^\-\-+$/.test(row)) {
            continue;
        }

        if (/^\-(\s|$)/.test(row)) {
            if (data) push();
            if (!parents[spacesize]) {
                var obj = [];
                push(obj);
                parents[spacesize] = obj;
            } else {
                parents = parents.slice(0, spacesize + 1);
            }
            span = spacesize;
            parents = parents.slice(0, span + 1);
            rowtype = row[0];
            row = row.slice(1);
            unshift(spacesize + 1, row);
            continue;
        }
        if (!data && /^[\[\{]/.test(row)) {
            var obj = row[0] === "{" ? {} : [];
            push(obj);
            parents.push(obj);
            jsonlikes.push(row[0]);
            row = row.slice(1);
            unshift(spacesize + 1, row);
            continue;
        }

        if (jsonlikes.length) {

            var match = /^\:|[\]\},]|\:[\s\[\{]/.exec(row);
            if (match) {
                if (match.index > 0) {
                    data += row.slice(0, match.index);
                    row = row.slice(match.index);
                }
                var pre = row[0];
                row = row.slice(1);
                if (pre === ":") {
                    prop = strings.decode(data);
                    data = '';
                }
                else {
                    switch (pre) {
                        case ",":
                            push();
                            break;
                        case "]":
                            if (jsonlikes[jsonlikes.length - 1] !== "[") console.warn('数据存在错误！', jsonlikes, pre);
                            if (data) push();
                            jsonlikes.pop();
                            parents.pop();
                            break;
                        case "}":
                            if (jsonlikes[jsonlikes.length - 1] !== "{") console.warn("数据存在错误！", jsonlikes, pre);
                            if (prop !== undefined || data) push();
                            jsonlikes.pop();
                            parents.pop();
                            break;
                    }
                }
                if (row) unshift(0, row);
                if (!jsonlikes.length) continue;
                if (pre === ']' || pre === '}') {
                    row = rows.shift();
                    row = row.replace(/^\s*,/, '');
                    if (row) rows.unshift(row);
                }
            }
            continue;
        }
        else {
            var match = /^([\s\S]*?)\:(|\s+[\s\S]*)$/.exec(row);
            if (match) {
                if (data) push();
                if (prop) {
                    var obj = {};
                    push(obj);
                    parents[spacesize] = obj;
                }
                var [_, prop, value] = match;
                value = value.trim();
                if (value) {
                    unshift(spacesize + 1, value);
                }
                prop = strings.decode(prop);
                span = spacesize;
                parents = parents.slice(0, span + 1);
                continue;
            }
        }

        if (row === "|") {
            rowtype = "|"
            continue;
        }
        if (row) data += row + "\r\n";
    }
    if (data) push();
    while (parents[0] === undefined && parents.length > 0) parents.shift();
    return parents[0];
}
module.exports = scan;<commit_msg>解决一些问题<commit_after>
var eval2 = function (data) {
    if (typeof data === 'string') data = data.replace(/(\r\n|\r|\n)$/, '');
    if (!data) return null;
    if (/^(true|TRUE|True)$/.test(data)) data = true;
    else if (/^(False|false|FALSE)$/.test(data)) data = false;
    else if (/^(NULL|null|Null)$/.test(data)) data = null;
    else if (
        /^[\+\-]?(\d+|\d*\.\d+|\d+\.)(e[\-\+]?\d+)?$/i.test(data) ||
        /^(0b[01]+|0x[\da-f]+|0o[0-7]+)$/i.test(data)
    ) data = parseNumber(data);
    else data = strings.decode(data);
    return data;
};
var scan = function (text) {
    var rows = text.split(/\r\n|\r|\n/);
    var rowtype = 0;
    var data = '';
    var span = 0;
    var prop;
    var parents = [];
    var jsonlikes = [];
    var push = function (value) {
        if (data && prop === undefined && jsonlikes[jsonlikes.length - 1] === '{') {
            prop = strings.decode(data);
            data = '';
        }
        if (!value) value = eval2(data);
        data = '';
        while (parents.length) {
            if (parents[parents.length - 1]) break;
            parents.pop();
        }
        if (prop !== undefined) {
            if (!parents.length) parents.push({});
            var parent = parents[parents.length - 1];
            if (parent instanceof Array) {
                parent.push({});
                parent = parent[parent.length - 1];
                parents[span] = parent;
            }
            parent[prop] = value;
        } else {
            var parent = parents[parents.length - 1];
            if (parent instanceof Array) parent.push(value);
            else parents[span] = value;
        }
        prop = undefined;
    };
    var unshift = function (size, row) {
        if (!row) return;
        row = new Array(size + 1).join(" ") + row;
        rows.unshift(row);
    };
    while (rows.length) {
        var row = rows.shift();
        if (/^['"]$/.test(rowtype)) {
            if (jsonlikes.length) {
                var reg = new RegExp(/\\[\s\S]|/.source + rowtype, 'g');
                var index = -1;
                do {
                    var res = reg.exec(row);
                    if (res && res[0] === rowtype) {
                        index = res.index;
                        break;
                    }
                } while (res);
            } else {
                index = row.indexOf(rowtype);
            }
            if (index < 0) {
                data += row + "\r\n";
                continue;
            }
            data += row.slice(0, index + +!!jsonlikes.length);
            row = row.slice(index + 1)
            unshift(spacesize, row);
            rowtype = 0;
            continue;
        }
        var spacesize = /^\s*/.exec(row)[0].length;
        if (spacesize === row.length) {
            rowtype = 0;
            continue;
        }
        if (!data && prop === undefined && !jsonlikes.length) {
            span = spacesize;
            parents = parents.slice(0, span + 1);
        }

        row = row.trim();
        if (rowtype === '|') {
            rowtype = spacesize;
            continue;
        }
        if (rowtype && spacesize >= rowtype) {
            data += row + "\r\n";
            continue;
        }
        rowtype = 0;
        if (/^#/.test(row)) {
            // comment
            continue;
        }
        if (/^["']/.test(row)) {
            rowtype = row[0];
            if (jsonlikes.length) {
                data += row[0];
            }
            row = row.slice(1);
            unshift(0, row);
            continue;
        }
        if (/^\-\-+$/.test(row)) {
            continue;
        }

        if (/^\-(\s|$)/.test(row)) {
            if (data) push();
            if (!parents[spacesize]) {
                var obj = [];
                push(obj);
                parents[spacesize] = obj;
            } else {
                parents = parents.slice(0, spacesize + 1);
            }
            span = spacesize;
            parents = parents.slice(0, span + 1);
            rowtype = row[0];
            row = row.slice(1);
            unshift(spacesize + 1, row);
            continue;
        }
        if (!data && /^[\[\{]/.test(row)) {
            var obj = row[0] === "{" ? {} : [];
            push(obj);
            parents.push(obj);
            jsonlikes.push(row[0]);
            row = row.slice(1);
            unshift(spacesize + 1, row);
            continue;
        }

        if (jsonlikes.length) {

            var match = /^\:|[\]\},]|\:[\s\[\{]/.exec(row);
            if (match) {
                if (match.index > 0) {
                    data += row.slice(0, match.index);
                    row = row.slice(match.index);
                }
                var pre = row[0];
                row = row.slice(1);
                if (pre === ":") {
                    prop = strings.decode(data);
                    data = '';
                }
                else {
                    switch (pre) {
                        case ",":
                            push();
                            break;
                        case "]":
                            if (jsonlikes[jsonlikes.length - 1] !== "[") console.warn('数据存在错误！', jsonlikes, pre);
                            if (data) push();
                            jsonlikes.pop();
                            parents.pop();
                            break;
                        case "}":
                            if (jsonlikes[jsonlikes.length - 1] !== "{") console.warn("数据存在错误！", jsonlikes, pre);
                            if (prop !== undefined || data) push();
                            jsonlikes.pop();
                            parents.pop();
                            break;
                    }
                }
                if (row) unshift(0, row);
                if (!jsonlikes.length) continue;
                if (pre === ']' || pre === '}') {
                    row = rows.shift();
                    row = row.replace(/^\s*,/, '');
                    if (row) rows.unshift(row);
                }
            }
            continue;
        }
        else {
            var match = /^([\s\S]*?)\:(|\s+[\s\S]*)$/.exec(row);
            if (match) {
                if (data || span > spacesize) push();
                if (prop) {
                    var obj = {};
                    push(obj);
                    parents[spacesize] = obj;
                }
                var [_, prop, value] = match;
                value = value.trim();
                if (value) {
                    unshift(spacesize + 1, value);
                }
                prop = strings.decode(prop);
                span = spacesize;
                parents = parents.slice(0, span + 1);
                continue;
            }
        }

        if (row === "|") {
            rowtype = "|"
            continue;
        }
        if (row) data += row + "\r\n";
    }
    if (data) push();
    while (parents[0] === undefined && parents.length > 0) parents.shift();
    return parents[0];
}
module.exports = scan;<|endoftext|>


<commit_before>function Cleanup(list) {
    function cleanup() {
        var target = this;
        for (var cx = list.length - 1; cx >= 0; cx--) {
            var element = list[cx];
            if (element === target) {
                list.splice(cx, 1);
            }
        }
    }
    return cleanup;
}<commit_msg>支持传入参数<commit_after>function Cleanup(list) {
    function cleanup(target) {
        if (isNode(this) && !isNode(target)) {
            target = this;
        }
        for (var cx = list.length - 1; cx >= 0; cx--) {
            var element = list[cx];
            if (element === target) {
                list.splice(cx, 1);
            }
        }
    }
    return cleanup;
}<|endoftext|>


<commit_before>const { i18n } = require('./next-i18next.config')

module.exports = {
  reactStrictMode: true,
  i18n
}
<commit_msg>Expose public env vars to the client-side environment<commit_after>const { i18n } = require('./next-i18next.config')

module.exports = {
  reactStrictMode: true,
  i18n,
  publicRuntimeConfig: {
    NEXT_PUBLIC_API_PROTOCOL: process.env.NEXT_PUBLIC_API_PROTOCOL,
    NEXT_PUBLIC_API_DOMAIN: process.env.NEXT_PUBLIC_API_DOMAIN,
    NEXT_PUBLIC_API_PATH: process.env.NEXT_PUBLIC_API_PATH,
    NEXT_PUBLIC_API_VERSION: process.env.NEXT_PUBLIC_API_VERSION
  }
}
<|endoftext|>


<commit_before>
angular.module("ngJustGage", [])
    .directive('justGage', ['$timeout', function ($timeout) {
      return {
        restrict: 'E',
        scope: {
          id: '@',
          class: '@',
          min: '=',
          max: '=',
          title: '@',
          value: '='
        },
        template: '

',
        link: function (scope) {
          $timeout(function () {
            var g = new JustGage({
              id: scope.id + '-justgage',
              min: scope.min,
              max: scope.max,
              title: scope.title,
              value: scope.value
            })

            scope.$watch('value', function (updatedValue) {
              if (updatedValue) {
                g.refresh(updatedValue)
              }
            }, true);
          });
        }
      };
    }]);
<commit_msg>Enable Attribute for directive<commit_after>
angular.module("ngJustGage", [])
    .directive('justGage', ['$timeout', function ($timeout) {
      return {
        restrict: 'EA',
        scope: {
          id: '@',
          class: '@',
          min: '=',
          max: '=',
          title: '@',
          value: '='
        },
        template: '

',
        link: function (scope) {
          $timeout(function () {
            var g = new JustGage({
              id: scope.id + '-justgage',
              min: scope.min,
              max: scope.max,
              title: scope.title,
              value: scope.value
            })

            scope.$watch('value', function (updatedValue) {
              if (updatedValue) {
                g.refresh(updatedValue)
              }
            }, true);
          });
        }
      };
    }]);
<|endoftext|>


<commit_before>var RocketIO = function(){
  new EventEmitter().apply(this);
  this.type = null; // "comet", "websocket"
  this.session = null;
  this.io = null;
  var self = this;
  var ws_close_timer = null;

  this.connect = function(){
    self.io = function(){
      if(self.type === "comet") return;
      if(typeof WebSocketIO === "undefined") return;
      var io = new WebSocketIO();
      io.session = self.session;
      return io.connect();
    }() || function(){
      if(typeof CometIO === "undefined") return;
      var io = new CometIO();
      io.session = self.session;
      return io.connect();
    }();
    if(self.io.url.match(/^ws:\/\/.+/)) self.type = "websocket";
    else if(self.io.url.match(/cometio/)) self.type = "comet";
    else self.type = "unknown";
    self.io.on("*", function(event_name, args){
      self.emit(event_name, args);
    });
    self.io.on("connect", function(session_id){
      self.session = session_id;
    });
    ws_close_timer = setTimeout(function(){
      self.close();
      self.type = "comet";
      self.connect();
    }, 3000);
    return self;
  };

  self.on("connect", function(){
    clearTimeout(ws_close_timer);
  });

  this.close = function(){
    self.io.close();
  };

  this.push = function(type, data){
    self.io.push(type, data);
  };
};
<commit_msg>RocketIO.emit("error") if websocket and comet not available  #2<commit_after>var RocketIO = function(){
  new EventEmitter().apply(this);
  this.type = null; // "comet", "websocket"
  this.session = null;
  this.io = null;
  var self = this;
  var ws_close_timer = null;

  this.connect = function(){
    self.io = function(){
      if(self.type === "comet") return;
      if(typeof WebSocketIO === "undefined") return;
      var io = new WebSocketIO();
      io.session = self.session;
      return io.connect();
    }() || function(){
      if(typeof CometIO === "undefined") return;
      var io = new CometIO();
      io.session = self.session;
      return io.connect();
    }();
    if(typeof self.io === "undefined"){
      setTimeout(function(){
        self.emit("error", "WebSocketIO and CometIO are not available")
      }, 100);
      return self;
    };
    if(self.io.url.match(/^ws:\/\/.+/)) self.type = "websocket";
    else if(self.io.url.match(/cometio/)) self.type = "comet";
    else self.type = "unknown";
    self.io.on("*", function(event_name, args){
      self.emit(event_name, args);
    });
    self.io.on("connect", function(session_id){
      self.session = session_id;
    });
    ws_close_timer = setTimeout(function(){
      self.close();
      self.type = "comet";
      self.connect();
    }, 3000);
    return self;
  };

  self.on("connect", function(){
    clearTimeout(ws_close_timer);
  });

  this.close = function(){
    self.io.close();
  };

  this.push = function(type, data){
    self.io.push(type, data);
  };
};
<|endoftext|>


<commit_before>'use babel';

import {SelectListView} from 'atom-space-pen-views';
import {EventEmitter} from 'events';
import when from "when";
import {runCommand, noProjectSelectedNotification} from './library';
import {Particle, Client} from 'particle-api-js';

const {LibraryAddCommandSite, LibraryAddCommand} = require('./cli');

import {profileManager} from './index';

/**
 * Wraps a promise in a notification that is presented while the promise runs, and
 * dismissed when the promise is done.
 * @param promise
 * @param message
 */
function progress(promise, message) {

}

/**
 * The view for adding and choosing a library.
 */
class LibrarySelectView extends SelectListView {

	initialize(listPromiseFactory, confirmCallback) {
		super.initialize();
		this.listPopulated = 'listPopulated';
		this.events = new EventEmitter();
		this.listPromiseFactory = listPromiseFactory;
		this.confirmCallback = confirmCallback;
		this.addClass('particle-library-add');
		this.filterEditorView.getModel().setPlaceholderText('Type in the library to add to your project...');
		this.setLoading();
		this.panel = atom.workspace.addModalPanel({item: this});
		this.panel.show();
		this.focusFilterEditor();
	}

	viewForItem(item) {
		return `<li>${item}</li>`;
	}

	setItems(items=[]) {
		this.items = items;
		super.populateList();
		this.setLoading();
		this.events.emit(this.listPopulated);
	}

	getItems() {
		return this.items;
	}

	getFilterQuery() {
		return [];
	}

	populateList() {
		const filter = super.getFilterQuery();
		const promise = this.listPromiseFactory(filter);
		when(promise).then(libraries => {
			if (libraries) {
				const names = libraries.map(lib => lib.name);
				this.setItems(names);
			}
			else {
				this.setItems();
			}
		});
	}

	schedulePopulateList() {
		console.log("schedule populate", super.getFilterQuery());
		this.setLoading('...');
		super.schedulePopulateList();
	}

	confirmed(item) {
		console.log(`${item} was selected`);
		this.close();
		const c = this.confirmCallback;
		if (c) {
			c(item, this);
		}
	}

	cancelled() {
		console.log('This view was cancelled');
		this.close();
	}

	close() {
		this.panel.destroy();
	}
}

class DevLibraryAddSite extends LibraryAddCommandSite {

	constructor(dir, name, version) {
		super();
		this.dir = dir;
		this.setLibraryIdent(name, version);
	}

	setLibraryIdent(name, version) {
		this.name = name;
		this.version = version;
	}

	projectDir() {
		return this.dir;
	}

	libraryIdent() {
		return { name: this.name, version: this.version };
	}

	notifyListLibrariesStart(promise) {
		return promise;
	}

	notifyListLibrariesComplete(promise, libraries, error) {
		this.libraries = libraries;
	}

	fetchingLibrary(promise, name) {
		return promise;
	}
}

function selectAddLibrary(atom, directory) {
	const pm = profileManager();
	const apiClient = pm.apiClient;
	const command = new LibraryAddCommand({apiClient});
	const site = new DevLibraryAddSite(directory);
	const listPromiseFactory = (filter) => {
		return command.listLibraries(site, filter).then((libraries) => {
			return libraries;
		})
	};

	const view = new LibrarySelectView(listPromiseFactory, (name, view) => {
		site.setLibraryIdent(name);
		const promise = site.run(command);
		runCommand(promise);
	});
}

export function libraryAddCommand(atom, directory) {
	if (!directory) {
		atom.notifications.addNotification(noProjectSelectedNotification());
	} else {
		selectAddLibrary(atom, directory);
	}
}
<commit_msg>removes console debugging output, linting<commit_after>'use babel';

import {SelectListView} from 'atom-space-pen-views';
import {EventEmitter} from 'events';
import when from "when";
import {runCommand, noProjectSelectedNotification} from './library';
import {Particle, Client} from 'particle-api-js';

const {LibraryAddCommandSite, LibraryAddCommand} = require('./cli');

import {profileManager} from './index';

/**
 * Wraps a promise in a notification that is presented while the promise runs, and
 * dismissed when the promise is done.
 * @param promise
 * @param message
 */
function progress(promise, message) {

}

/**
 * The view for adding and choosing a library.
 */
class LibrarySelectView extends SelectListView {

	initialize(listPromiseFactory, confirmCallback) {
		super.initialize();
		this.listPopulated = 'listPopulated';
		this.events = new EventEmitter();
		this.listPromiseFactory = listPromiseFactory;
		this.confirmCallback = confirmCallback;
		this.addClass('particle-library-add');
		this.filterEditorView.getModel().setPlaceholderText('Type in the library to add to your project...');
		this.setLoading();
		this.panel = atom.workspace.addModalPanel({item: this});
		this.panel.show();
		this.focusFilterEditor();
	}

	viewForItem(item) {
		return `<li>${item}</li>`;
	}

	setItems(items=[]) {
		this.items = items;
		super.populateList();
		this.setLoading();
		this.events.emit(this.listPopulated);
	}

	getItems() {
		return this.items;
	}

	getFilterQuery() {
		return [];
	}

	populateList() {
		const filter = super.getFilterQuery();
		const promise = this.listPromiseFactory(filter);
		when(promise).then(libraries => {
			if (libraries) {
				const names = libraries.map(lib => lib.name);
				this.setItems(names);
			}
			else {
				this.setItems();
			}
		});
	}

	schedulePopulateList() {
		this.setLoading('...');
		super.schedulePopulateList();
	}

	confirmed(item) {
		this.close();
		const c = this.confirmCallback;
		if (c) {
			c(item, this);
		}
	}

	cancelled() {
		this.close();
	}

	close() {
		this.panel.destroy();
	}
}

class DevLibraryAddSite extends LibraryAddCommandSite {

	constructor(dir, name, version) {
		super();
		this.dir = dir;
		this.setLibraryIdent(name, version);
	}

	setLibraryIdent(name, version) {
		this.name = name;
		this.version = version;
	}

	projectDir() {
		return this.dir;
	}

	libraryIdent() {
		return { name: this.name, version: this.version };
	}

	notifyListLibrariesStart(promise) {
		return promise;
	}

	notifyListLibrariesComplete(promise, libraries, error) {
		this.libraries = libraries;
	}

	fetchingLibrary(promise, name) {
		return promise;
	}
}

function selectAddLibrary(atom, directory) {
	const pm = profileManager();
	const apiClient = pm.apiClient;
	const command = new LibraryAddCommand({apiClient});
	const site = new DevLibraryAddSite(directory);
	const listPromiseFactory = (filter) => {
		return command.listLibraries(site, filter).then((libraries) => {
			return libraries;
		});
	};

	/*const view =*/new LibrarySelectView(listPromiseFactory, (name, view) => {
		site.setLibraryIdent(name);
		const promise = site.run(command);
		runCommand(promise);
	});
}

export function libraryAddCommand(atom, directory) {
	if (!directory) {
		atom.notifications.addNotification(noProjectSelectedNotification());
	} else {
		selectAddLibrary(atom, directory);
	}
}
<|endoftext|>


<commit_before>/*
 * Copyright 2012 Brett Slatkin
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var GROUP_TYPE_COLUMN = 0;
var GROUP_VALUE_COLUMN = 1;
var DAY_COLUMN = 2;

function getSelectedGroupType() {
  return $('input:radio[name=\'chart1\']:checked').val();
}

function getSelectedGroupValues() {
  return $.makeArray(
    $('.group-value-checkbox:checked').map(function(index, el) {
      return $(el).val();
    }));
}

function getIsNormalized() {
  return $('input:checkbox[name=\'normalize\']:checked').val();
}

function getIsWeekly() {
  return $('input:checkbox[name=\'weekly\']:checked').val();
}

function createGroupTypeRadios(groupTypes) {
  var vizDiv = $('#viz_group_type1');
  vizDiv.empty();

  // Guess that whichever group type has only one value and that value is
  // empty will be the topline data.
  var checkedType = null;
  $.each(groupTypes, function(key, value) {
    if (value.length == 1 && value[0] === '') {
      checkedType = key;
    }
  });

  var i = 0;
  $.each(groupTypes, function(key, value) {
    var radioId = 'group_type_radio1_' + (i++);
    var useRadio = $('<input type="radio">')
        .addClass('group-type-radio')
        .attr('id', radioId)
        .attr('name', 'chart1')
        .attr('value', key);

    // Select the default group type.
    if (!!checkedType && checkedType === key) {
      useRadio.attr('checked', 'checked');
    }

    var container = $('
');
    container.append(useRadio);
    container.append($('').attr('for', radioId).text(key));

    vizDiv.append(container);
  });

  // Register event handlers
  $('.group-type-radio').click(function() {
    createGroupValueCheckboxes(groupTypes);
    $(document).trigger('cohorts.viz');
  });
}

function createGroupValueCheckboxes(groupTypes) {
  var type = getSelectedGroupType();
  var values = groupTypes[type];
  if (!values) {
    $.error('Bad group type: ' + type);
  }

  var valuesDiv = $('#viz_group_value1');
  valuesDiv.empty();

  // Special case for group types that only have a single, empty value.
  if (values.length == 1 && values[0] === '') {
    return;
  }

  valuesDiv.append(
      $('
')
          .text('Included group values'));

  var i = 0;
  $.each(values, function(key, value) {
    var checkboxId = 'group_value_checkbox1_' + (i++);
    var container = $('
');
    container.append(
        $('<input type="checkbox" class="group-value-checkbox" checked>')
        .attr('value', value)
        .attr('id', checkboxId));
    container.append(
        $('').attr('for', checkboxId).text(value));
    valuesDiv.append(container);
  });

  // Register event handlers
  $('.group-value-checkbox').click(function() {
    $(document).trigger('cohorts.viz');
  });
}

function createLegend(rowsWithHeader) {
  var columnNames = rowsWithHeader[0].slice(3);
  var container = $('#viz_legend');
  container.empty();

  var color = d3.scale.category20();
  $.each(columnNames, function(index, value) {
    var item = $('
');
    $('
')
        .attr('style', 'background-color: ' + color(index))
        .appendTo(item);
    $('
')
        .text(value)
        .appendTo(item);
    // Reverse order to match graph stacking.
    container.prepend(item);
  });
}

function getCohort(cohortDay, cohortsInOrder, weekly) {
  if (weekly) {
    var index = cohortsInOrder.indexOf(cohortDay);
    var indexRounded = 6 * Math.floor(index / 7);
    result = cohortsInOrder[indexRounded];
    return result;
  } else {
    return cohortDay;
  }
};

function filterData(rows, groupType, groupValues, weekly) {
  // Helper function for only pulling the row data that matches.
  function shouldSkip(index, value) {
    // Skip the header row.
    if (index == 0) {
      return true;
    }
    // Skip rows of the wrong group type.
    if (groupType !== value[GROUP_TYPE_COLUMN]) {
      return true;
    }
    // Skip rows with unmatched group values. Match everything if no values
    // were supplied.
    if (groupValues.length > 0 &&
        groupValues.indexOf(value[GROUP_VALUE_COLUMN]) == -1) {
      return true;
    }
  }

  // Extract the cohort days so we can do arbitrary time regroupings.
  function compareCohorts(a, b) {
    return d3.ascending(format.parse(a), format.parse(b));
  }

  var cohortsInOrder = [];
  $.each(rows, function(index, value) {
    if (shouldSkip(index, value)) {
      return;
    }
    cohortsInOrder.push(value[DAY_COLUMN]);
  });
  var format = d3.time.format("%m/%d/%y");
  cohortsInOrder.sort(compareCohorts);

  // Maps cohort key to the combined data row for the key. The data rows in
  // the values of this map have all cohort columns removed.
  var cohorts = {};

  // Filter matching group type and group values.
  $.each(rows, function(index, value) {
    if (shouldSkip(index, value)) {
      return;
    }

    var cohort = getCohort(value[DAY_COLUMN], cohortsInOrder, weekly);
    var cohortRows = cohorts[cohort];
    if (!cohortRows) {
      // First row for a cohort. Truncate the group type, group name, and date
      // columns, leaving just numeric data.
      var firstRow = [];
      for (var i = 3, n = value.length; i < n; ++i) {
        firstRow.push(parseInt(value[i]));
      }
      cohorts[cohort] = firstRow;
    } else {
      for (var i = 0, n = cohortRows.length; i < n; ++i) {
        cohortRows[i] += parseInt(value[i + 3]);
      }
    }
  });

  // Save some metadata about the cohorts.
  var rowData = [];
  $.each(cohortsInOrder, function(index, value) {
    var valueList = cohorts[value];
    var total = d3.sum(valueList || []);
    rowData.push({
      cohort: value,
      x: index,
      total: total,
      show: !!valueList
    });
  });

  // Now regroup the data as sets of points grouped by column (for D3).
  var columns = {};
  var headers = rows[0].slice(3);
  $.each(cohortsInOrder, function(index, key) {
    var columnValues = cohorts[key];
    $.each(headers, function(columnIndex, header) {
      var data = columns[header];
      if (!data) {
        data = []
        columns[header] = data;
      }

      if (!columnValues) {
        data.push({
          cohort: key,
          x: cohortsInOrder.indexOf(key),
          y: 0,
          show: false
        });
      } else {
        data.push({
          cohort: key,
          x: cohortsInOrder.indexOf(key),
          y: columnValues[columnIndex],
          show: true
        });
      }
    });
  });

  var columnData = [];
  $.each(columns, function(key, value) {
    columnData.push({name: key, values: value});
  });

  return [rowData, columnData];
}

function extractGroupTypes(csvData) {
  // Maps cohort group types to lists of cohort group values
  var cohortGroupTypes = {};

  // Skip the header row
  for (var i = 1; i < csvData.length; ++i) {
    var row = csvData[i];
    var groupType = row[GROUP_TYPE_COLUMN];
    var groupValue = row[GROUP_VALUE_COLUMN];
    var valueList = cohortGroupTypes[groupType];
    if (!valueList) {
      valueList = [];
      cohortGroupTypes[groupType] = valueList;
    }
    if (valueList.indexOf(groupValue) == -1) {
      valueList.push(groupValue);
    }
  }

  return cohortGroupTypes;
}

function clearViz() {
  d3.select('#viz_graph1')
      .select('svg.stacked').select('g').selectAll('g.layer').remove();
}

function updateViz(rows) {
  var groupType = getSelectedGroupType();
  var groupValues = getSelectedGroupValues();
  var normalized = getIsNormalized();
  var weekly = getIsWeekly();

  view = filterData(rows, groupType, groupValues, weekly);
  var viewCohorts = view[0];
  var viewBarGroups = view[1];

  var realRows = viewCohorts.filter(function(value, index) {
    return value.show;
  });

  console.log('Filtered to: type="' + groupType +
              '", values="' + (groupValues.join('|')) +
              '"; ' + realRows.length + ' rows found');

  // Scale graph to whole window area, with minimum
  var height = 500;
  var width = $(window).width() - 100;
  if (width < 500) {
    width = 500;
  }
  $('#viz_container').width(width);

  // Put margins around the graphs so the axes render without clipping
  var marginX = 50;
  var marginY = 20;
  height -= 2 * marginY;
  width -= 2 * marginX;

  var scaleX = d3.scale.linear()
      .domain([0, viewCohorts.length])
      .range([0, width]);
  var barWidth = width / realRows.length;
  var maxY = d3.max(viewCohorts, function(d) { return d.total; });
  if (normalized) {
    maxY = 1;
  }

  var scaleY = d3.scale.linear()
      .domain([0, maxY])
      .range([marginY, height - (2 * marginY)]);
  var scaleColor = d3.scale.category20();

  var getColor = function(d, i) {
    return scaleColor(i);
  };
  var getX = function(d) {
    return scaleX(d.x);
  };
  var getY = function(d) {
    return scaleY(maxY - d.y0 - d.y);
  };
  var getHeight = function(d) {
    return scaleY(d.y);
  };
  var getWidth = function(d, i) {
    if (d.show) {
      return barWidth;
    } else {
      return 0;
    }
  };

  var getValues = function(d) { return d.values; };

  var chart = d3.select('#viz_graph1')
      .select('svg.stacked')
        .attr('width', width + 2 * marginX)
        .attr('height', height + 2 * marginY)
      .select('g')
        .attr("transform", "translate(" + marginX + "," + marginY + ")");

  var stack = d3.layout.stack();
  if (normalized) {
    stack = stack.offset('expand');
  }
  stack = stack.values(getValues)(viewBarGroups);

  var layers = chart.selectAll('g.layer').data(stack);
  layers.enter().append('svg:g')
      .attr('class', 'layer')
      .style('fill', getColor)
      .style('stroke', d3.rgb('#333'));

  layers.exit().remove();

  var bars = layers.selectAll('rect.bar').data(getValues);
  bars.enter().append('svg:rect')
      .attr('class', 'bar')
      .attr('x', scaleX(scaleX.domain()[1]))
      .attr('y', getY)
      .attr('width', getWidth)
      .attr('height', getHeight)
    .transition()
      .duration(500)
      .attr('width', getWidth)
      .attr('x', getX)
      .attr('y', getY);

  bars.transition()
      .duration(500)
      .attr('x', getX)
      .attr('y', getY)
      .attr('width', getWidth)
      .attr('height', getHeight);
  bars.exit().remove();

  // Cohort date axis
  // TODO: Always include the last one!
  function filterTicks(value, index) {
    // With very few ticks, show them all
    if (viewCohorts.length <= 5) {
      return true;
    }
    if (index % 7 == 0) {
      return true;
    }
    return false;
  };

  var domain = viewCohorts.map(function(d) { return d.cohort; });
  var range = viewCohorts.map(function(d, i) {
    return scaleX(i);
  });
  domain = domain.filter(filterTicks);
  range = range.filter(filterTicks);

  var xAxisScale = d3.scale.ordinal()
    .domain(domain)
    .range(range);

  var xAxis = d3.svg.axis()
      .scale(xAxisScale)
      .tickSize(5, 2, 0);

  chart.selectAll('g.bottom.axis').remove();

  chart.append("g")
      .attr("class", "bottom axis")
      .attr("transform", "translate(0," + (height-marginY) + ")")
      .call(xAxis.orient("bottom"));

  // Vertical axis
  var yAxisScale = d3.time.scale()
    .domain([0, maxY])
    .range([height-marginY, marginY]);

  var yAxis = d3.svg.axis().scale(yAxisScale);

  if (normalized) {
    yAxis = yAxis.tickFormat(d3.format("%"))
        .tickSize(5, 0, 0)
        .tickValues([1]);
  } else {
    yAxis = yAxis.tickFormat(d3.format(",.0f"))
        .tickSize(5, 0, 0)
        .tickValues([maxY]);
  }

  chart.selectAll('g.left.axis').remove();

  chart.append("g")
      .attr("class", "left axis")
      .call(yAxis.orient("left"));
}

function handleClickVisualize() {
  // Parse the CSV data
  var rowsWithHeader = $.csv.toArrays($('#data').val());
  var groupTypes = extractGroupTypes(rowsWithHeader);

  // Setup UI
  createGroupTypeRadios(groupTypes);
  createGroupValueCheckboxes(groupTypes);
  createLegend(rowsWithHeader);

  // Register event handlers
  $(document).unbind('cohorts.viz');
  $(document).bind('cohorts.viz', function() {
    updateViz(rowsWithHeader);
  });

  // Clear any existing chart
  clearViz();

  // Build chart
  $(document).trigger('cohorts.viz');
}

function init() {
  $('#visualize_my_data').click(handleClickVisualize);

  var trigger = function() {
    $(document).trigger('cohorts.viz');
  };

  $('#normalize-check').click(trigger);
  $('#weekly-check').click(trigger)

  $(window).resize(trigger);

  // Start off with the dummy data that's in the textarea on page load.
  handleClickVisualize();
}

$(document).ready(init);
<commit_msg>Weekly transition not working correctly for sub-filtered data<commit_after>/*
 * Copyright 2012 Brett Slatkin
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var GROUP_TYPE_COLUMN = 0;
var GROUP_VALUE_COLUMN = 1;
var DAY_COLUMN = 2;

function getSelectedGroupType() {
  return $('input:radio[name=\'chart1\']:checked').val();
}

function getSelectedGroupValues() {
  return $.makeArray(
    $('.group-value-checkbox:checked').map(function(index, el) {
      return $(el).val();
    }));
}

function getIsNormalized() {
  return $('input:checkbox[name=\'normalize\']:checked').val();
}

function getIsWeekly() {
  return $('input:checkbox[name=\'weekly\']:checked').val();
}

function createGroupTypeRadios(groupTypes) {
  var vizDiv = $('#viz_group_type1');
  vizDiv.empty();

  // Guess that whichever group type has only one value and that value is
  // empty will be the topline data.
  var checkedType = null;
  $.each(groupTypes, function(key, value) {
    if (value.length == 1 && value[0] === '') {
      checkedType = key;
    }
  });

  var i = 0;
  $.each(groupTypes, function(key, value) {
    var radioId = 'group_type_radio1_' + (i++);
    var useRadio = $('<input type="radio">')
        .addClass('group-type-radio')
        .attr('id', radioId)
        .attr('name', 'chart1')
        .attr('value', key);

    // Select the default group type.
    if (!!checkedType && checkedType === key) {
      useRadio.attr('checked', 'checked');
    }

    var container = $('
');
    container.append(useRadio);
    container.append($('').attr('for', radioId).text(key));

    vizDiv.append(container);
  });

  // Register event handlers
  $('.group-type-radio').click(function() {
    createGroupValueCheckboxes(groupTypes);
    $(document).trigger('cohorts.viz');
  });
}

function createGroupValueCheckboxes(groupTypes) {
  var type = getSelectedGroupType();
  var values = groupTypes[type];
  if (!values) {
    $.error('Bad group type: ' + type);
  }

  var valuesDiv = $('#viz_group_value1');
  valuesDiv.empty();

  // Special case for group types that only have a single, empty value.
  if (values.length == 1 && values[0] === '') {
    return;
  }

  valuesDiv.append(
      $('
')
          .text('Included group values'));

  var i = 0;
  $.each(values, function(key, value) {
    var checkboxId = 'group_value_checkbox1_' + (i++);
    var container = $('
');
    container.append(
        $('<input type="checkbox" class="group-value-checkbox" checked>')
        .attr('value', value)
        .attr('id', checkboxId));
    container.append(
        $('').attr('for', checkboxId).text(value));
    valuesDiv.append(container);
  });

  // Register event handlers
  $('.group-value-checkbox').click(function() {
    $(document).trigger('cohorts.viz');
  });
}

function createLegend(rowsWithHeader) {
  var columnNames = rowsWithHeader[0].slice(3);
  var container = $('#viz_legend');
  container.empty();

  var color = d3.scale.category20();
  $.each(columnNames, function(index, value) {
    var item = $('
');
    $('
')
        .attr('style', 'background-color: ' + color(index))
        .appendTo(item);
    $('
')
        .text(value)
        .appendTo(item);
    // Reverse order to match graph stacking.
    container.prepend(item);
  });
}

function getCohort(cohortDay, cohortsInOrder, weekly) {
  if (weekly) {
    var index = cohortsInOrder.indexOf(cohortDay);
    var indexRounded = 6 * Math.floor(index / 7);
    result = cohortsInOrder[indexRounded];
    return result;
  } else {
    return cohortDay;
  }
};

function filterData(rows, groupType, groupValues, weekly) {
  // Helper function for only pulling the row data that matches.
  function shouldSkip(index, value) {
    // Skip the header row.
    if (index == 0) {
      return true;
    }
    // Skip rows of the wrong group type.
    if (groupType !== value[GROUP_TYPE_COLUMN]) {
      return true;
    }
    // Skip rows with unmatched group values. Match everything if no values
    // were supplied.
    if (groupValues.length > 0 &&
        groupValues.indexOf(value[GROUP_VALUE_COLUMN]) == -1) {
      return true;
    }
  }

  // Extract the cohort days so we can do arbitrary time regroupings.
  function compareCohorts(a, b) {
    return d3.ascending(format.parse(a), format.parse(b));
  }

  var cohortsInOrder = [];
  $.each(rows, function(index, value) {
    if (shouldSkip(index, value)) {
      return;
    }
    cohortsInOrder.push(value[DAY_COLUMN]);
  });
  var format = d3.time.format("%m/%d/%y");
  cohortsInOrder.sort(compareCohorts);

  // Maps cohort key to the combined data row for the key. The data rows in
  // the values of this map have all cohort columns removed.
  var cohorts = {};

  // Filter matching group type and group values.
  $.each(rows, function(index, value) {
    if (shouldSkip(index, value)) {
      return;
    }

    var cohort = getCohort(value[DAY_COLUMN], cohortsInOrder, weekly);
    var cohortRows = cohorts[cohort];
    if (!cohortRows) {
      // First row for a cohort. Truncate the group type, group name, and date
      // columns, leaving just numeric data.
      var firstRow = [];
      for (var i = 3, n = value.length; i < n; ++i) {
        firstRow.push(parseInt(value[i]));
      }
      cohorts[cohort] = firstRow;
    } else {
      for (var i = 0, n = cohortRows.length; i < n; ++i) {
        cohortRows[i] += parseInt(value[i + 3]);
      }
    }
  });

  // Save some metadata about the cohorts.
  var rowData = [];
  $.each(cohortsInOrder, function(index, value) {
    var valueList = cohorts[value];
    var total = d3.sum(valueList || []);
    rowData.push({
      cohort: value,
      x: index,
      total: total,
      show: !!valueList
    });
  });

  // Now regroup the data as sets of points grouped by column (for D3).
  var columns = {};
  var headers = rows[0].slice(3);
  $.each(cohortsInOrder, function(index, key) {
    var columnValues = cohorts[key];
    $.each(headers, function(columnIndex, header) {
      var data = columns[header];
      if (!data) {
        data = []
        columns[header] = data;
      }

      if (!columnValues) {
        data.push({
          cohort: key,
          x: cohortsInOrder.indexOf(key),
          y: 0,
          show: false
        });
      } else {
        data.push({
          cohort: key,
          x: cohortsInOrder.indexOf(key),
          y: columnValues[columnIndex],
          show: true
        });
      }
    });
  });

  var columnData = [];
  $.each(columns, function(key, value) {
    columnData.push({name: key, values: value});
  });

  return [rowData, columnData];
}

function extractGroupTypes(csvData) {
  // Maps cohort group types to lists of cohort group values
  var cohortGroupTypes = {};

  // Skip the header row
  for (var i = 1; i < csvData.length; ++i) {
    var row = csvData[i];
    var groupType = row[GROUP_TYPE_COLUMN];
    var groupValue = row[GROUP_VALUE_COLUMN];
    var valueList = cohortGroupTypes[groupType];
    if (!valueList) {
      valueList = [];
      cohortGroupTypes[groupType] = valueList;
    }
    if (valueList.indexOf(groupValue) == -1) {
      valueList.push(groupValue);
    }
  }

  return cohortGroupTypes;
}

function clearViz() {
  d3.select('#viz_graph1')
      .select('svg.stacked').select('g').selectAll('g.layer').remove();
}

function updateViz(rows) {
  var groupType = getSelectedGroupType();
  var groupValues = getSelectedGroupValues();
  var normalized = getIsNormalized();
  var weekly = getIsWeekly();

  view = filterData(rows, groupType, groupValues, weekly);
  var viewCohorts = view[0];
  var viewBarGroups = view[1];

  var realRows = viewCohorts.filter(function(value, index) {
    return value.show;
  });

  console.log('Filtered to: type="' + groupType +
              '", values="' + (groupValues.join('|')) +
              '"; ' + realRows.length + ' rows found');

  // Scale graph to whole window area, with minimum
  var height = 500;
  var width = $(window).width() - 100;
  if (width < 500) {
    width = 500;
  }
  $('#viz_container').width(width);

  // Put margins around the graphs so the axes render without clipping
  var marginX = 50;
  var marginY = 20;
  height -= 2 * marginY;
  width -= 2 * marginX;

  var scaleX = d3.scale.linear()
      .domain([0, viewCohorts.length])
      .range([0, width]);
  var barWidth = width / realRows.length;
  var maxY = d3.max(viewCohorts, function(d) { return d.total; });
  if (normalized) {
    maxY = 1;
  }

  var scaleY = d3.scale.linear()
      .domain([0, maxY])
      .range([marginY, height - (2 * marginY)]);
  var scaleColor = d3.scale.category20();

  var getColor = function(d, i) {
    return scaleColor(i);
  };
  var getX = function(d) {
    return scaleX(d.x);
  };
  var getY = function(d) {
    if (d.show) {
      return scaleY(maxY - d.y0 - d.y);
    } else {
      return height - marginY;  // TODO: Clean this up
    }
  };
  var getHeight = function(d) {
    if (d.show) {
      return scaleY(d.y);
    } else {
      return 0;
    }
  };
  var getWidth = function(d, i) {
    if (d.show) {
      return barWidth;
    } else {
      return 0;
    }
  };

  var getValues = function(d) { return d.values; };

  var chart = d3.select('#viz_graph1')
      .select('svg.stacked')
        .attr('width', width + 2 * marginX)
        .attr('height', height + 2 * marginY)
      .select('g')
        .attr("transform", "translate(" + marginX + "," + marginY + ")");

  var stack = d3.layout.stack();
  if (normalized) {
    stack = stack.offset('expand');
  }
  stack = stack.values(getValues)(viewBarGroups);

  var layers = chart.selectAll('g.layer').data(stack);
  layers.enter().append('svg:g')
      .attr('class', 'layer')
      .style('fill', getColor)
      .style('stroke', d3.rgb('#333'));

  layers.exit().remove();

  var bars = layers.selectAll('rect.bar').data(getValues);
  bars.enter().append('svg:rect')
      .attr('class', 'bar')
      .attr('x', getX)
      .attr('y', height - marginY) // TODO: Clean this up
      .attr('width', getWidth)
      .attr('height', 0)
    .transition()
      .duration(500)
      .attr('width', getWidth)
      .attr('height', getHeight)
      .attr('x', getX)
      .attr('y', getY);

  bars.transition()
      .duration(500)
      .attr('x', getX)
      .attr('y', getY)
      .attr('height', getHeight)
    .transition()
      .delay(500)
      .attr('width', getWidth);

  bars.exit().remove();

  // Cohort date axis
  // TODO: Always include the last one!
  function filterTicks(value, index) {
    // With very few ticks, show them all
    if (viewCohorts.length <= 5) {
      return true;
    }
    if (index % 7 == 0) {
      return true;
    }
    return false;
  };

  var domain = viewCohorts.map(function(d) { return d.cohort; });
  var range = viewCohorts.map(function(d, i) {
    return scaleX(i);
  });
  domain = domain.filter(filterTicks);
  range = range.filter(filterTicks);

  var xAxisScale = d3.scale.ordinal()
    .domain(domain)
    .range(range);

  var xAxis = d3.svg.axis()
      .scale(xAxisScale)
      .tickSize(5, 2, 0);

  chart.selectAll('g.bottom.axis').remove();

  chart.append("g")
      .attr("class", "bottom axis")
      .attr("transform", "translate(0," + (height-marginY) + ")")
      .call(xAxis.orient("bottom"));

  // Vertical axis
  var yAxisScale = d3.time.scale()
    .domain([0, maxY])
    .range([height-marginY, marginY]);

  var yAxis = d3.svg.axis().scale(yAxisScale);

  if (normalized) {
    yAxis = yAxis.tickFormat(d3.format("%"))
        .tickSize(5, 0, 0)
        .tickValues([1]);
  } else {
    yAxis = yAxis.tickFormat(d3.format(",.0f"))
        .tickSize(5, 0, 0)
        .tickValues([maxY]);
  }

  chart.selectAll('g.left.axis').remove();

  chart.append("g")
      .attr("class", "left axis")
      .call(yAxis.orient("left"));
}

function handleClickVisualize() {
  // Parse the CSV data
  var rowsWithHeader = $.csv.toArrays($('#data').val());
  var groupTypes = extractGroupTypes(rowsWithHeader);

  // Setup UI
  createGroupTypeRadios(groupTypes);
  createGroupValueCheckboxes(groupTypes);
  createLegend(rowsWithHeader);

  // Register event handlers
  $(document).unbind('cohorts.viz');
  $(document).bind('cohorts.viz', function() {
    updateViz(rowsWithHeader);
  });

  // Clear any existing chart
  clearViz();

  // Build chart
  $(document).trigger('cohorts.viz');
}

function init() {
  $('#visualize_my_data').click(handleClickVisualize);

  var trigger = function() {
    $(document).trigger('cohorts.viz');
  };

  $('#normalize-check').click(trigger);
  $('#weekly-check').click(trigger)

  $(window).resize(trigger);

  // Start off with the dummy data that's in the textarea on page load.
  handleClickVisualize();
}

$(document).ready(init);
<|endoftext|>


<commit_before>// Define imports
var SipListener         = Java.type('javax.sip.SipListener')
var Request             = Java.type('javax.sip.message.Request')
var Response            = Java.type('javax.sip.message.Response')
var RouteHeader         = Java.type('javax.sip.header.RouteHeader')
var ToHeader            = Java.type('javax.sip.header.ToHeader')
var ContactHeader       = Java.type('javax.sip.header.ContactHeader')
var ExpiresHeader       = Java.type('javax.sip.header.ExpiresHeader')
var ViaHeader           = Java.type('javax.sip.header.ViaHeader')
var CSeqHeader          = Java.type('javax.sip.header.CSeqHeader')
var AuthorizationHeader = Java.type('javax.sip.header.AuthorizationHeader')
var LogManager          = Java.type('org.apache.logging.log4j.LogManager')

load("mod/core/context.js")
load("mod/utils/auth_helper.js")

function Processor(sipProvider, sipStack, headerFactory, messageFactory, addressFactory, contactHeader, locationService,
    registrarService, accountManagerService, config) {

    let LOG = LogManager.getLogger()
    let ctxtList = new java.util.ArrayList()
    let localhost = InetAddress.getLocalHost().getHostAddress()
    let authHelper =  new AuthHelper(headerFactory)

    function register(request, transaction) {
        let toHeader = request.getHeader(ToHeader.NAME)
        let toURI = toHeader.getAddress().getURI()
        let toDomain = toHeader.getAddress().getURI().getHost()
        let contactHeader = request.getHeader(ContactHeader.NAME)
        let contactURI = contactHeader.getAddress().getURI()
        let expH = request.getHeader(ExpiresHeader.NAME)
        let authHeader = request.getHeader(AuthorizationHeader.NAME)

        if (authHeader == null) {
            let unauthorized = messageFactory.createResponse(Response.UNAUTHORIZED, request)
            unauthorized.addHeader(authHelper.generateChallenge())
            transaction.sendResponse(unauthorized)
            LOG.trace(unauthorized)
        } else {
            if (registrarService.register(authHeader, toDomain, contactURI)) {
                let ok = messageFactory.createResponse(Response.OK, request)
                ok.addHeader(contactHeader)
                ok.addHeader(expH)
                transaction.sendResponse(ok)
                LOG.trace("\n" + ok)
            } else {
                let unauthorized = messageFactory.createResponse(Response.UNAUTHORIZED, request)
                unauthorized.addHeader(authHelper.generateChallenge(headerFactory))
                transaction.sendResponse(unauthorized)
                LOG.trace(unauthorized)
            }
        }
    }

    function cancel(request, st) {
        let iterator = ctxtList.iterator()

        while (iterator.hasNext()) {
            let ctxt = iterator.next()
            if (ctxt.serverTrans.getBranchId()
                .equals(st.getBranchId())) {

                let originRequest = ctxt.requestIn
                let originResponse = messageFactory.createResponse(Response.REQUEST_TERMINATED, originRequest)
                let cancelResponse = messageFactory.createResponse(Response.OK, request)
                let cancelRequest = ctxt.clientTrans.createCancel()
                let ct = sipProvider.getNewClientTransaction(cancelRequest)

                ctxt.serverTrans.sendResponse(originResponse)
                st.sendResponse(cancelResponse)
                ct.sendRequest()

                LOG.trace(originResponse)
                LOG.trace(cancelResponse)
                LOG.trace(cancelRequest)
            }
        }
    }

    function unavailable(request, transaction) {
        LOG.info("XXXXXXXXXXXX Unable to find contact: " + request.getHeader(ContactHeader.NAME))
        transaction.sendResponse(messageFactory.createResponse(Response.NOT_FOUND, request))
    }

    this.listener = new SipListener() {
        processRequest: function (e)    {
            let requestIn = e.getRequest()
            let routeHeader = requestIn.getHeader(RouteHeader.NAME)
            let proxyHost

            print(requestIn)

            // Edge proxy
            if (routeHeader != null) {
                let sipURI = routeHeader.getAddress().getURI()
                proxyHost = sipURI.getHost()
            } else {
                proxyHost = localhost;
            }

            let method = requestIn.getMethod()
            let st = e.getServerTransaction()

            if (st == null) {
                st = sipProvider.getNewServerTransaction(requestIn)
            }

            if (method.equals(Request.REGISTER)) {
                register(requestIn, st)
            } else if(method.equals(Request.CANCEL)) {
                cancel(requestIn, st)
            } else if(method.equals(Request.OPTIONS)) {
                // WARNING: NOT YET IMPLEMENTED
            } else {
                let requestOut = requestIn.clone()
                let tgtURI = requestIn.getRequestURI()

                // Last proxy in route
                if (proxyHost.equals(localhost)) {
                    let viaHeader = headerFactory.createViaHeader(proxyHost, config.port, config.proto, null)
                    requestOut.removeFirst(RouteHeader.NAME)
                    requestOut.addFirst(viaHeader)
                }

                let uri = locationService.get(tgtURI)

                if (uri == null) {
                    unavailable(requestIn, st)
                    return
                }

                requestOut.setRequestURI(uri)

                // Not need transaction
                if(method.equals(Request.ACK)) {
                    sipProvider.sendRequest(requestOut)
                } else {
                    let ct = sipProvider.getNewClientTransaction(requestOut)
                    ct.sendRequest()

                    // Transaction context
                    let ctxt = new Context()
                    ctxt.clientTrans = ct
                    ctxt.serverTrans = st
                    ctxt.method = method
                    ctxt.requestIn = requestIn
                    ctxt.requestOut = requestOut
                    ctxtList.add(ctxt)
                }
                LOG.trace(requestOut)
            }
        },

        processResponse: function (e) {
            let responseIn = e.getResponse()
            let statusCode = responseIn.getStatusCode()

            print(responseIn)

            if (responseIn.getStatusCode() == Response.TRYING
                || statusCode == Response.REQUEST_TERMINATED) return

            let ct = e.getClientTransaction()

            try {
                let originalCSeq = ct.getRequest().getHeader(CSeqHeader.NAME)
                let method = originalCSeq.getMethod()

                if (method.equals(Request.CANCEL)) return
            } catch(e) {
            }

            let routeHeader = responseIn.getHeader(RouteHeader.NAME)
            let proxyHost

            // Edge proxy
            if (routeHeader != null) {
                let sipURI = routeHeader.getAddress().getURI()
                proxyHost = sipURI.getHost()
            } else {
                proxyHost = localhost;
            }

            if (responseIn.getStatusCode() == Response.PROXY_AUTHENTICATION_REQUIRED
                    || responseIn.getStatusCode() == Response.UNAUTHORIZED) {
                let authenticationHelper =
                    sipStack.getAuthenticationHelper(accountManagerService.getAccountManager(), headerFactory)
                let t = authenticationHelper.handleChallenge(responseIn, ct, sipProvider, 5)
                t.sendRequest()
                return
            }

            let responseOut = responseIn.clone()

            //if(proxyHost.equals(localhost)) {
                responseOut.removeFirst(ViaHeader.NAME)
            //}

            let i = ctxtList.iterator()

            let match = false
            while (i.hasNext()) {
                let ctxt = i.next()

                if (ctxt.clientTrans.equals(ct)) {
                    ctxt.serverTrans.sendResponse(responseOut)
                    match = true
                    break
                }
            }

            if (!match) {
                sipProvider.sendResponse(responseOut)
            }
            LOG.trace(responseOut)
        },

        processTransactionTerminated: function (e) {
            if (e.isServerTransaction()) {
                let st = e.getServerTransaction()
                let i = ctxtList.iterator()

                while (i.hasNext()) {
                    let ctxt = i.next()

                    if (ctxt.serverTrans.equals(st)) {
                        i.remove()
                        break
                    } else {
                        LOG.info("Ongoing Transaction")
                    }
                }
            }
        },

        processDialogTerminated: function (e) {
            LOG.info("#processDialogTerminated not yet implemented")
        },

        processTimeout: function (e) {
            LOG.info("#processTimeout not yet implemented")
        }
    }
}
<commit_msg>Refactored proccesor.js<commit_after>// Define imports
var SipListener         = Java.type('javax.sip.SipListener')
var Request             = Java.type('javax.sip.message.Request')
var Response            = Java.type('javax.sip.message.Response')
var RouteHeader         = Java.type('javax.sip.header.RouteHeader')
var ToHeader            = Java.type('javax.sip.header.ToHeader')
var ContactHeader       = Java.type('javax.sip.header.ContactHeader')
var ExpiresHeader       = Java.type('javax.sip.header.ExpiresHeader')
var ViaHeader           = Java.type('javax.sip.header.ViaHeader')
var CSeqHeader          = Java.type('javax.sip.header.CSeqHeader')
var AuthorizationHeader = Java.type('javax.sip.header.AuthorizationHeader')
var LogManager          = Java.type('org.apache.logging.log4j.LogManager')

load("mod/core/context.js")
load("mod/utils/auth_helper.js")

function Processor(sipProvider, sipStack, headerFactory, messageFactory, addressFactory, contactHeader, locationService,
    registrarService, accountManagerService, config) {

    let LOG = LogManager.getLogger()
    let ctxtList = new java.util.ArrayList()
    let localhost = InetAddress.getLocalHost().getHostAddress()
    let authHelper =  new AuthHelper(headerFactory)

    function register(request, transaction) {
        let toHeader = request.getHeader(ToHeader.NAME)
        let toURI = toHeader.getAddress().getURI()
        let toDomain = toHeader.getAddress().getURI().getHost()
        let contactHeader = request.getHeader(ContactHeader.NAME)
        let contactURI = contactHeader.getAddress().getURI()
        let expH = request.getHeader(ExpiresHeader.NAME)
        let authHeader = request.getHeader(AuthorizationHeader.NAME)

        if (authHeader == null) {
            let unauthorized = messageFactory.createResponse(Response.UNAUTHORIZED, request)
            unauthorized.addHeader(authHelper.generateChallenge())
            transaction.sendResponse(unauthorized)
            LOG.trace(unauthorized)
        } else {
            if (registrarService.register(authHeader, toDomain, contactURI)) {
                let ok = messageFactory.createResponse(Response.OK, request)
                ok.addHeader(contactHeader)
                ok.addHeader(expH)
                transaction.sendResponse(ok)
                LOG.trace("\n" + ok)
            } else {
                let unauthorized = messageFactory.createResponse(Response.UNAUTHORIZED, request)
                unauthorized.addHeader(authHelper.generateChallenge(headerFactory))
                transaction.sendResponse(unauthorized)
                LOG.trace(unauthorized)
            }
        }
    }

    function cancel(request, st) {
        let iterator = ctxtList.iterator()

        while (iterator.hasNext()) {
            let ctxt = iterator.next()
            if (ctxt.serverTrans.getBranchId()
                .equals(st.getBranchId())) {

                let originRequest = ctxt.requestIn
                let originResponse = messageFactory.createResponse(Response.REQUEST_TERMINATED, originRequest)
                let cancelResponse = messageFactory.createResponse(Response.OK, request)
                let cancelRequest = ctxt.clientTrans.createCancel()
                let ct = sipProvider.getNewClientTransaction(cancelRequest)

                ctxt.serverTrans.sendResponse(originResponse)
                st.sendResponse(cancelResponse)
                ct.sendRequest()

                LOG.trace(originResponse)
                LOG.trace(cancelResponse)
                LOG.trace(cancelRequest)
            }
        }
    }

    function unavailable(request, transaction) {
        LOG.debug("Unable to find contact: " + request.getHeader(ContactHeader.NAME))
        transaction.sendResponse(messageFactory.createResponse(Response.NOT_FOUND, request))
    }

    this.listener = new SipListener() {
        processRequest: function (e)    {
            let requestIn = e.getRequest()
            let routeHeader = requestIn.getHeader(RouteHeader.NAME)
            let proxyHost

            // Edge proxy
            if (routeHeader != null) {
                let sipURI = routeHeader.getAddress().getURI()
                proxyHost = sipURI.getHost()
            } else {
                proxyHost = localhost;
            }

            let method = requestIn.getMethod()
            let st = e.getServerTransaction()

            if (st == null) {
                st = sipProvider.getNewServerTransaction(requestIn)
            }

            if (method.equals(Request.REGISTER)) {
                register(requestIn, st)
            } else if(method.equals(Request.CANCEL)) {
                cancel(requestIn, st)
            } else if(method.equals(Request.OPTIONS)) {
                // WARNING: NOT YET IMPLEMENTED
            } else {
                let requestOut = requestIn.clone()
                let tgtURI = requestIn.getRequestURI()

                // Last proxy in route
                if (proxyHost.equals(localhost)) {
                    let viaHeader = headerFactory.createViaHeader(proxyHost, config.port, config.proto, null)
                    requestOut.removeFirst(RouteHeader.NAME)
                    requestOut.addFirst(viaHeader)
                }

                let uri = locationService.get(tgtURI)

                if (uri == null) {
                    unavailable(requestIn, st)
                    return
                }

                requestOut.setRequestURI(uri)

                // Not need transaction
                if(method.equals(Request.ACK)) {
                    sipProvider.sendRequest(requestOut)
                } else {
                    let ct = sipProvider.getNewClientTransaction(requestOut)
                    ct.sendRequest()

                    // Transaction context
                    let ctxt = new Context()
                    ctxt.clientTrans = ct
                    ctxt.serverTrans = st
                    ctxt.method = method
                    ctxt.requestIn = requestIn
                    ctxt.requestOut = requestOut
                    ctxtList.add(ctxt)
                }
                LOG.trace(requestOut)
            }
        },

        processResponse: function (e) {
            let rin = e.getResponse()
            let cseq = rin.getHeader(CSeqHeader.NAME)

            if (rin.getStatusCode() == Response.TRYING || rin.getStatusCode() == Response.REQUEST_TERMINATED) return
            if (cseq.getMethod().equals(Request.CANCEL)) return

            let ct = e.getClientTransaction()

            if (rin.getStatusCode() == Response.PROXY_AUTHENTICATION_REQUIRED || rin.getStatusCode() == Response.UNAUTHORIZED) {
                let authenticationHelper =
                    sipStack.getAuthenticationHelper(accountManagerService.getAccountManager(), headerFactory)
                let t = authenticationHelper.handleChallenge(rin, ct, e.getSource(), 5)
                t.sendRequest()
                return
            }

            if (cseq.getMethod().equals(Request.INVITE)) {
                if (ct != null) {
                    // In theory we should be able to obtain the ServerTransaction casting the ApplicationData.
                    // However, I'm unable to find the way to cast this object.
                    //let st = ct.getApplicationData()'

                    // Strip the topmost via header
                    let rout = rin.clone();
                    rout.removeFirst(ViaHeader.NAME);

                    let i = ctxtList.iterator()
                    while (i.hasNext()) {
                        let ctxt = i.next()

                        if (ctxt.clientTrans.equals(ct)) {
                            // The server tx goes to the terminated state.
                            ctxt.serverTrans.sendResponse(rout)
                            break
                        }
                    }
                } else {
                    // Client tx has already terminated but the UA is retransmitting
                    // just forward the response statelessly.
                    // Strip the topmost via header

                    let rout = rin.clone();
                    rout.removeFirst(ViaHeader.NAME);
                    // Send the retransmission statelessly
                    let sipProvider = e.getSource();
                    sipProvider.sendResponse(rout);
                }
            } else {
                // Can be BYE due to Record-Route
                LOG.trace("Got a non-invite response " + rin);
                let sipProvider = e.getSource();
                rin.removeFirst(ViaHeader.NAME);

                // There is no more Via headers; the response was intended for the proxy.
                if (rin.getHeader(ViaHeader.NAME) != null) sipProvider.sendResponse(rin);
            }
        },

        processTransactionTerminated: function (e) {
            if (e.isServerTransaction()) {
                let st = e.getServerTransaction()
                let i = ctxtList.iterator()

                while (i.hasNext()) {
                    let ctxt = i.next()

                    if (ctxt.serverTrans.equals(st)) {
                        i.remove()
                        break
                    } else {
                        LOG.info("Ongoing Transaction")
                    }
                }
            }
        },

        processDialogTerminated: function (e) {
            LOG.info("#processDialogTerminated not yet implemented")
        },

        processTimeout: function (e) {
            LOG.info("#processTimeout not yet implemented")
        }
    }
}
<|endoftext|>