<commit_before>'use strict';
/**
 * Created by chregi on 2/28/15.
 * v0.1 - 13.4.2015
 * - fixed: Kickoff time daylight saving independent
 * - new: put Day in schedule table
 */

 // parse a date in yyyy-mm-dd format
function parseDate(input) {
  var parts = input.match(/(\d+)/g);
  // new Date(year, month [, date [, hours[, minutes[, seconds[, ms]]]]])
  return new Date(parts[0], parts[1]-1, parts[2], parts[3], parts[4]); // months are 0-based
}

// get hours to add / subtract to date to fix timezone errors
function getHourCorrection(date) {
    return - (date.getTimezoneOffset() / 60);
}

// Get day of week from a date as String
function getDayOfWeek(date) {
    var dow = ["So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"];
    return dow[date.getDay()];
}

var getSchedule = function(team_id, season_id) {
    var selector = '.srs-schedule[data-teamid='+id+']';

	jQuery.ajax({
	    url: "http://api.swissrugbystats.ch/teams/"+team_id+"/games/season/"+season_id+".json",
	    success: function(data){

            /* build schedule table
             * TODO:
             * - set links
            */
            var tableStr = "";
            tableStr = "

Datum	Host	Guest	Kickoff / Result

";
            for (var i = 0; i < data.length; i++) {
                // parse the date
                var d = parseDate(data[i].date);
                var dStr = ("0" + d.getDate()).slice(-2) +"."+ ("0"+(d.getMonth()+1)).slice(-2) +"."+ d.getFullYear();

                // game result
                if ((data[i].host.score != null) && (data[i].guest.score != null)) {
                    var result = data[i].host.score + " : " + data[i].guest.score;
                } else {
                    var result = (d.getHours() + getHourCorrection(d)) + ":"+ ("0" + d.getMinutes()).slice(-2) + " Uhr";
                }

                tableStr += "
" + getDayOfWeek(d) +", "+ dStr + "	" + data[i].host.team.name + "	" + data[i].guest.team.name + "	" + result + "
";
            }

            tableStr += "

";
            jQuery(selector).html(tableStr);

            jQuery(selector).append("

All game data provided by Swiss Rugby Stats");
	    }
	});
}

var getSchedules = function() {

    var scheduleTags = jQuery('.srs-schedule');
    jQuery('.srs-schedule').each(function( index ) {
        var team_id = jQuery( this ).attr('data-teamid');
        var season_id = jQuery( this ).attr('data-seasonid');
        getSchedule(team_id, season_id);
    });
}

var getNextGame = function() {

	var id = jQuery('#srs-nextGame').attr('data-teamid');

	jQuery.ajax({
	    url: "http://api.swissrugbystats.ch/nextGameByTeamId/"+id+"/.json",
	    success: function(data){
	      jQuery('#srs-nextGame').html("Host: " + data.host.team.name + "
Guest: " + data.guest.team.name);
	    }
	});
}

/* execute as soon as DOM is ready
 * TODO: check for existing tags first to reduce ajax calls to minimum
 */
window.onload = function() {

	getSchedules();
	getNextGame();

};<commit_msg>fix small bug<commit_after>'use strict';
/**
 * Created by chregi on 2/28/15.
 * v0.1 - 13.4.2015
 * - fixed: Kickoff time daylight saving independent
 * - new: put Day in schedule table
 */

 // parse a date in yyyy-mm-dd format
function parseDate(input) {
  var parts = input.match(/(\d+)/g);
  // new Date(year, month [, date [, hours[, minutes[, seconds[, ms]]]]])
  return new Date(parts[0], parts[1]-1, parts[2], parts[3], parts[4]); // months are 0-based
}

// get hours to add / subtract to date to fix timezone errors
function getHourCorrection(date) {
    return - (date.getTimezoneOffset() / 60);
}

// Get day of week from a date as String
function getDayOfWeek(date) {
    var dow = ["So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"];
    return dow[date.getDay()];
}

var getSchedule = function(team_id, season_id) {
    var selector = '.srs-schedule[data-teamid='+team_id+']';

	jQuery.ajax({
	    url: "http://api.swissrugbystats.ch/teams/"+team_id+"/games/season/"+season_id+".json",
	    success: function(data){

            /* build schedule table
             * TODO:
             * - set links
            */
            var tableStr = "";
            tableStr = "

Datum	Host	Guest	Kickoff / Result

";
            for (var i = 0; i < data.length; i++) {
                // parse the date
                var d = parseDate(data[i].date);
                var dStr = ("0" + d.getDate()).slice(-2) +"."+ ("0"+(d.getMonth()+1)).slice(-2) +"."+ d.getFullYear();

                // game result
                if ((data[i].host.score != null) && (data[i].guest.score != null)) {
                    var result = data[i].host.score + " : " + data[i].guest.score;
                } else {
                    var result = (d.getHours() + getHourCorrection(d)) + ":"+ ("0" + d.getMinutes()).slice(-2) + " Uhr";
                }

                tableStr += "
" + getDayOfWeek(d) +", "+ dStr + "	" + data[i].host.team.name + "	" + data[i].guest.team.name + "	" + result + "
";
            }

            tableStr += "

";
            jQuery(selector).html(tableStr);

            jQuery(selector).append("

All game data provided by Swiss Rugby Stats");
	    }
	});
}

var getSchedules = function() {

    var scheduleTags = jQuery('.srs-schedule');
    jQuery('.srs-schedule').each(function( index ) {
        var team_id = jQuery( this ).attr('data-teamid');
        var season_id = jQuery( this ).attr('data-seasonid');
        getSchedule(team_id, season_id);
    });
}

var getNextGame = function() {

	var id = jQuery('#srs-nextGame').attr('data-teamid');

	jQuery.ajax({
	    url: "http://api.swissrugbystats.ch/nextGameByTeamId/"+id+"/.json",
	    success: function(data){
	      jQuery('#srs-nextGame').html("Host: " + data.host.team.name + "
Guest: " + data.guest.team.name);
	    }
	});
}

/* execute as soon as DOM is ready
 * TODO: check for existing tags first to reduce ajax calls to minimum
 */
window.onload = function() {

	getSchedules();
	getNextGame();

};<|endoftext|>


<commit_before>var orm = require('orm');
var queue = require('queue-async');
var Cache = require('adaptative-replacement-cache');

module.exports = function(raja, opts, cb) {
	var store = new Store(raja, opts);
	orm.connect(opts.store, function(err, db) {
		if (err) return cb(err);
		store.init(db, cb);
	});
};

function Store(raja, opts) {
	this.reset = opts.reset || false;
	this.raja = raja;
	this.cache = new Cache(opts.cacheSize || 500);
	this.limbo = {};
	this.cache.on('eviction', function(key, resource) {
	}.bind(this));
}

Store.prototype.init = function(db, cb) {
	var SlowResource = this.SlowResource = db.define('SlowResource', {
		key: { type: 'text', index: true },
		url: { type: 'text' },
		mtime: { type: 'date', time: true, index: true },
		maxage: { type: 'integer' },
		headers: { type: 'object' }, // a hash
		valid: { type: 'boolean', defaultValue: true },
		data: { type: 'binary' },
		code: { type: 'integer', defaultValue: 200 }
	}, {
		table: "raja_cached_resources",
		cache: false, // we cache better :)
		hooks: {
			beforeSave: beforeSaveResource
		},
	});

	SlowResource.hasMany("children", SlowResource, {}, {
		reverse : "parents",
		key: true
	});

	var store = this;

	queue(1)
	.defer(SlowResource.drop)
	.defer(SlowResource.sync)
	.awaitAll(function(err) {
		cb(err, store);
	});
};

Store.prototype.store = function(key, resource, cb) {
	var raja = this.raja;
	this.SlowResource.one({key: key}, function(err, row) {
		if (err) return cb(err);
		if (!row) row = new this.SlowResource();
		if (resource.maxage == Infinity) resource.maxage = -1;
		row.save(resource, function(err) {
			if (err) return cb(err);
			var q = queue(2);
			if (resource.resources) {
				q.defer(saveRelations.bind(this), row, resource.resources, true);
			}
			if (resource.parents) {
				q.defer(saveRelations.bind(this), row, resource.parents, false);
			}
			q.awaitAll(cb);
		}.bind(this));
	}.bind(this));
};

function beforeSaveResource() {
	if (this.data != null) {
		if (!Buffer.isBuffer(this.data)) {
			this.data = new Buffer(this.data.toString());
		}
		if (this.valid == null) {
			this.valid = true;
		}
	} else if (this.valid != null) {
		this.valid = false;
	}
	if (!this.headers) this.headers = {};
	this.mtime = new Date();
}

Store.prototype.get = function(key, cb) {
	var resource = this.cache.get(key) || this.limbo[key];
	if (resource) {
		return cb(null, resource);
	}
	this.SlowResource.one({key: key}, function(err, row) {
		if (err || !row) return cb(err);
		var resource = this.raja.create(row);
		if (resource.maxage == -1) resource.maxage = Infinity;
		queue(2)
		.defer(getRelations, row, resource, true)
		.defer(getRelations, row, resource, false)
		.awaitAll(function(err) {
			if (err) return cb(err);
			this.cache.set(key, resource);
			cb(null, resource);
		}.bind(this));
	}.bind(this));
};

Store.prototype.del = function(key, cb) {
	this.cache.del(key);
	this.SlowResource.find({key: key}).remove(cb);
};

Store.prototype.invalidate = function(key, cb) {
	// what happens if it does not find any resource ?
	var resource = this.cache.get(key) || this.limbo[key];
	if (resource) {
		resource.valid = false;
		cb();
		cb = raja.error;
	}
	this.SlowResource.find({key: key}, function(err, rows) {
		if (err) return cb(err);
		if (rows.length > 1) return cb(new Error("invalidate expects only one resource at " + key));
		else if (rows.length == 0) return cb();
		rows[0].valid = false;
		rows[0].save(cb);
	});
};

Store.prototype.invalidateParents = function(msg, cb) {
	var raja = this.raja;
	var cache = this.cache;
	var limbo = this.limbo;
	var key = msg.parents.slice(-1).pop() || msg.key || msg.url;
	if (!key) return cb(new Error("Missing key in " + JSON.stringify(msg)));
	var resource = cache.get(key) || limbo[key];
	var parents = resource && resource.parents;
	var sentMsg = {};
	if (parents) for (var pkey in parents) {
		var parentResource = cache.get(pkey) || limbo[pkey];
		if (!parentResource) {
			continue;
		}
		parentResource.valid = false;
		var cmsg = raja.shallow(msg);
		cmsg.parents = msg.parents.slice();
		cmsg.parents.push(pkey);
		sentMsg[pkey] = true;
		raja.send(cmsg);
	} else {
		parents = {};
	}

	this.SlowResource.find({key: key}, function(err, rows) {
		if (err) return cb(err);
		if (rows.length > 1) return cb(new Error("invalidateParents expects only one resource at " + key));
		else if (rows.length == 0) return cb();
		var res = rows[0];
		res.getParents(function(err, parents) {
			var q = queue(1);
			parents.forEach(function(par) {
				if (sentMsg[par.key]) return; // already dealt with
				var parentResource = cache.get(par.key) || limbo[par.key];
				if (parentResource) parentResource.valid = false;
				par.valid = false;
				q.defer(par.save.bind(par));
				var cmsg = raja.shallow(msg);
				cmsg.parents = msg.parents.slice();
				cmsg.parents.push(par.key);
				raja.send(cmsg);
			});
			q.awaitAll(function(err) {
				cb(err);
			});
		});
	});
};

Store.prototype.set = function(key, resource, cb) {
	var raja = this.raja;
	cb = cb || raja.error;
	var cache = this.cache;
	var limbo = this.limbo;
	var store = this;
	var oldResource = cache.get(key) || limbo[key];
	// remove previous associations if we are going to update them
	if (oldResource && oldResource.resources && resource.resources) for (var rkey in oldResource.resources) {
		var childResource = cache.get(rkey) || limbo[rkey];
		if (childResource && childResource.parents) {
			delete childResource.parents[key];
		}
	}
	if (oldResource && oldResource.parents && resource.parents) for (var rkey in oldResource.parents) {
		var parentResource = cache.get(rkey) || limbo[rkey];
		if (parentResource && parentResource.resources) {
			delete parentResource.resources[key];
		}
	}
	// set new associations
	if (resource.resources) {
		Object.keys(resource.resources).forEach(function(rkey) {
			var resource = cache.get(rkey) || limbo[rkey];
			if (!resource) resource = raja.create({key: rkey});
			if (!resource.parents) {
				resource.parents = {};
			}
			// do not mess with whatever was put there
			if (!resource.parents[key]) {
				resource.parents[key] = true;
			}
		});
	}
	if (resource.parents) {
		Object.keys(resource.parents).forEach(function(rkey) {
			var resource = cache.get(rkey) || limbo[rkey];
			if (!resource) resource = raja.create({key: rkey});
			if (!resource.resources) {
				resource.resources = {};
			}
			// do not mess with whatever was put there
			if (!resource.resources[key]) {
				resource.resources[key] = true;
			}
		});
	}
	beforeSaveResource.call(resource);
	cache.set(key, resource);
	limbo[key] = resource;
	this.store(key, resource, function(err) {
		delete limbo[key];
		cb(err, resource);
	});
};

function saveRelations(inst, hash, isChildren, cb) {
	var self = this;
	var SlowResource = this.SlowResource;
	SlowResource.find({key: Object.keys(hash)}).run(function(err, rows) {
		if (err) return cb(err);
		var notfound = self.raja.shallow(hash);
		rows.forEach(function(row) {
			delete notfound[row.key];
		});
		var q = queue(3);
		for (var rkey in notfound) {
			q.defer(function(rkey, cb) {
				(new SlowResource({key: rkey})).save(cb);
			}, rkey);
		}
		q.awaitAll(function(err, savedRows) {
			var total = rows.concat(savedRows);
			if (isChildren) inst.setChildren(total, cb);
			else inst.setParents(total, cb);
		});
	});
}

function getRelations(row, resource, isChildren, cb) {
	var hash, method;
	if (isChildren) {
		hash = resource.resources = {};
		method = row.getChildren;
	} else {
		hash = resource.parents = {};
		method = row.getParents;
	}
	method.call(row, function(err, rows) {
		if (err) return cb(err);
		rows.forEach(function(row) {
			hash[row.key] = true;
		});
		cb();
	});
}

<commit_msg>Option reset to wipe cache<commit_after>var orm = require('orm');
var queue = require('queue-async');
var Cache = require('adaptative-replacement-cache');

module.exports = function(raja, opts, cb) {
	var store = new Store(raja, opts);
	orm.connect(opts.store, function(err, db) {
		if (err) return cb(err);
		store.init(db, cb);
	});
};

function Store(raja, opts) {
	this.reset = opts.reset || false;
	this.raja = raja;
	this.cache = new Cache(opts.cacheSize || 500);
	this.limbo = {};
	this.cache.on('eviction', function(key, resource) {
	}.bind(this));
}

Store.prototype.init = function(db, cb) {
	var SlowResource = this.SlowResource = db.define('SlowResource', {
		key: { type: 'text', index: true },
		url: { type: 'text' },
		mtime: { type: 'date', time: true, index: true },
		maxage: { type: 'integer' },
		headers: { type: 'object' }, // a hash
		valid: { type: 'boolean', defaultValue: true },
		data: { type: 'binary' },
		code: { type: 'integer', defaultValue: 200 }
	}, {
		table: "raja_cached_resources",
		cache: false, // we cache better :)
		hooks: {
			beforeSave: beforeSaveResource
		},
	});

	SlowResource.hasMany("children", SlowResource, {}, {
		reverse : "parents",
		key: true
	});

	var self = this;

	var q = queue(1);
	if (this.reset) {
		q.defer(SlowResource.drop);
	}
	q.defer(SlowResource.sync).awaitAll(function(err) {
		cb(err, self);
	});
};

Store.prototype.store = function(key, resource, cb) {
	var raja = this.raja;
	this.SlowResource.one({key: key}, function(err, row) {
		if (err) return cb(err);
		if (!row) row = new this.SlowResource();
		if (resource.maxage == Infinity) resource.maxage = -1;
		row.save(resource, function(err) {
			if (err) return cb(err);
			var q = queue(2);
			if (resource.resources) {
				q.defer(saveRelations.bind(this), row, resource.resources, true);
			}
			if (resource.parents) {
				q.defer(saveRelations.bind(this), row, resource.parents, false);
			}
			q.awaitAll(cb);
		}.bind(this));
	}.bind(this));
};

function beforeSaveResource() {
	if (this.data != null) {
		if (!Buffer.isBuffer(this.data)) {
			this.data = new Buffer(this.data.toString());
		}
		if (this.valid == null) {
			this.valid = true;
		}
	} else if (this.valid != null) {
		this.valid = false;
	}
	if (!this.headers) this.headers = {};
	this.mtime = new Date();
}

Store.prototype.get = function(key, cb) {
	var resource = this.cache.get(key) || this.limbo[key];
	if (resource) {
		return cb(null, resource);
	}
	this.SlowResource.one({key: key}, function(err, row) {
		if (err || !row) return cb(err);
		var resource = this.raja.create(row);
		if (resource.maxage == -1) resource.maxage = Infinity;
		queue(2)
		.defer(getRelations, row, resource, true)
		.defer(getRelations, row, resource, false)
		.awaitAll(function(err) {
			if (err) return cb(err);
			this.cache.set(key, resource);
			cb(null, resource);
		}.bind(this));
	}.bind(this));
};

Store.prototype.del = function(key, cb) {
	this.cache.del(key);
	this.SlowResource.find({key: key}).remove(cb);
};

Store.prototype.invalidate = function(key, cb) {
	// what happens if it does not find any resource ?
	var resource = this.cache.get(key) || this.limbo[key];
	if (resource) {
		resource.valid = false;
		cb();
		cb = raja.error;
	}
	this.SlowResource.find({key: key}, function(err, rows) {
		if (err) return cb(err);
		if (rows.length > 1) return cb(new Error("invalidate expects only one resource at " + key));
		else if (rows.length == 0) return cb();
		rows[0].valid = false;
		rows[0].save(cb);
	});
};

Store.prototype.invalidateParents = function(msg, cb) {
	var raja = this.raja;
	var cache = this.cache;
	var limbo = this.limbo;
	var key = msg.parents.slice(-1).pop() || msg.key || msg.url;
	if (!key) return cb(new Error("Missing key in " + JSON.stringify(msg)));
	var resource = cache.get(key) || limbo[key];
	var parents = resource && resource.parents;
	var sentMsg = {};
	if (parents) for (var pkey in parents) {
		var parentResource = cache.get(pkey) || limbo[pkey];
		if (!parentResource) {
			continue;
		}
		parentResource.valid = false;
		var cmsg = raja.shallow(msg);
		cmsg.parents = msg.parents.slice();
		cmsg.parents.push(pkey);
		sentMsg[pkey] = true;
		raja.send(cmsg);
	} else {
		parents = {};
	}

	this.SlowResource.find({key: key}, function(err, rows) {
		if (err) return cb(err);
		if (rows.length > 1) return cb(new Error("invalidateParents expects only one resource at " + key));
		else if (rows.length == 0) return cb();
		var res = rows[0];
		res.getParents(function(err, parents) {
			var q = queue(1);
			parents.forEach(function(par) {
				if (sentMsg[par.key]) return; // already dealt with
				var parentResource = cache.get(par.key) || limbo[par.key];
				if (parentResource) parentResource.valid = false;
				par.valid = false;
				q.defer(par.save.bind(par));
				var cmsg = raja.shallow(msg);
				cmsg.parents = msg.parents.slice();
				cmsg.parents.push(par.key);
				raja.send(cmsg);
			});
			q.awaitAll(function(err) {
				cb(err);
			});
		});
	});
};

Store.prototype.set = function(key, resource, cb) {
	var raja = this.raja;
	cb = cb || raja.error;
	var cache = this.cache;
	var limbo = this.limbo;
	var store = this;
	var oldResource = cache.get(key) || limbo[key];
	// remove previous associations if we are going to update them
	if (oldResource && oldResource.resources && resource.resources) for (var rkey in oldResource.resources) {
		var childResource = cache.get(rkey) || limbo[rkey];
		if (childResource && childResource.parents) {
			delete childResource.parents[key];
		}
	}
	if (oldResource && oldResource.parents && resource.parents) for (var rkey in oldResource.parents) {
		var parentResource = cache.get(rkey) || limbo[rkey];
		if (parentResource && parentResource.resources) {
			delete parentResource.resources[key];
		}
	}
	// set new associations
	if (resource.resources) {
		Object.keys(resource.resources).forEach(function(rkey) {
			var resource = cache.get(rkey) || limbo[rkey];
			if (!resource) resource = raja.create({key: rkey});
			if (!resource.parents) {
				resource.parents = {};
			}
			// do not mess with whatever was put there
			if (!resource.parents[key]) {
				resource.parents[key] = true;
			}
		});
	}
	if (resource.parents) {
		Object.keys(resource.parents).forEach(function(rkey) {
			var resource = cache.get(rkey) || limbo[rkey];
			if (!resource) resource = raja.create({key: rkey});
			if (!resource.resources) {
				resource.resources = {};
			}
			// do not mess with whatever was put there
			if (!resource.resources[key]) {
				resource.resources[key] = true;
			}
		});
	}
	beforeSaveResource.call(resource);
	cache.set(key, resource);
	limbo[key] = resource;
	this.store(key, resource, function(err) {
		delete limbo[key];
		cb(err, resource);
	});
};

function saveRelations(inst, hash, isChildren, cb) {
	var self = this;
	var SlowResource = this.SlowResource;
	SlowResource.find({key: Object.keys(hash)}).run(function(err, rows) {
		if (err) return cb(err);
		var notfound = self.raja.shallow(hash);
		rows.forEach(function(row) {
			delete notfound[row.key];
		});
		var q = queue(3);
		for (var rkey in notfound) {
			q.defer(function(rkey, cb) {
				(new SlowResource({key: rkey})).save(cb);
			}, rkey);
		}
		q.awaitAll(function(err, savedRows) {
			var total = rows.concat(savedRows);
			if (isChildren) inst.setChildren(total, cb);
			else inst.setParents(total, cb);
		});
	});
}

function getRelations(row, resource, isChildren, cb) {
	var hash, method;
	if (isChildren) {
		hash = resource.resources = {};
		method = row.getChildren;
	} else {
		hash = resource.parents = {};
		method = row.getParents;
	}
	method.call(row, function(err, rows) {
		if (err) return cb(err);
		rows.forEach(function(row) {
			hash[row.key] = true;
		});
		cb();
	});
}

<|endoftext|>


<commit_before>function Shuffle(pContainer) {
    var container = null;

    var canvas = null;
    var border = 0;
    var context = null;
    var bgColor = null;

    var self = this;
    var alphabet = 'abcdefghijklmnopqrstuvwxyz';
    var alphaHash = {};
    var base_dir = 'images/';
    var fileextension = '.png';
    var i = 0;

    var getImages = function() {
        var letter = alphabet[i];
        if (i === alphabet.length || typeof(letter) === 'undefined') {
            return;
        }

        var dir = base_dir + letter + '/';
        alphaHash[letter] = [];

        $.ajax({
            //This will retrieve the contents of the folder
            //if the folder is configured as 'browsable'
            url: dir,
            success: function (data) {
                //List all .png file names in the page
                console.log(data);
                $(data).find('a:contains(' + fileextension + ')').each(function () {
                    var filename = this.href.replace(window.location.href, '').replace('http://', '');
                    var img = $("")[0];
                    alphaHash[letter].push(img);
                    $(container).append(img);
                });

                getImages(alphabet[++i]);
            }
        });
    };

    var getRandomInt = function(min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    };

    var getRandomImage = function(letter) {
        if (!alphaHash || !alphaHash[letter] ||
            alphaHash[letter].length === 0)
        {
            console.err('Fail to get images for letter: ', letter);
            return;
        }

        if (!context) {
            console.err('No context for canvas');
            return;
        }

        // pick random image from available
        var letterImages = alphaHash[letter];
        var index = getRandomInt(0, letterImages.length - 1)
        var img = letterImages[index];

        if (!img) {
            console.err('Images array overflow');
        }

        return img;
    };

    var drawLetter = function(letter) {
        var image = getRandomImage(letter);

        var width = getRandomInt(0, canvas.width - border);
        var height = getRandomInt(0, canvas.height - border);
        var scaleFactor = getRandomInt(5, 20);

        context.drawImage(image, width, height, image.width/scaleFactor, image.height/scaleFactor);
    };

    var registerListener = function() {
        $('body').keypress(function (ev) {
            var sign = String.fromCharCode(ev.which);
            if (alphabet.indexOf(sign) !== -1) {
                console.log(sign);
                drawLetter(sign);
            }
        });
    };

    function init() {
        container = $(pContainer);
        canvas = $('<canvas></canvas>')[0];
        context = canvas.getContext('2d');

        // resize to full screen
        self.resize(window.innerWidth, window.innerHeight, 100);
        container.append(canvas);
        self.setBackground('white');

        registerListener();
        getImages();
    };

    this.getHash = function() {
        return alphaHash;
    };

    this.resize = function(w, h, borderSize) {
        console.log('canvas (w: %d, h: %d)', w, h);
        canvas.width = w;
        canvas.height = h;
        if (borderSize) {
            border = borderSize;
        }
    };

    this.clear = function() {
        context.beginPath();
        context.rect(0, 0, canvas.width, canvas.height);
        context.fillStyle = bgColor;
        context.fill();
    };

    this.saveImage = function() {
        var capture = canvas.toDataURL('image/png');
        var href = capture.replace(/^data:image\/[^;]/, 'data:application/octet-stream');
        return href;
    };

    this.setBackground = function(color) {
        bgColor = color;
        self.clear();
    }

    init();
};
<commit_msg>* Make improvements on drawing<commit_after>function Shuffle(pContainer) {
    var container = null;

    var canvas = null;
    var border = 0;
    var context = null;
    var bgColor = null;

    var self = this;
    var alphabet = 'abcdefghijklmnopqrstuvwxyz';
    var alphaHash = {};
    var base_dir = 'images/';
    var fileextension = '.png';
    var i = 0;

    var getImages = function() {
        var letter = alphabet[i];
        if (i === alphabet.length || typeof(letter) === 'undefined') {
            return;
        }

        var dir = base_dir + letter + '/';
        alphaHash[letter] = [];

        $.ajax({
            //This will retrieve the contents of the folder
            //if the folder is configured as 'browsable'
            url: dir,
            success: function (data) {
                //List all .png file names in the page
                console.log(data);
                $(data).find('a:contains(' + fileextension + ')').each(function () {
                    var filename = this.href.replace(window.location.href, '').replace('http://', '');
                    var img = $("")[0];
                    alphaHash[letter].push(img);
                    $(container).append(img);
                });

                getImages(alphabet[++i]);
            }
        });
    };

    var getRandomInt = function(min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    };

    var getRandomImage = function(letter) {
        if (!alphaHash || !alphaHash[letter] ||
            alphaHash[letter].length === 0)
        {
            console.err('Fail to get images for letter: ', letter);
            return;
        }

        if (!context) {
            console.err('No context for canvas');
            return;
        }

        // pick random image from available
        var letterImages = alphaHash[letter];
        var index = getRandomInt(0, letterImages.length - 1)
        var img = letterImages[index];

        if (!img) {
            console.err('Images array overflow');
        }

        return img;
    };

    var drawLetter = function(letter) {
        var image = getRandomImage(letter);

        var wlimit = canvas.width - border;
        wlimit = wlimit > 0 ? wlimit: 0;

        var hlimit = canvas.height - border;
        hlimit = hlimit > 0 ? hlimit: 0;

        var width = getRandomInt(0, wlimit);
        var height = getRandomInt(0, hlimit);

//         if (width + image.width > canvas.width) {
//             width -= Math.abs(image.width - canvas.width);
//         }
//
//         if (height+ image.height > canvas.height) {
//             height -= Math.abs(image.height - canvas.height);
//         }

        var operation = getRandomInt(0, 1);

        if (operation === 0) {
            var scaleFactor = getRandomInt(1, 5);
            context.drawImage(image, width, height, image.width/scaleFactor, image.height/scaleFactor);
        } else {
            var scaleFactor = getRandomInt(1, 3);
            console.log('multiply');
            context.drawImage(image, width, height, image.width*scaleFactor, image.height*scaleFactor);
        }
    };

    var registerListener = function() {
        $('body').keypress(function (ev) {
            var sign = String.fromCharCode(ev.which);
            if (alphabet.indexOf(sign) !== -1) {
                console.log(sign);
                drawLetter(sign);
            }
        });
    };

    function init() {
        container = $(pContainer);
        canvas = $('<canvas></canvas>')[0];
        context = canvas.getContext('2d');

        // resize to full screen
        self.resize(window.innerWidth, window.innerHeight, 300);
        container.append(canvas);
        self.setBackground('white');

        registerListener();
        getImages();
    };

    this.getHash = function() {
        return alphaHash;
    };

    this.resize = function(w, h, borderSize) {
        console.log('canvas (w: %d, h: %d)', w, h);
        canvas.width = w;
        canvas.height = h;
        if (borderSize) {
            border = borderSize;
        }
    };

    this.clear = function() {
        context.beginPath();
        context.rect(0, 0, canvas.width, canvas.height);
        context.fillStyle = bgColor;
        context.fill();
    };

    this.saveImage = function() {
        var capture = canvas.toDataURL('image/png');
        var href = capture.replace(/^data:image\/[^;]/, 'data:application/octet-stream');
        return href;
    };

    this.setBackground = function(color) {
        bgColor = color;
        self.clear();
    }

    init();
};
<|endoftext|>


<commit_before>'use strict';

let comm = require('./common.js'),
  progress = require('request-progress'),
  path = require('path'),
  request = require("request"),
  fs = require('fs-extra');

function downloadFile(fromUrl, toFile, onFinish) {
  //request(fromUrl).pipe(fs.createWriteStream(toFile)).on('finish', onFinish);
  let previous = -1;

  progress(request(fromUrl), {
    throttle: 5000,
    delay: 0,
    lengthHeader: 'content-length'
  })
  .on('progress', (state) => {
    if (previous == -1) {
      console.log('[INFO] \'' + toFile + '\' download started from \'' + fromUrl + '\'');
      console.log('0%');
      previous = 0;
    }
    let current = Math.round(state.percentage*100);
    if(current!=100 && current!=0 && previous!=current) {
      console.log(current + '%');
    }
    previous = current;
  })
  .on('end',()=>{
    if (previous == -1) {
      console.log('[INFO] \'' + toFile + '\' download started from \'' + fromUrl + '\'');
      console.log('0%');
    }
    console.log('100%');
  })
  .pipe(fs.createWriteStream(toFile)).on('finish', onFinish);
}

function downloadAndReadSHA256(targetFolder, fileName, reqURL, reject, processResult) {
  let currentFile = path.join(targetFolder, fileName);
  let currentSHA256 = 'NOSHA256SUM';
  if (reqURL.length == 64 && reqURL.indexOf("http")<0 && reqURL.indexOf("ftp")<0) {
    // return the hardcoded SHA256sum in requirements.json
    if(!fileName.endsWith('.sha256')) {
      console.log('[INFO] \'' + fileName + '\' hardcoded sha256 check');
    }
    processResult(reqURL);
  } else {
    // download the remote SHA256sum, save the file, and return its value to compare to existing downloaded file
    console.log('[INFO] \'' + fileName + '\' remote sha256 check');
    downloadFile(reqURL, currentFile, (err, res)=>{
      if (err) {
        reject(err);
      } else {
        // read the contents of the sha256sum file
        currentSHA256 = fs.readFileSync(currentFile,'utf8');
        processResult(currentSHA256);
      }
    });
  }
}

function downloadFileAndCreateSha256(targetFolder, fileName, reqURL, sha256sum, resolve, reject) {
  let currentFile = path.join(targetFolder, fileName);
  downloadFile(reqURL, currentFile, (err, res)=>{
    if (err) {
      reject(err);
    } else {
      comm.getSHA256(currentFile,(currentSHA256)=>{
        if(currentSHA256 == sha256sum) {
          console.log( '[INFO] \'' + currentFile + '\' is downloaded and sha256 is correct');
          comm.createSHA256File(currentFile,(shaGenError)=>{
            shaGenError ? reject(shaGenError) : resolve(res);
          });
        } else {
          reject( '\'' + currentFile + '\' is downloaded and sha256 is not correct');
        }
      });
    }
  });
}

function prefetch(reqs, bundle, targetFolder) {
  let promises = new Array();
  for (let key in reqs) {
    if (reqs[key].bundle === bundle) {
      let currentUrl = reqs[key].url;
      let currentFile = path.join(targetFolder, key);
      promises.push(() => {
        return new Promise((resolve,reject) => {
          // if file is already downloaded, check its sha against the stored one
          downloadAndReadSHA256(targetFolder, key + ".sha256", reqs[key].sha256sum, reject, (currentSHA256) => {
            //console.log('[DEBUG] SHA256SUM for ' + key + ' = ' + currentSHA256);
            comm.isExistingSHA256Current(currentFile, currentSHA256, (dl) => {
              if(dl) {
                console.log('[INFO] \'' + currentFile + '\' SHA256 is correct, no download required');
                resolve(true);
              } else {
                if(fs.existsSync(currentFile)) {
                  console.log('[INFO] \'' + currentFile + '\' SHA256 is not correct, download required');
                } else {
                  console.log('[INFO] \'' + currentFile + '\' is not downloaded yet');
                }
                downloadFileAndCreateSha256(targetFolder, key, reqs[key].url, currentSHA256, resolve, reject);
              }
            });
          });
        })
      });
    }
  }
  return promises.reduce( function(pacc, fn) { return pacc.then(fn); }, Promise.resolve() );
};

module.exports = {
  downloadFile,
  downloadAndReadSHA256,
  downloadFileAndCreateSha256,
  prefetch
}
<commit_msg>Rename percentage to percent for request-progress 3.0<commit_after>'use strict';

let comm = require('./common.js'),
  progress = require('request-progress'),
  path = require('path'),
  request = require("request"),
  fs = require('fs-extra');

function downloadFile(fromUrl, toFile, onFinish) {
  //request(fromUrl).pipe(fs.createWriteStream(toFile)).on('finish', onFinish);
  let previous = -1;

  progress(request(fromUrl), {
    throttle: 5000,
    delay: 0,
    lengthHeader: 'content-length'
  })
  .on('progress', (state) => {
    if (previous == -1) {
      console.log('[INFO] \'' + toFile + '\' download started from \'' + fromUrl + '\'');
      console.log('0%');
      previous = 0;
    }
    let current = Math.round(state.percent*100);
    if(current!=100 && current!=0 && previous!=current) {
      console.log(current + '%');
    }
    previous = current;
  })
  .on('end',()=>{
    if (previous == -1) {
      console.log('[INFO] \'' + toFile + '\' download started from \'' + fromUrl + '\'');
      console.log('0%');
    }
    console.log('100%');
  })
  .pipe(fs.createWriteStream(toFile)).on('finish', onFinish);
}

function downloadAndReadSHA256(targetFolder, fileName, reqURL, reject, processResult) {
  let currentFile = path.join(targetFolder, fileName);
  let currentSHA256 = 'NOSHA256SUM';
  if (reqURL.length == 64 && reqURL.indexOf("http")<0 && reqURL.indexOf("ftp")<0) {
    // return the hardcoded SHA256sum in requirements.json
    if(!fileName.endsWith('.sha256')) {
      console.log('[INFO] \'' + fileName + '\' hardcoded sha256 check');
    }
    processResult(reqURL);
  } else {
    // download the remote SHA256sum, save the file, and return its value to compare to existing downloaded file
    console.log('[INFO] \'' + fileName + '\' remote sha256 check');
    downloadFile(reqURL, currentFile, (err, res)=>{
      if (err) {
        reject(err);
      } else {
        // read the contents of the sha256sum file
        currentSHA256 = fs.readFileSync(currentFile,'utf8');
        processResult(currentSHA256);
      }
    });
  }
}

function downloadFileAndCreateSha256(targetFolder, fileName, reqURL, sha256sum, resolve, reject) {
  let currentFile = path.join(targetFolder, fileName);
  downloadFile(reqURL, currentFile, (err, res)=>{
    if (err) {
      reject(err);
    } else {
      comm.getSHA256(currentFile,(currentSHA256)=>{
        if(currentSHA256 == sha256sum) {
          console.log( '[INFO] \'' + currentFile + '\' is downloaded and sha256 is correct');
          comm.createSHA256File(currentFile,(shaGenError)=>{
            shaGenError ? reject(shaGenError) : resolve(res);
          });
        } else {
          reject( '\'' + currentFile + '\' is downloaded and sha256 is not correct');
        }
      });
    }
  });
}

function prefetch(reqs, bundle, targetFolder) {
  let promises = new Array();
  for (let key in reqs) {
    if (reqs[key].bundle === bundle) {
      let currentUrl = reqs[key].url;
      let currentFile = path.join(targetFolder, key);
      promises.push(() => {
        return new Promise((resolve,reject) => {
          // if file is already downloaded, check its sha against the stored one
          downloadAndReadSHA256(targetFolder, key + ".sha256", reqs[key].sha256sum, reject, (currentSHA256) => {
            //console.log('[DEBUG] SHA256SUM for ' + key + ' = ' + currentSHA256);
            comm.isExistingSHA256Current(currentFile, currentSHA256, (dl) => {
              if(dl) {
                console.log('[INFO] \'' + currentFile + '\' SHA256 is correct, no download required');
                resolve(true);
              } else {
                if(fs.existsSync(currentFile)) {
                  console.log('[INFO] \'' + currentFile + '\' SHA256 is not correct, download required');
                } else {
                  console.log('[INFO] \'' + currentFile + '\' is not downloaded yet');
                }
                downloadFileAndCreateSha256(targetFolder, key, reqs[key].url, currentSHA256, resolve, reject);
              }
            });
          });
        })
      });
    }
  }
  return promises.reduce( function(pacc, fn) { return pacc.then(fn); }, Promise.resolve() );
};

module.exports = {
  downloadFile,
  downloadAndReadSHA256,
  downloadFileAndCreateSha256,
  prefetch
}
<|endoftext|>


<commit_before>function Shuffle(pContainer) {
    var container = null;

    var canvas = null;
    var border = 0;
    var context = null;
    var bgColor = null;

    var self = this;
    var alphabet = 'abcdefghijklmnopqrstuvwxyz';
    var alphaHash = {};
    var base_dir = 'images/';
    var fileextension = '.png';
    var i = 0;

    var getImages = function() {
        var letter = alphabet[i];
        if (i === alphabet.length || typeof(letter) === 'undefined') {
            return;
        }

        var dir = base_dir + letter + '/';
        alphaHash[letter] = [];

        $.ajax({
            //This will retrieve the contents of the folder
            //if the folder is configured as 'browsable'
            url: dir,
            success: function (data) {
                //List all .png file names in the page
                console.log(data);
                $(data).find('a:contains(' + fileextension + ')').each(function () {
                    var filename = this.href.replace(window.location.href, '').replace('http://', '');
                    var img = $("")[0];
                    alphaHash[letter].push(img);
                    $(container).append(img);
                });

                getImages(alphabet[++i]);
            }
        });
    };

    var getRandomInt = function(min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    };

    var getRandomImage = function(letter) {
        if (!alphaHash || !alphaHash[letter] ||
            alphaHash[letter].length === 0)
        {
            console.err('Fail to get images for letter: ', letter);
            return;
        }

        if (!context) {
            console.err('No context for canvas');
            return;
        }

        // pick random image from available
        var letterImages = alphaHash[letter];
        var index = getRandomInt(0, letterImages.length - 1)
        var img = letterImages[index];

        if (!img) {
            console.err('Images array overflow');
        }

        return img;
    };

    var drawLetter = function(letter) {
        var image = getRandomImage(letter);

        var wlimit = canvas.width - border;
        wlimit = wlimit > 0 ? wlimit: 0;

        var hlimit = canvas.height - border;
        hlimit = hlimit > 0 ? hlimit: 0;

        var width = getRandomInt(0, wlimit);
        var height = getRandomInt(0, hlimit);

//         if (width + image.width > canvas.width) {
//             width -= Math.abs(image.width - canvas.width);
//         }
//
//         if (height+ image.height > canvas.height) {
//             height -= Math.abs(image.height - canvas.height);
//         }

        var operation = getRandomInt(0, 1);

        if (operation === 0) {
            var scaleFactor = getRandomInt(1, 5);
            context.drawImage(image, width, height, image.width/scaleFactor, image.height/scaleFactor);
        } else {
            var scaleFactor = getRandomInt(1, 3);
            console.log('multiply');
            context.drawImage(image, width, height, image.width*scaleFactor, image.height*scaleFactor);
        }
    };

    var registerListener = function() {
        $('body').keypress(function (ev) {
            var sign = String.fromCharCode(ev.which);
            if (alphabet.indexOf(sign) !== -1) {
                console.log(sign);
                drawLetter(sign);
            }
        });
    };

    function init() {
        container = $(pContainer);
        canvas = $('<canvas></canvas>')[0];
        context = canvas.getContext('2d');

        // resize to full screen
        self.resize(window.innerWidth, window.innerHeight, 300);
        container.append(canvas);
        self.setBackground('white');

        registerListener();
        getImages();
    };

    this.getHash = function() {
        return alphaHash;
    };

    this.resize = function(w, h, borderSize) {
        console.log('canvas (w: %d, h: %d)', w, h);
        canvas.width = w;
        canvas.height = h;
        if (borderSize) {
            border = borderSize;
        }
    };

    this.clear = function() {
        context.beginPath();
        context.rect(0, 0, canvas.width, canvas.height);
        context.fillStyle = bgColor;
        context.fill();
    };

    this.saveImage = function() {
        var capture = canvas.toDataURL('image/png');
        var href = capture.replace(/^data:image\/[^;]/, 'data:application/octet-stream');
        return href;
    };

    this.setBackground = function(color) {
        bgColor = color;
        self.clear();
    }

    init();
};
<commit_msg>* Improve random positioning. * Fix overflow issue<commit_after>function Shuffle(pContainer) {
    var container = null;

    var canvas = null;
    var border = 0;
    var context = null;
    var bgColor = null;

    var self = this;
    var alphabet = 'abcdefghijklmnopqrstuvwxyz';
    var alphaHash = {};
    var base_dir = 'images/';
    var fileextension = '.png';
    var i = 0;

    var getImages = function() {
        var letter = alphabet[i];
        if (i === alphabet.length || typeof(letter) === 'undefined') {
            return;
        }

        var dir = base_dir + letter + '/';
        alphaHash[letter] = [];

        $.ajax({
            //This will retrieve the contents of the folder
            //if the folder is configured as 'browsable'
            url: dir,
            success: function (data) {
                //List all .png file names in the page
                console.log(data);
                $(data).find('a:contains(' + fileextension + ')').each(function () {
                    var filename = this.href.replace(window.location.href, '').replace('http://', '');
                    var img = $("")[0];
                    alphaHash[letter].push(img);
                    $(container).append(img);
                });

                getImages(alphabet[++i]);
            }
        });
    };

    var getRandomInt = function(min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    };

    var getRandomImage = function(letter) {
        if (!alphaHash || !alphaHash[letter] ||
            alphaHash[letter].length === 0)
        {
            console.err('Fail to get images for letter: ', letter);
            return;
        }

        if (!context) {
            console.err('No context for canvas');
            return;
        }

        // pick random image from available
        var letterImages = alphaHash[letter];
        var index = getRandomInt(0, letterImages.length - 1)
        var img = letterImages[index];

        if (!img) {
            console.err('Images array overflow');
        }

        return img;
    };

    var drawLetter = function(letter) {
        var image = getRandomImage(letter);

        // if we have a set border, substrack its width/height
        // from canvas area
        var wlimit = canvas.width - border;
        wlimit = wlimit > 0 ? wlimit: 0;

        var hlimit = canvas.height - border;
        hlimit = hlimit > 0 ? hlimit: 0;

        var widthStart = getRandomInt(0, wlimit);
        var heightStart = getRandomInt(0, hlimit);
        var dstWidth = 0;
        var dstHeight = 0;

        var operation = getRandomInt(0, 1);
        if (operation === 0) {
            var scaleFactor = getRandomInt(1, 5);
            dstWidth = image.width / scaleFactor;
            dstHeight = image.height / scaleFactor;
        } else {
            var scaleFactor = getRandomInt(1, 3);
            dstWidth = image.width * scaleFactor;
            dstHeight = image.height * scaleFactor;
        }

        if (widthStart + dstWidth > canvas.width) {
            widthStart -= Math.abs((widthStart + dstWidth) - canvas.width);
        }

        if (heightStart + dstHeight > canvas.height) {
            heightStart -= Math.abs((heightStart + dstHeight) - canvas.height);
        }

        context.drawImage(image, widthStart, heightStart, dstWidth, dstHeight);
    };

    var registerListener = function() {
        $('body').keypress(function (ev) {
            var sign = String.fromCharCode(ev.which);
            if (alphabet.indexOf(sign) !== -1) {
                console.log(sign);
                drawLetter(sign);
            }
        });
    };

    function init() {
        container = $(pContainer);
        canvas = $('<canvas></canvas>')[0];
        context = canvas.getContext('2d');

        // resize to full screen
        self.resize(window.innerWidth, window.innerHeight, 100);
        container.append(canvas);
        self.setBackground('white');

        registerListener();
        getImages();
    };

    this.getHash = function() {
        return alphaHash;
    };

    this.resize = function(w, h, borderSize) {
        console.log('canvas (w: %d, h: %d)', w, h);
        canvas.width = w;
        canvas.height = h;
        if (borderSize) {
            border = borderSize;
        }
    };

    this.clear = function() {
        context.beginPath();
        context.rect(0, 0, canvas.width, canvas.height);
        context.fillStyle = bgColor;
        context.fill();
    };

    this.saveImage = function() {
        var capture = canvas.toDataURL('image/png');
        var href = capture.replace(/^data:image\/[^;]/, 'data:application/octet-stream');
        return href;
    };

    this.setBackground = function(color) {
        bgColor = color;
        self.clear();
    }

    init();
};
<|endoftext|>


<commit_before>import './adventure_selector_action_menu.html';
import { Template } from 'meteor/templating';
import { NodeReadyCheckFns } from '../../../../../imports/api/node/node_ready_check_fns.js';
import { NodeValidCheckFns } from '../../../../../imports/api/node/node_valid_check_fns.js';
import './adventure_selector_action_target_menu.js';

/**
 * Template Helpers
 */
Template.AdventureSelectorActionMenu.helpers({
  readyCheckFns () {
    return _.values(NodeReadyCheckFns)
  },
  validCheckFns () {
    return _.values(NodeValidCheckFns)
  },
  getSelector () {
    let selector = this.selector;
    return selector.selector || selector;
  }
});

/**
 * Template Event Handlers
 */
Template.AdventureSelectorActionMenu.events({});

/**
 * Template Created
 */
Template.AdventureSelectorActionMenu.onCreated(() => {

});

/**
 * Template Rendered
 */
Template.AdventureSelectorActionMenu.onRendered(() => {

});

/**
 * Template Destroyed
 */
Template.AdventureSelectorActionMenu.onDestroyed(() => {

});
<commit_msg>Added a null check to selectors check to prevent broken menus<commit_after>import './adventure_selector_action_menu.html';
import { Template } from 'meteor/templating';
import { NodeReadyCheckFns } from '../../../../../imports/api/nodes/node_ready_check_fns.js';
import { NodeValidCheckFns } from '../../../../../imports/api/nodes/node_valid_check_fns.js';
import './adventure_selector_action_target_menu.js';

/**
 * Template Helpers
 */
Template.AdventureSelectorActionMenu.helpers({
  readyCheckFns () {
    return _.values(NodeReadyCheckFns)
  },
  validCheckFns () {
    return _.values(NodeValidCheckFns)
  },
  getSelector () {
    let selector = this.selector;
    if(selector){
      return selector.selector || selector;
    }
  }
});

/**
 * Template Event Handlers
 */
Template.AdventureSelectorActionMenu.events({});

/**
 * Template Created
 */
Template.AdventureSelectorActionMenu.onCreated(() => {

});

/**
 * Template Rendered
 */
Template.AdventureSelectorActionMenu.onRendered(() => {

});

/**
 * Template Destroyed
 */
Template.AdventureSelectorActionMenu.onDestroyed(() => {

});
<|endoftext|>


<commit_before>"use strict";

var q = require('q'),
  QSVN = require('q-svn'),
  ReleaseUtils = require('./release-utils'),
  semver = require('semver'),
  _ = require('lodash');

var svn = new QSVN('.'),
  utils = new ReleaseUtils(svn);

module.exports = {
  branch: branch,
  release: release
};

function release(releaseOptions) {

  return noLocalChanges()
    .then(mergeReleaseOptions(releaseOptions))
    .then(function (options) {
      utils.setVersion(options.tagVersion)
        .then(commit())
        .then(copy(options.repoUrl, utils.tagUrl(options)))
        .then(utils.setVersion(options.nextVersion))
        .then(commit());
    });

  function mergeReleaseOptions(providedReleaseOptions) {

    return q.spread([utils.loadPackageJson(), svn.info()], defaultReleaseOptions)
      .then(mergeWithProvided);

    function defaultReleaseOptions(packageJson, repoInfo) {
      return {
        trunk: 'trunk',
        branches: 'branches',
        tags: 'tags',
        tagName: packageJson.version,
        tagVersion: packageJson.version,
        nextVersion: semver.inc(packageJson.version, 'patch'),
        repoRoot: repoInfo['repositoryroot'],
        repoUrl: repoInfo.url
      };
    }

    function mergeWithProvided(releaseOptions) {
      return _.extend(releaseOptions, providedReleaseOptions);
    }
  }

  function copy(source, target) {
    return function () {
      return svn.copy(source, target, 'svn-release: release');
    };
  }

  function commit() {
    return function () {
      return svn.commit([], 'svn-release: release');
    };
  }
}

function branch(branchOptions) {

  return noLocalChanges()
    .then(mergeBranchOptions(branchOptions))
    .then(function (options) {
      utils.setVersion(options.branchVersion)
        .then(commit())
        .then(copy(options.repoUrl, utils.branchUrl(options)))
        .then(utils.setVersion(options.nextVersion))
        .then(commit());
    });

  function mergeBranchOptions(providedBranchOptions) {

    return q.spread([utils.loadPackageJson(), svn.info()], defaultBranchOptions)
      .then(mergeWithProvided);

    function defaultBranchOptions(packageJson, repoInfo) {
      return {
        trunk: 'trunk',
        branches: 'branches',
        tags: 'tags',
        branchName: semver.major(packageJson.version) + '.' + semver.minor(packageJson.version),
        branchVersion: packageJson.version,
        nextVersion: semver.inc(packageJson.version, 'minor'),
        repoRoot: repoInfo['repositoryroot'],
        repoUrl: repoInfo.url
      };
    }

    function mergeWithProvided(branchOptions) {
      return _.extend(branchOptions, providedBranchOptions);
    }
  }

  function copy(source, target) {
    return function () {
      return svn.copy(source, target, 'svn-release: branch');
    };
  }

  function commit() {
    return function () {
      return svn.commit([], 'svn-release: branch');
    };
  }
}

function noLocalChanges() {
  return svn.status().then(utils.failOnChanges);
}<commit_msg>svn-release basic release functionality<commit_after>"use strict";

var q = require('q'),
  utils = require('./release-utils'),
  semver = require('semver'),
  _ = require('lodash'),
  QSVN = require('q-svn'),
  svn = new QSVN('.');

module.exports = {
  branch: branch,
  release: release
};

function release(releaseOptions) {

  return noLocalChanges()
    .then(mergeReleaseOptions(releaseOptions))
    .then(function (options) {
      utils.setVersion(options.tagVersion)
        .then(commit())
        .then(copy(options.repoUrl, utils.tagUrl(options)))
        .then(utils.setVersion(options.nextVersion))
        .then(commit());
    });

  function mergeReleaseOptions(providedReleaseOptions) {

    return q.spread([utils.loadPackageJson(), svn.info()], defaultReleaseOptions)
      .then(mergeWithProvided);

    function defaultReleaseOptions(packageJson, repoInfo) {
      return {
        trunk: 'trunk',
        branches: 'branches',
        tags: 'tags',
        tagName: packageJson.version,
        tagVersion: packageJson.version,
        nextVersion: semver.inc(packageJson.version, 'patch'),
        repoRoot: repoInfo['repositoryroot'],
        repoUrl: repoInfo.url
      };
    }

    function mergeWithProvided(releaseOptions) {
      return _.extend(releaseOptions, providedReleaseOptions);
    }
  }

  function copy(source, target) {
    return function () {
      return svn.copy(source, target, 'svn-release: release');
    };
  }

  function commit() {
    return function () {
      return svn.commit([], 'svn-release: release');
    };
  }
}

function branch(branchOptions) {

  return noLocalChanges()
    .then(mergeBranchOptions(branchOptions))
    .then(function (options) {
      utils.setVersion(options.branchVersion)
        .then(commit())
        .then(copy(options.repoUrl, utils.branchUrl(options)))
        .then(utils.setVersion(options.nextVersion))
        .then(commit());
    });

  function mergeBranchOptions(providedBranchOptions) {

    return q.spread([utils.loadPackageJson(), svn.info()], defaultBranchOptions)
      .then(mergeWithProvided);

    function defaultBranchOptions(packageJson, repoInfo) {
      return {
        trunk: 'trunk',
        branches: 'branches',
        tags: 'tags',
        branchName: semver.major(packageJson.version) + '.' + semver.minor(packageJson.version),
        branchVersion: packageJson.version,
        nextVersion: semver.inc(packageJson.version, 'minor'),
        repoRoot: repoInfo['repositoryroot'],
        repoUrl: repoInfo.url
      };
    }

    function mergeWithProvided(branchOptions) {
      return _.extend(branchOptions, providedBranchOptions);
    }
  }

  function copy(source, target) {
    return function () {
      return svn.copy(source, target, 'svn-release: branch');
    };
  }

  function commit() {
    return function () {
      return svn.commit([], 'svn-release: branch');
    };
  }
}

function noLocalChanges() {
  return svn.status().then(utils.failOnChanges);
}<|endoftext|>


<commit_before>(function() {
  'use strict';

  var http = require('http');
  var https = require('https');
  var urlparse = require('url').parse;

  function EventTarget() {
    this._eventListeners = {};
  }

  (function(proto) {
    proto.addEventListener = function addEventListener(type, listener, useCapture) {
      this['on' + type] = listener;
    };

    proto.dispatchEvent = function dispatchEvent(event) {
      var _listener = this['on' + event.type];
      if (typeof(_listener) === 'function') {
        _listener.call(this, event);
      }
    };

    proto.removeEventListener = function removeEventListener(type, listener, useCapture) {
      // todo
    };
  })(EventTarget.prototype);

  function XMLHttpRequestEventTarget() {
    EventTarget.call(this);
  }
  XMLHttpRequestEventTarget.prototype = Object.create(EventTarget.prototype);

  (function(proto) {
    // Event handler
    (function(types) {
      types.forEach(function(type) {
        Object.defineProperty(proto, 'on' + type, {
          get: function() {
            var _listener = this._eventListeners[type];
            if (typeof(_listener) !== 'function') {
              return null;
            }
            return _listener;
          },
          set: function(listener) {
            if (typeof(listener) !== 'function') {
              delete this._eventListeners[type];
              return listener;
            }
            return this._eventListeners[type] = listener;
          },
          enumerble: false,
          configurable: false
        });
      });
    })([
      'loadstart',
      'progress',
      'abort',
      'error', // todo
      'load',
      'timeout', // todo
      'loadend'
    ]);
  })(XMLHttpRequestEventTarget.prototype);

  function XMLHttpRequestUpload() {
    if (!(this instanceof XMLHttpRequestUpload)) {
      throw new TypeError('DOM object constructor cannot be called as a function.');
    }
    XMLHttpRequestEventTarget.call(this);
  }
  XMLHttpRequestUpload.prototype = Object.create(XMLHttpRequestEventTarget.prototype);

  var XMLHttpRequestResponseType = [
    '',
    'arraybuffer',
    'blob',
    'document',
    'json',
    'text'
  ];

  function XMLHttpRequest() {
    if (!(this instanceof XMLHttpRequest)) {
      throw new TypeError('DOM object constructor cannot be called as a function.');
    }
    XMLHttpRequestEventTarget.call(this);

    // Private properties
    this._eventListeners = {};
    this._responseType = '';
    this._responseBuffer = null;
    this._async = true;
    this._client = null;
    this._options = {};
    this._requestHeaders = {};
    this._responseHeaders = {};

    // States
    this.readyState = XMLHttpRequest.UNSENT;

    // Request
    this.timeout = null; // todo
    this.withCredentials = false; // todo
    this.upload = new XMLHttpRequestUpload();

    // Response
    this.status = 0;
    this.statusText = '';
    this.responseType = ''; // todo
    this.response = ''; // todo
    this.responseText = '';
    this.responseXML = null; // not support
  }
  XMLHttpRequest.prototype = Object.create(XMLHttpRequestEventTarget.prototype);

  (function(proto) {
    // Event handler
    Object.defineProperty(proto, 'onreadystatechange', {
      get: function() {
        var _listener = this._eventListeners['readystatechange'];
        if (typeof(_listener) !== 'function') {
          return null;
        }
        return _listener;
      },
      set: function(listener) {
        if (typeof(listener) !== 'function') {
          this._eventListener['readystatechange'] = null;
          return listener;
        }
        return this._eventListeners['readystatechange'] = listener;
      },
      enumerble: false,
      configurable: false
    });

    // States
    (function(states) {
      var _objs = [XMLHttpRequest, proto];
      Object.keys(states).forEach(function(prop) {
        var _value = states[prop];
        _objs.forEach(function(_obj) {
          Object.defineProperty(_obj, prop, {
            value: _value,
            writable: false,
            enumerable: true,
            configurable: false
          });
        });
      });
    })({
      UNSENT: 0,
      OPENED: 1,
      HEADERS_RECEIVED: 2,
      LOADING: 3,
      DONE: 4
    });

    // Request
    proto.open = function open(method, url, async, user, password) {
      if (typeof(method) === 'undefined' || typeof(url) === 'undefined') {
        throw new TypeError('Not enought arguments');
      }
      this._options.method = method;
      (function(_parsedUrlObj) {
        this._options.protocol = (typeof(_parsedUrlObj.protocol) !== 'undefined') ? _parsedUrlObj.protocol : 'http:';
        this._options.agent = ((this._options.protocol === 'https:') ? https : http).globalAgent;
        this._options.host = (typeof(_parsedUrlObj.hostname) !== 'undefined') ? _parsedUrlObj.hostname : 'localhost';
        this._options.port = (typeof(_parsedUrlObj.port) !== 'undefined') ? _parsedUrlObj.port : ((this._options.protocol === 'https:') ? 443 : 80);
        this._options.path = (typeof(_parsedUrlObj.path) !== 'undefined') ? _parsedUrlObj.path : '/';
      }).call(this, urlparse(url));
      this._async = (typeof(async) !== 'undifined') ? async : true;
      if (typeof(user) === 'string' && typeof(password) === 'string') {
        this._options.auth = [user, password].join(':');
      }
      _readyStateChange.call(this, XMLHttpRequest.OPENED);
    };

    proto.setRequestHeader = function setRequestHeader(header, value) {
      if (this.readyState === XMLHttpRequest.UNSENT) {
        throw Error(''); // todo
      }
      this._requestHeaders[header] = value;
    };

    proto.send = function send(body) {
      if (this.readyState !== XMLHttpRequest.OPENED) {
        throw new Error(); // todo
      }
      this._client = new http.ClientRequest(this._options);
      this._client.on('response', _setDispatchProgressEvents(this.dispatchEvent.bind(this)));
      this._client.on('response', _receiveResponse.bind(this));
      this._client.on('socket', _setDispatchProgressEvents(this.upload.dispatchEvent.bind(this.upload)));
      Object.keys(this._requestHeaders).forEach(function(key) {
        this._client.setHeader(key, this._requestHeaders[key]);
      }, this);
      _readyStateChange.call(this, XMLHttpRequest.HEADERS_RECEIVED);
      if (typeof(body) !== 'undefined' && body !== null) {
        this._client.write(body);
      }
      this._client.end();
    };

    proto.abort = function abort() {
      if (!(this._client instanceof http.ClientRequest)) {
        return;
      }
      this._client.abort();
      this.dispatchEvent({type: 'abort'});
      this.upload.dispatchEvent({type: 'abort'});
    };

    // Response
    proto.getResponseHeader = function getResponseHeader(header) {
      if (this.readyState === XMLHttpRequest.UNSENT || this.readyState === XMLHttpRequest.OPENED) {
        throw new Error(''); // todo;
      }
      var value = this._responseHeaders[header.toLowerCase()];
      return (typeof(value) !== 'undefined') ? value : null;
    };

    proto.getAllResponseHeaders = function getAllResponseHeaders() {
      if (this.readyState === XMLHttpRequest.UNSENT || this.readyState === XMLHttpRequest.OPENED) {
        throw new Error(''); // todo
      }
      return Object.keys(this._responseHeaders).map(function(key) {
        return [key, this._responseHeaders[key]].join(': ');
      }, this).join('\n');
    };

    proto.overrideMimeType = function overrideMimeType(mime) {
      // todo
    };

    Object.defineProperties(proto, {
      'responseType': (function(responseTypes) {
        return {
          get: function() {
            var responseType = this._responseType;
            if (responseTypes.indexOf(responseType) < 0) {
              return '';
            }
            return this._responseType;
          },
          set: function(value) {
            var responseType = this._responseType;
            if (responseTypes.indexOf(responseType) < 0) {
              throw new Error(''); // todo
            }
            return this._responseType = value;
          },
          enumerable: true,
          configurable: false
        };
      })(XMLHttpRequestResponseType),

      'response': {
        get: function() {
          if (!(this._responseBuffer instanceof Buffer)) {
            return '';
          }
          switch (this.responseType) {
            case '':
              return this.responseText;
            case 'arraybuffer':
            case 'blob':
              return (new Uint8Array(this._responseBuffer)).buffer;
            case 'document':
              return null; // todo
            case 'json':
              return JSON.parse(this.responseText);
            case 'text':
              return this.responseText;
            default:
              return '';
          }
        },
        set: function(value) {
          return value;
        },
        enumerable: true,
        configurable: false
      },

      'responseText': {
        get: function() {
          if (!(this._responseBuffer instanceof Buffer)) {
            return '';
          }
          return this._responseBuffer.toString();
        },
        set: function(value) {
          return value;
        },
        enumerable: true,
        configurable: false
      },

      'responseXML': {
        value: null, // todo
        writable: false,
        enumerable: true,
        configurable: false
      }
    });

    // private methods
    var _readyStateChange = function _readyStateChange(readyState) {
      this.readyState = readyState;
      this.dispatchEvent({type: 'readystatechange'});
    };

    var _setDispatchProgressEvents = function _setDispatchProgressEvents(_dispatchEvent) {
      return function(stream) {
        _dispatchEvent({type: 'loadstart'});
        stream.on('data', function() {
          _dispatchEvent({type: 'progress'});
        });
        stream.on('end', function() {
          _dispatchEvent({type: 'load'});
          _dispatchEvent({type: 'loadend'});
        });
      };
    };

    var _receiveResponse = function _receiveResponse(response) {
      var contentLength = '0';
      var bufferLength = 0;
      var byteOffset = 0;
      this.status = response.statusCode;
      this.statusText = http.STATUS_CODES[this.status];
      this._responseHeaders = response.headers;
      if ((contentLength = response.headers['content-length'])) {
        bufferLength = +contentLength;
      }
      this._responseBuffer = new Buffer(bufferLength);
      _readyStateChange.call(this, XMLHttpRequest.LOADING);
      response.addListener('data', function(chunk) {
        var buffer;
        if (bufferLength === 0) {
          buffer = this._responseBuffer;
          this._responseBuffer = new Buffer(buffer.length + chunk.length);
          buffer.copy(this._responseBuffer);
        }
        chunk.copy(this._responseBuffer, byteOffset);
        byteOffset += chunk.length;
      }.bind(this));
      response.addListener('end', function() {
        _readyStateChange.call(this, XMLHttpRequest.DONE);
        this._responseBuffer = null;
        this._client = null;
        this._options = {};
      }.bind(this));
    };
  })(XMLHttpRequest.prototype);

  function FormData() {
    if (!(this instanceof FormData)) {
      throw new TypeError('DOM object constructor cannot be called as a function.');
    }
  }

  (function(proto) {
    proto.append = function append(name, value, filename) {
      // todo
    };
  })(FormData.prototype);

  XMLHttpRequest.XMLHttpRequestUpload = XMLHttpRequestUpload;
  XMLHttpRequest.XMLHttpRequest = XMLHttpRequest;
  XMLHttpRequest.FormData = FormData;
  module.exports = XMLHttpRequest;
})();
<commit_msg>Fix bug<commit_after>(function() {
  'use strict';

  var http = require('http');
  var https = require('https');
  var urlparse = require('url').parse;

  function EventTarget() {
    this._eventListeners = {};
  }

  (function(proto) {
    proto.addEventListener = function addEventListener(type, listener, useCapture) {
      this['on' + type] = listener;
    };

    proto.dispatchEvent = function dispatchEvent(event) {
      var _listener = this['on' + event.type];
      if (typeof(_listener) === 'function') {
        _listener.call(this, event);
      }
    };

    proto.removeEventListener = function removeEventListener(type, listener, useCapture) {
      // todo
    };
  })(EventTarget.prototype);

  function XMLHttpRequestEventTarget() {
    EventTarget.call(this);
  }
  XMLHttpRequestEventTarget.prototype = Object.create(EventTarget.prototype);

  (function(proto) {
    // Event handler
    (function(types) {
      types.forEach(function(type) {
        Object.defineProperty(proto, 'on' + type, {
          get: function() {
            var _listener = this._eventListeners[type];
            if (typeof(_listener) !== 'function') {
              return null;
            }
            return _listener;
          },
          set: function(listener) {
            if (typeof(listener) !== 'function') {
              delete this._eventListeners[type];
              return listener;
            }
            return this._eventListeners[type] = listener;
          },
          enumerble: false,
          configurable: false
        });
      });
    })([
      'loadstart',
      'progress',
      'abort',
      'error', // todo
      'load',
      'timeout', // todo
      'loadend'
    ]);
  })(XMLHttpRequestEventTarget.prototype);

  function XMLHttpRequestUpload() {
    if (!(this instanceof XMLHttpRequestUpload)) {
      throw new TypeError('DOM object constructor cannot be called as a function.');
    }
    XMLHttpRequestEventTarget.call(this);
  }
  XMLHttpRequestUpload.prototype = Object.create(XMLHttpRequestEventTarget.prototype);

  var XMLHttpRequestResponseType = [
    '',
    'arraybuffer',
    'blob',
    'document',
    'json',
    'text'
  ];

  function XMLHttpRequest() {
    if (!(this instanceof XMLHttpRequest)) {
      throw new TypeError('DOM object constructor cannot be called as a function.');
    }
    XMLHttpRequestEventTarget.call(this);

    // Private properties
    this._eventListeners = {};
    this._responseType = '';
    this._responseBuffer = null;
    this._async = true;
    this._client = null;
    this._options = {};
    this._requestHeaders = {};
    this._responseHeaders = {};

    // States
    this.readyState = XMLHttpRequest.UNSENT;

    // Request
    this.timeout = null; // todo
    this.withCredentials = false; // todo
    this.upload = new XMLHttpRequestUpload();

    // Response
    this.status = 0;
    this.statusText = '';
    this.responseType = ''; // todo
    this.response = ''; // todo
    this.responseText = '';
    this.responseXML = null; // not support
  }
  XMLHttpRequest.prototype = Object.create(XMLHttpRequestEventTarget.prototype);

  (function(proto) {
    // Event handler
    Object.defineProperty(proto, 'onreadystatechange', {
      get: function() {
        var _listener = this._eventListeners['readystatechange'];
        if (typeof(_listener) !== 'function') {
          return null;
        }
        return _listener;
      },
      set: function(listener) {
        if (typeof(listener) !== 'function') {
          this._eventListener['readystatechange'] = null;
          return listener;
        }
        return this._eventListeners['readystatechange'] = listener;
      },
      enumerble: false,
      configurable: false
    });

    // States
    (function(states) {
      var _objs = [XMLHttpRequest, proto];
      Object.keys(states).forEach(function(prop) {
        var _value = states[prop];
        _objs.forEach(function(_obj) {
          Object.defineProperty(_obj, prop, {
            value: _value,
            writable: false,
            enumerable: true,
            configurable: false
          });
        });
      });
    })({
      UNSENT: 0,
      OPENED: 1,
      HEADERS_RECEIVED: 2,
      LOADING: 3,
      DONE: 4
    });

    // Request
    proto.open = function open(method, url, async, user, password) {
      if (typeof(method) === 'undefined' || typeof(url) === 'undefined') {
        throw new TypeError('Not enought arguments');
      }
      this._options.method = method;
      (function(_parsedUrlObj) {
        this._options.protocol = (typeof(_parsedUrlObj.protocol) !== 'undefined') ? _parsedUrlObj.protocol : 'http:';
        this._options.agent = ((this._options.protocol === 'https:') ? https : http).globalAgent;
        this._options.host = (typeof(_parsedUrlObj.hostname) !== 'undefined') ? _parsedUrlObj.hostname : 'localhost';
        this._options.port = (typeof(_parsedUrlObj.port) !== 'undefined') ? _parsedUrlObj.port : ((this._options.protocol === 'https:') ? 443 : 80);
        this._options.path = (typeof(_parsedUrlObj.path) !== 'undefined') ? _parsedUrlObj.path : '/';
      }).call(this, urlparse(url));
      this._async = (typeof(async) !== 'undifined') ? async : true;
      if (typeof(user) === 'string' && typeof(password) === 'string') {
        this._options.auth = [user, password].join(':');
      }
      _readyStateChange.call(this, XMLHttpRequest.OPENED);
    };

    proto.setRequestHeader = function setRequestHeader(header, value) {
      if (this.readyState === XMLHttpRequest.UNSENT) {
        throw Error(''); // todo
      }
      this._requestHeaders[header] = value;
    };

    proto.send = function send(body) {
      if (this.readyState !== XMLHttpRequest.OPENED) {
        throw new Error(); // todo
      }
      this._client = new http.ClientRequest(this._options);
      this._client.on('response', _setDispatchProgressEvents(this.dispatchEvent.bind(this)));
      this._client.on('response', _receiveResponse.bind(this));
      this._client.on('socket', _setDispatchProgressEvents(this.upload.dispatchEvent.bind(this.upload)));
      Object.keys(this._requestHeaders).forEach(function(key) {
        this._client.setHeader(key, this._requestHeaders[key]);
      }, this);
      _readyStateChange.call(this, XMLHttpRequest.HEADERS_RECEIVED);
      if (typeof(body) !== 'undefined' && body !== null) {
        this._client.write(body);
      }
      this._client.end();
    };

    proto.abort = function abort() {
      if (!(this._client instanceof http.ClientRequest)) {
        return;
      }
      this._client.abort();
      this.dispatchEvent({type: 'abort'});
      this.upload.dispatchEvent({type: 'abort'});
    };

    // Response
    proto.getResponseHeader = function getResponseHeader(header) {
      if (this.readyState === XMLHttpRequest.UNSENT || this.readyState === XMLHttpRequest.OPENED) {
        throw new Error(''); // todo;
      }
      var value = this._responseHeaders[header.toLowerCase()];
      return (typeof(value) !== 'undefined') ? value : null;
    };

    proto.getAllResponseHeaders = function getAllResponseHeaders() {
      if (this.readyState === XMLHttpRequest.UNSENT || this.readyState === XMLHttpRequest.OPENED) {
        throw new Error(''); // todo
      }
      return Object.keys(this._responseHeaders).map(function(key) {
        return [key, this._responseHeaders[key]].join(': ');
      }, this).join('\n');
    };

    proto.overrideMimeType = function overrideMimeType(mime) {
      // todo
    };

    Object.defineProperties(proto, {
      'responseType': (function(responseTypes) {
        return {
          get: function() {
            var responseType = this._responseType;
            if (responseTypes.indexOf(responseType) < 0) {
              return '';
            }
            return this._responseType;
          },
          set: function(value) {
            var responseType = this._responseType;
            if (responseTypes.indexOf(responseType) < 0) {
              throw new Error(''); // todo
            }
            return this._responseType = value;
          },
          enumerable: true,
          configurable: false
        };
      })(XMLHttpRequestResponseType),

      'response': {
        get: function() {
          if (!(this._responseBuffer instanceof Buffer)) {
            return '';
          }
          switch (this.responseType) {
            case '':
              return this.responseText;
            case 'arraybuffer':
            case 'blob':
              return (new Uint8Array(this._responseBuffer)).buffer;
            case 'document':
              return null; // todo
            case 'json':
              return JSON.parse(this.responseText);
            case 'text':
              return this.responseText;
            default:
              return '';
          }
        },
        set: function(value) {
          return value;
        },
        enumerable: true,
        configurable: false
      },

      'responseText': {
        get: function() {
          if (!(this._responseBuffer instanceof Buffer)) {
            return '';
          }
          return this._responseBuffer.toString();
        },
        set: function(value) {
          return value;
        },
        enumerable: true,
        configurable: false
      },

      'responseXML': {
        value: null, // todo
        writable: false,
        enumerable: true,
        configurable: false
      }
    });

    // private methods
    var _readyStateChange = function _readyStateChange(readyState) {
      this.readyState = readyState;
      this.dispatchEvent({type: 'readystatechange'});
    };

    var _setDispatchProgressEvents = function _setDispatchProgressEvents(_dispatchEvent) {
      return function(stream) {
        _dispatchEvent({type: 'loadstart'});
        stream.on('data', function() {
          _dispatchEvent({type: 'progress'});
        });
        stream.on('end', function() {
          _dispatchEvent({type: 'load'});
          _dispatchEvent({type: 'loadend'});
        });
      };
    };

    var _receiveResponse = function _receiveResponse(response) {
      var contentLength = '0';
      var bufferLength = 0;
      var byteOffset = 0;
      this.status = response.statusCode;
      this.statusText = http.STATUS_CODES[this.status];
      this._responseHeaders = response.headers;
      if ((contentLength = response.headers['content-length'])) {
        bufferLength = +contentLength;
      }
      this._responseBuffer = new Buffer(bufferLength);
      _readyStateChange.call(this, XMLHttpRequest.LOADING);
      response.addListener('data', function(chunk) {
        var buffer;
        if (bufferLength === 0) {
          buffer = this._responseBuffer;
          this._responseBuffer = new Buffer(buffer.length + chunk.length);
          buffer.copy(this._responseBuffer);
        }
        chunk.copy(this._responseBuffer, byteOffset);
        byteOffset += chunk.length;
      }.bind(this));
      response.addListener('end', function() {
        _readyStateChange.call(this, XMLHttpRequest.DONE);
        this._client = null;
        this._options = {};
      }.bind(this));
    };
  })(XMLHttpRequest.prototype);

  function FormData() {
    if (!(this instanceof FormData)) {
      throw new TypeError('DOM object constructor cannot be called as a function.');
    }
  }

  (function(proto) {
    proto.append = function append(name, value, filename) {
      // todo
    };
  })(FormData.prototype);

  XMLHttpRequest.XMLHttpRequestUpload = XMLHttpRequestUpload;
  XMLHttpRequest.XMLHttpRequest = XMLHttpRequest;
  XMLHttpRequest.FormData = FormData;
  module.exports = XMLHttpRequest;
})();
<|endoftext|>


<commit_before>/**
	_moon.SimplePicker_ is a control that solicits a choice from the user by
	cycling through a list of options. The picker's child components, typically
	simple enyo.Control objects with text content,
	become the options for the picker.

		{kind:"moon.SimplePicker", onChange:"changed", selectedIndex:1, components: [
			{content:"San Francisco"},
			{content:"Boston"},
			{content:"Tokyo"}
		]}

	The picker may be changed programmatically by calling _previous()_ or
	_next()_, or by modifying the _selectedIndex_ published property by calling
	_set("selectedIndex", <value>)_.

	The _onChange_ event is fired when the selected item changes, and contains the
	following	properties:

		{
			selected: [object Object],	// Reference to selected item
			content: "San Francisco",	// Content of selected item
			index: 1					// Index of selected item
		}

	The picker options may be modified programmatically in the standard manner, by
	calling	_createComponent().render()_ or _destroy()_.

		// Add new items to picker
		this.$.picker.createComponent({"New York"}).render();
		this.$.picker.createComponent({"London"}).render();

		// Remove currently selected item from picker
		this.$.picker.getSelected().destroy();
*/
enyo.kind({
	name: "moon.SimplePicker",
	classes: "moon-simple-picker",
	mixins: ["moon.MarqueeSupport"],
	events: {
		/**
			Fires when the currently selected item changes.

			_inEvent.selected_ contains a reference to the currently selected item.

			_inEvent.content_ contains the content of the currently selected item.

			_inEvent.index_ contains the index of the currently selected item.
		*/
		onChange:""
	},
	published: {
		//* Reference to currently selected item, if any
		selected: "",
		//* Index of currently selected item, if any
		selectedIndex: 0,
		//* When true, picker transitions animate left/right
		animate: true,
		//* When true, button is shown as disabled and does not generate tap events
		disabled: false,
		//* When true, picker will wrap around from last item to first
		wrap: false,
		//* By default, SimplePicker is an inline-block element; Setting `block: true` makes it a block element
		block: false
	},
	defaultKind:"moon.MarqueeText",
	//* @protected
	handlers: {
		onSpotlightFocused: "scrollIntoView"
	},
	components: [
		{name: "buttonLeft",  kind: "enyo.Button", classes: "moon-simple-picker-button left", spotlight: true, defaultSpotlightRight: "buttonRight", ontap: "left"},
		{kind: "enyo.Control", name: "clientWrapper", classes:"moon-simple-picker-client-wrapper", components: [
			{kind: "enyo.Control", name: "client", classes: "moon-simple-picker-client"}
		]},
		{name: "buttonRight", kind: "enyo.Button", classes: "moon-simple-picker-button right", spotlight: true, defaultSpotlightLeft: "buttonLeft", ontap: "right"}
	],
	create: function() {
		this.inherited(arguments);
		this.animateChanged();
		this.initializeActiveItem();
		this.disabledChanged();
		this.selectedIndexChanged();
		this.updateMarqueeDisable();
		this.blockChanged();
	},
	scrollIntoView: function() {
		this.bubble("onRequestScrollIntoView");
	},
	fireChangedEvent: function() {
		if (!this.generated) {
			return;
		}

		this.doChange({
			selected:   this.selected,
			content:    this.selected && this.selected.content,
			index:      this.selected && this.selectedIndex
		});
	},
	blockChanged: function() {
		this.addRemoveClass("block", this.block);
	},
	//* Show/hide prev/next buttons based on current index
	showHideNavButtons: function() {
		var index = this.getSelectedIndex(),
			maxIndex = this.getClientControls().length - 1;
		var prevButton = this.rtl ? this.$.buttonRight : this.$.buttonLeft;
		var nextButton = this.rtl ? this.$.buttonLeft : this.$.buttonRight;

		if (this.disabled) {
			this.hideNavButton(prevButton);
			this.hideNavButton(nextButton);
		// Always show buttons if _this.wrap_ is _true_
		} else if (this.wrap) {
			this.showNavButton(prevButton);
			this.showNavButton(nextButton);
		// If we have one or less options, always show no buttons
		} else if (maxIndex <= 0) {
			this.hideNavButton(prevButton);
			this.hideNavButton(nextButton);
		// If we are on the first option, hide the left button
		} else if (index <= 0) {
			this.hideNavButton(prevButton);
			this.showNavButton(nextButton);
		// If we are on the last item, hide the right button
		} else if (index >= maxIndex) {
			this.showNavButton(prevButton);
			this.hideNavButton(nextButton);
		// Otherwise show both buttons
		} else {
			this.showNavButton(prevButton);
			this.showNavButton(nextButton);
		}
	},
	addControl: function(inControl) {
		this.inherited(arguments);
		var addedIdx = this.getClientControls().indexOf(inControl);
		var selectedIdx = this.selectedIndex;
		if (this.generated) {
			if ((selectedIdx < 0) || (addedIdx < selectedIdx)) {
				this.setSelectedIndex(selectedIdx + 1);
			} else if (selectedIdx == addedIdx) {
				// Force change handler, since the currently selected item actually changed
				this.selectedIndexChanged();
			}
			this.showHideNavButtons();
		}
	},
	removeControl: function(inControl) {
		var removedIdx = this.getClientControls().indexOf(inControl);
		var selectedIdx = this.selectedIndex;
		var wasLast = (removedIdx == this.getClientControls().length-1);

		this.inherited(arguments);

		// If removedIdx is -1, that means that the Control being removed is
		// not one of our picker items, so we don't need to update our state.
		// Probably, we're being torn down.
		if (removedIdx !== -1) {
			if ((removedIdx < selectedIdx) || ((selectedIdx == removedIdx) && wasLast)) {
				this.setSelectedIndex(selectedIdx - 1);
			} else if (selectedIdx == removedIdx) {
				// Force change handler, since the currently selected item actually changed
				this.selectedIndexChanged();
			}
			this.showHideNavButtons();
		}
	},
	//* Hide _inControl_ and disable spotlight functionality
	hideNavButton: function(inControl) {
		inControl.addClass("hidden");
		enyo.Spotlight.unspot();
		inControl.spotlight = false;
	},
	//* Show _inControl_ and enable spotlight functionality
	showNavButton: function(inControl) {
		inControl.removeClass("hidden");
		inControl.spotlight = true;
	},
	disabledChanged: function() {
		this.$.client.addRemoveClass("disabled", this.disabled);
		if (this.generated) {
			this.showHideNavButtons();
		}
	},
	animateChanged: function() {
		this.$.client.addRemoveClass("animated", this.animate);
	},
	selectedChanged: function() {
		var idx = this.getClientControls().indexOf(this.selected);
		if (idx >= 0) {
			this.setSelectedIndex(idx);
		}
	},
	/*
		When the picker is initialized, looks for any items with an _active:true_
		flag; if one is found, it is set as the currently selected item. This is
		done without triggering an _onChange_ event, as it happens during
		initialization.
	*/
	initializeActiveItem: function() {
		var controls = this.getClientControls();
		for(var i=0;i<controls.length;i++) {
			if(controls[i].active) {
				this.selectedIndex = i;
				this.selected = controls[i];
				return;
			}
		}
	},
	selectedIndexChanged: function() {
		enyo.dom.transform(this.$.client, {translateX: (this.selectedIndex * 100 * (this.rtl ? 1 : -1)) + "%"});
		if (this.selectedIndex !== null) {
			this.updateMarqueeDisable();
		}
		this.setSelected(this.getClientControls()[this.selectedIndex]);
		this.fireChangedEvent();
		this.showHideNavButtons();
	},
	updateMarqueeDisable: function() {
		for (var c$=this.getClientControls(), i=0; i<c$.length; i++) {
			if (i == this.selectedIndex) {
				c$[i].disabled = false;
			} else {
				c$[i].disabled = true;
			}
		}
	},
	left: function() {
		if (this.rtl) {
			this.next();
		} else {
			this.previous();
		}
	},
	right: function() {
		if (this.rtl) {
			this.previous();
		} else {
			this.next();
		}
	},
	//* @public
	//* Cycles the selected item to the one before the currently selected item.
	previous: function() {
		if (!this.disabled) {
			var idx = this.selectedIndex - 1;
			if (idx < 0) {
				idx = this.wrap ? this.getClientControls().length - 1 : 0;
			}
			this.setSelectedIndex(idx);
			this.updateMarqueeDisable();
		}
	},
	//* @public
	//* Cycles the selected item to the one after the currently selected item.
	next: function() {
		if (!this.disabled) {
			var idx = this.selectedIndex + 1;
			if (idx > this.getClientControls().length - 1) {
				idx = this.wrap ? 0 : this.getClientControls().length - 1;
			}
			this.setSelectedIndex(idx);
			this.updateMarqueeDisable();
		}
	}
});
<commit_msg>Avoid firing events and doing selected item fixup as controls are being removed when SimplePicker is in the process of being destroyed (similar to logic in enyo.Panels). DCO-1.1-Signed-Off-By: Kevin Schaaf (kevin.schaaf@lge.com)<commit_after>/**
	_moon.SimplePicker_ is a control that solicits a choice from the user by
	cycling through a list of options. The picker's child components, typically
	simple enyo.Control objects with text content,
	become the options for the picker.

		{kind:"moon.SimplePicker", onChange:"changed", selectedIndex:1, components: [
			{content:"San Francisco"},
			{content:"Boston"},
			{content:"Tokyo"}
		]}

	The picker may be changed programmatically by calling _previous()_ or
	_next()_, or by modifying the _selectedIndex_ published property by calling
	_set("selectedIndex", <value>)_.

	The _onChange_ event is fired when the selected item changes, and contains the
	following	properties:

		{
			selected: [object Object],	// Reference to selected item
			content: "San Francisco",	// Content of selected item
			index: 1					// Index of selected item
		}

	The picker options may be modified programmatically in the standard manner, by
	calling	_createComponent().render()_ or _destroy()_.

		// Add new items to picker
		this.$.picker.createComponent({"New York"}).render();
		this.$.picker.createComponent({"London"}).render();

		// Remove currently selected item from picker
		this.$.picker.getSelected().destroy();
*/
enyo.kind({
	name: "moon.SimplePicker",
	classes: "moon-simple-picker",
	mixins: ["moon.MarqueeSupport"],
	events: {
		/**
			Fires when the currently selected item changes.

			_inEvent.selected_ contains a reference to the currently selected item.

			_inEvent.content_ contains the content of the currently selected item.

			_inEvent.index_ contains the index of the currently selected item.
		*/
		onChange:""
	},
	published: {
		//* Reference to currently selected item, if any
		selected: "",
		//* Index of currently selected item, if any
		selectedIndex: 0,
		//* When true, picker transitions animate left/right
		animate: true,
		//* When true, button is shown as disabled and does not generate tap events
		disabled: false,
		//* When true, picker will wrap around from last item to first
		wrap: false,
		//* By default, SimplePicker is an inline-block element; Setting `block: true` makes it a block element
		block: false
	},
	defaultKind:"moon.MarqueeText",
	//* @protected
	handlers: {
		onSpotlightFocused: "scrollIntoView"
	},
	components: [
		{name: "buttonLeft",  kind: "enyo.Button", classes: "moon-simple-picker-button left", spotlight: true, defaultSpotlightRight: "buttonRight", ontap: "left"},
		{kind: "enyo.Control", name: "clientWrapper", classes:"moon-simple-picker-client-wrapper", components: [
			{kind: "enyo.Control", name: "client", classes: "moon-simple-picker-client"}
		]},
		{name: "buttonRight", kind: "enyo.Button", classes: "moon-simple-picker-button right", spotlight: true, defaultSpotlightLeft: "buttonLeft", ontap: "right"}
	],
	create: function() {
		this.inherited(arguments);
		this.animateChanged();
		this.initializeActiveItem();
		this.disabledChanged();
		this.selectedIndexChanged();
		this.updateMarqueeDisable();
		this.blockChanged();
	},
	scrollIntoView: function() {
		this.bubble("onRequestScrollIntoView");
	},
	fireChangedEvent: function() {
		if (!this.generated) {
			return;
		}

		this.doChange({
			selected:   this.selected,
			content:    this.selected && this.selected.content,
			index:      this.selected && this.selectedIndex
		});
	},
	blockChanged: function() {
		this.addRemoveClass("block", this.block);
	},
	//* Show/hide prev/next buttons based on current index
	showHideNavButtons: function() {
		var index = this.getSelectedIndex(),
			maxIndex = this.getClientControls().length - 1;
		var prevButton = this.rtl ? this.$.buttonRight : this.$.buttonLeft;
		var nextButton = this.rtl ? this.$.buttonLeft : this.$.buttonRight;

		if (this.disabled) {
			this.hideNavButton(prevButton);
			this.hideNavButton(nextButton);
		// Always show buttons if _this.wrap_ is _true_
		} else if (this.wrap) {
			this.showNavButton(prevButton);
			this.showNavButton(nextButton);
		// If we have one or less options, always show no buttons
		} else if (maxIndex <= 0) {
			this.hideNavButton(prevButton);
			this.hideNavButton(nextButton);
		// If we are on the first option, hide the left button
		} else if (index <= 0) {
			this.hideNavButton(prevButton);
			this.showNavButton(nextButton);
		// If we are on the last item, hide the right button
		} else if (index >= maxIndex) {
			this.showNavButton(prevButton);
			this.hideNavButton(nextButton);
		// Otherwise show both buttons
		} else {
			this.showNavButton(prevButton);
			this.showNavButton(nextButton);
		}
	},
	destroy: function() {
		this.destroying = true;
		this.inherited(arguments);
	},
	addControl: function(inControl) {
		this.inherited(arguments);
		var addedIdx = this.getClientControls().indexOf(inControl);
		var selectedIdx = this.selectedIndex;
		if (this.generated) {
			if ((selectedIdx < 0) || (addedIdx < selectedIdx)) {
				this.setSelectedIndex(selectedIdx + 1);
			} else if (selectedIdx == addedIdx) {
				// Force change handler, since the currently selected item actually changed
				this.selectedIndexChanged();
			}
			this.showHideNavButtons();
		}
	},
	removeControl: function(inControl) {
		if (!this.destroying) {
			var removedIdx = this.getClientControls().indexOf(inControl);
			var selectedIdx = this.selectedIndex;
			var wasLast = (removedIdx == this.getClientControls().length-1);

			this.inherited(arguments);

			// If removedIdx is -1, that means that the Control being removed is
			// not one of our picker items, so we don't need to update our state.
			// Probably, we're being torn down.
			if (removedIdx !== -1) {
				if ((removedIdx < selectedIdx) || ((selectedIdx == removedIdx) && wasLast)) {
					this.setSelectedIndex(selectedIdx - 1);
				} else if (selectedIdx == removedIdx) {
					// Force change handler, since the currently selected item actually changed
					this.selectedIndexChanged();
				}
				this.showHideNavButtons();
			}
		}
	},
	//* Hide _inControl_ and disable spotlight functionality
	hideNavButton: function(inControl) {
		inControl.addClass("hidden");
		enyo.Spotlight.unspot();
		inControl.spotlight = false;
	},
	//* Show _inControl_ and enable spotlight functionality
	showNavButton: function(inControl) {
		inControl.removeClass("hidden");
		inControl.spotlight = true;
	},
	disabledChanged: function() {
		this.$.client.addRemoveClass("disabled", this.disabled);
		if (this.generated) {
			this.showHideNavButtons();
		}
	},
	animateChanged: function() {
		this.$.client.addRemoveClass("animated", this.animate);
	},
	selectedChanged: function() {
		var idx = this.getClientControls().indexOf(this.selected);
		if (idx >= 0) {
			this.setSelectedIndex(idx);
		}
	},
	/*
		When the picker is initialized, looks for any items with an _active:true_
		flag; if one is found, it is set as the currently selected item. This is
		done without triggering an _onChange_ event, as it happens during
		initialization.
	*/
	initializeActiveItem: function() {
		var controls = this.getClientControls();
		for(var i=0;i<controls.length;i++) {
			if(controls[i].active) {
				this.selectedIndex = i;
				this.selected = controls[i];
				return;
			}
		}
	},
	selectedIndexChanged: function() {
		enyo.dom.transform(this.$.client, {translateX: (this.selectedIndex * 100 * (this.rtl ? 1 : -1)) + "%"});
		if (this.selectedIndex !== null) {
			this.updateMarqueeDisable();
		}
		this.setSelected(this.getClientControls()[this.selectedIndex]);
		this.fireChangedEvent();
		this.showHideNavButtons();
	},
	updateMarqueeDisable: function() {
		for (var c$=this.getClientControls(), i=0; i<c$.length; i++) {
			if (i == this.selectedIndex) {
				c$[i].disabled = false;
			} else {
				c$[i].disabled = true;
			}
		}
	},
	left: function() {
		if (this.rtl) {
			this.next();
		} else {
			this.previous();
		}
	},
	right: function() {
		if (this.rtl) {
			this.previous();
		} else {
			this.next();
		}
	},
	//* @public
	//* Cycles the selected item to the one before the currently selected item.
	previous: function() {
		if (!this.disabled) {
			var idx = this.selectedIndex - 1;
			if (idx < 0) {
				idx = this.wrap ? this.getClientControls().length - 1 : 0;
			}
			this.setSelectedIndex(idx);
			this.updateMarqueeDisable();
		}
	},
	//* @public
	//* Cycles the selected item to the one after the currently selected item.
	next: function() {
		if (!this.disabled) {
			var idx = this.selectedIndex + 1;
			if (idx > this.getClientControls().length - 1) {
				idx = this.wrap ? 0 : this.getClientControls().length - 1;
			}
			this.setSelectedIndex(idx);
			this.updateMarqueeDisable();
		}
	}
});
<|endoftext|>


<commit_before>/**
* Each Enyo-provided library will annotate this structure with its own
* version info. Why? In general, Enyo and its libraries are versioned
* and released together, but libraries may be versioned separately in
* the future. Also, since libraries are checked out and updated
* individually, a project may be using "mismatched" libraries at any
* given time (e.g., the last stable release of Enyo core, but an
* unreleased checkout from the master branch of `layout`).
*
* Enyo uses semantic versioning. Official releases have version
* numbers	of the form `'X.y.z'`. Prereleases are indicated by a suffix
* of the form `'-pre.N'`, where `N` is incremented for each prerelease.
* Between releases, version numbers include an additional `'-dev'`
* suffix.
*
* @name enyo.version
* @type {Object}
* @property {String} enyo - The current release version string.
* @public
*/
enyo.version = {
	enyo: '2.6.0-pre.1.dev'
};
<commit_msg>Update version string to 2.6.0-pre.2<commit_after>/**
* Each Enyo-provided library will annotate this structure with its own
* version info. Why? In general, Enyo and its libraries are versioned
* and released together, but libraries may be versioned separately in
* the future. Also, since libraries are checked out and updated
* individually, a project may be using "mismatched" libraries at any
* given time (e.g., the last stable release of Enyo core, but an
* unreleased checkout from the master branch of `layout`).
*
* Enyo uses semantic versioning. Official releases have version
* numbers	of the form `'X.y.z'`. Prereleases are indicated by a suffix
* of the form `'-pre.N'`, where `N` is incremented for each prerelease.
* Between releases, version numbers include an additional `'-dev'`
* suffix.
*
* @name enyo.version
* @type {Object}
* @property {String} enyo - The current release version string.
* @public
*/
enyo.version = {
	enyo: '2.6.0-pre.2'
};
<|endoftext|>