<commit_before>"use strict";
var ui = require("./uiutil");
var Cards = require("./Cards");
var etgutil = require("./etgutil");
exports.loaded = false;
function load(preload, postload){
	var singles = ["assets/gold.png", "assets/bg_quest.png", "assets/bg_game.png", "assets/bg_questmap.png"];
	var preLoader = new PIXI.AssetLoader(["assets/esheet.png", "assets/raritysheet.png", "assets/backsheet.png",
		"assets/cardborders.png", "assets/statussheet.png", "assets/statusborders.png", "assets/typesheet.png"].concat(singles));
	var loadingBarGraphic = new PIXI.Graphics();
	preLoader.onProgress = function(e) {
		loadingBarGraphic.clear();
		loadingBarGraphic.beginFill(0xFFFFFF);
		loadingBarGraphic.drawRect(0, 284, 900*(1-this.loadCount/this.assetURLs.length), 32);
		loadingBarGraphic.endFill();
	}
	preLoader.onComplete = function() {
		var ui = require("./uiutil");
		ui.loadSounds("cardClick", "buttonClick", "permPlay", "creaturePlay");
		singles.forEach(function(single){
			exports[single.slice(7, -4)] = PIXI.Texture.fromFrame(single);
		});
		var names = {
			eicons: {name: "esheet", w: 32},
			ricons: {name: "raritysheet", w: 25},
			cardBacks: {name: "backsheet", w: 132},
			cardBorders: {name: "cardborders", w: 128},
			sicons: {name: "statussheet", w: 13},
			ticons: {name: "typesheet", w: 25},
			sborders: {name: "statusborders", w: 64}
		};
		for(var name in names){
			var obj = names[name], ts = [], tex = PIXI.Texture.fromFrame("assets/" + obj.name + ".png");
			for (var x = 0;x < tex.width;x += obj.w) ts.push(new PIXI.Texture(tex, new PIXI.Rectangle(x, 0, obj.w, tex.height)));
			exports[name] = ts;
		}
		exports.ricons[-1] = exports.ricons[5];
		exports.loaded = true;
		postload();
	}
	preload(loadingBarGraphic);
	preLoader.load();
}
var caimgcache = {}, crimgcache = {}, wsimgcache = {}, artcache = {}, artimagecache = {};
function makeArt(card, art, oldrend) {
	var rend = oldrend || new PIXI.RenderTexture(132, 256);
	var template = new PIXI.DisplayObjectContainer();
	template.addChild(new PIXI.Sprite(exports.cardBacks[card.element+(card.upped?13:0)]));
	var rarity = new PIXI.Sprite(exports.ricons[card.rarity]);
	rarity.anchor.set(0, 1);
	rarity.position.set(5, 252);
	template.addChild(rarity);
	if (art) {
		var artspr = new PIXI.Sprite(art);
		artspr.position.set(2, 20);
		if (card.shiny) artspr.filters = [shinyFilter];
		template.addChild(artspr);
	}
	var typemark = new PIXI.Sprite(exports.ticons[card.type]);
	typemark.anchor.set(1, 1);
	typemark.position.set(128, 252);
	template.addChild(typemark);
	var nametag = new PIXI.Text(card.name, { font: "12px Dosis", fill: card.upped ? "black" : "white" });
	nametag.position.set(2, 4);
	template.addChild(nametag);
	if (card.cost) {
		var text = new PIXI.Text(card.cost, { font: "12px Dosis", fill: card.upped ? "black" : "white" });
		text.anchor.x = 1;
		text.position.set(rend.width - 20, 4);
		template.addChild(text);
		if (card.costele) {
			var eleicon = new PIXI.Sprite(exports.eicons[card.costele]);
			eleicon.position.set(rend.width - 1, 10);
			eleicon.anchor.set(1, .5);
			eleicon.scale.set(.5, .5);
			template.addChild(eleicon);
		}
	}
	var infospr = new PIXI.Sprite(ui.getTextImage(card.info(), ui.mkFont(11, card.upped ? "black" : "white"), "", rend.width-4));
	infospr.position.set(2, 150);
	template.addChild(infospr);
	rend.render(template, null, true);
	return rend;
}
function getArtImage(code, cb){
	if (!(code in artimagecache)){
		var redcode = code;
		if (artpool){
			while (!(redcode in artpool) && redcode >= "6qo"){
				redcode = etgutil[redcode >= "g00"?"asShiny":"asUpped"](redcode, false);
			}
			if (!(redcode in artpool)) return cb(artimagecache[code] = undefined);
			else if (redcode in artimagecache) return cb(artimagecache[code] = artimagecache[redcode]);
		}
		var loader = new PIXI.ImageLoader("Cards/" + redcode + ".png");
		loader.addEventListener("loaded", function() {
			return cb(artimagecache[code] = PIXI.Texture.fromFrame("Cards/" + redcode + ".png"));
		});
		loader.load();
	}
	return cb(artimagecache[code]);
}
function getArt(code) {
	if (artcache[code]) return artcache[code];
	else {
		return getArtImage(code, function(art){
			return artcache[code] = makeArt(Cards.Codes[code], art, artcache[code]);
		});
	}
}
function getCardImage(code) {
	if (caimgcache[code]) return caimgcache[code];
	else {
		var card = Cards.Codes[code];
		var rend = new PIXI.RenderTexture(100, 20);
		var graphics = new PIXI.Graphics();
		graphics.lineStyle(1, card && card.shiny ? 0xdaa520 : 0x222222);
		graphics.beginFill(card ? ui.maybeLighten(card) : code == "0" ? 0x887766 : 0x111111);
		graphics.drawRect(0, 0, 99, 19);
		graphics.endFill();
		if (card) {
			var clipwidth = 2;
			if (card.cost) {
				var text = new PIXI.Text(card.cost, { font: "11px Dosis", fill: card.upped ? "black" : "white" });
				text.anchor.x = 1;
				text.position.set(rend.width - 20, 5);
				graphics.addChild(text);
				clipwidth += text.width + 22;
				if (card.costele) {
					var eleicon = new PIXI.Sprite(exports.eicons[card.costele]);
					eleicon.position.set(rend.width - 1, 10);
					eleicon.anchor.set(1, .5);
					eleicon.scale.set(.5, .5);
					graphics.addChild(eleicon);
				}
			}
			var text, loopi = 1;
			do text = new PIXI.Text(--loopi?card.name.slice(0, loopi):card.name, { font: "11px Dosis", fill: card.upped ? "black" : "white" }); while (text.width > rend.width - clipwidth);
			text.position.set(2, 5);
			graphics.addChild(text);
		}
		rend.render(graphics);
		return caimgcache[code] = rend;
	}
}
function getInstImage(code, scale, cache){
	return cache[code] || getArtImage(code, function(art) {
		var card = Cards.Codes[code];
		var rend = new PIXI.RenderTexture(Math.ceil(128 * scale), Math.ceil(164 * scale));
		var border = new PIXI.Sprite(exports.cardBorders[card.element + (card.upped ? 13 : 0)]);
		var graphics = new PIXI.Graphics();
		border.addChild(graphics);
		graphics.beginFill(ui.maybeLighten(card));
		graphics.drawRect(0, 16, 128, 128);
		graphics.endFill();
		if (card.shiny){
			graphics.lineStyle(2, 0xdaa520);
			graphics.moveTo(0, 14);
			graphics.lineTo(128, 14);
			graphics.moveTo(0, 147);
			graphics.lineTo(128, 147);
		}
		if (art) {
			var artspr = new PIXI.Sprite(art);
			artspr.position.set(0, 16);
			if (card.shiny) artspr.filters = [shinyFilter];
			border.addChild(artspr);
		}
		var text = new PIXI.Text(card.name, { font: "16px Dosis", fill: card.upped ? "black" : "white" });
		text.anchor.x = .5;
		text.position.set(64, 144);
		border.addChild(text);
		var mtx = new PIXI.Matrix();
		mtx.scale(scale, scale);
		rend.render(border, mtx);
		return cache[code] = rend;
	});
}
function getCreatureImage(code) {
	return getInstImage(code, .5, crimgcache);
}
function getWeaponShieldImage(code) {
	return getInstImage(code, 5/8, wsimgcache);
}
var artpool;
exports.preloadCardArt = function(art){
	var pool = {};
	for(var i=0; i<art.length; i+=3){
		pool[art.substr(i, 3)] = true;
	}
	artpool = pool;
	(function loadArt(i){
		if (i == art.length) return;
		var code = art.substr(i, 3);
		var img = new Image();
		img.onload = function(){
			this.onload = undefined;
			artimagecache[code] = new PIXI.Texture(new PIXI.BaseTexture(this));
			loadArt(i+3);
		}
		img.src = "Cards/" + code + ".png";
	})(0);
}
if (typeof PIXI !== "undefined"){
	exports.nopic = PIXI.Texture.emptyTexture;
	exports.nopic.width = exports.nopic.height = 0;
	exports.load = load;
	exports.getPermanentImage = exports.getCreatureImage = getCreatureImage;
	exports.getArt = getArt;
	exports.getCardImage = getCardImage;
	exports.getWeaponShieldImage = getWeaponShieldImage;
	var shinyFilter = new PIXI.ColorMatrixFilter();
	shinyFilter.matrix = [
		0,1,0,0,
		0,0,1,0,
		1,0,0,0,
		0,0,0,1,
	];
}<commit_msg>Improve card text rendering to not spam redundant eicon<commit_after>"use strict";
var ui = require("./uiutil");
var Cards = require("./Cards");
var etgutil = require("./etgutil");
exports.loaded = false;
function load(preload, postload){
	var singles = ["assets/gold.png", "assets/bg_quest.png", "assets/bg_game.png", "assets/bg_questmap.png"];
	var preLoader = new PIXI.AssetLoader(["assets/esheet.png", "assets/raritysheet.png", "assets/backsheet.png",
		"assets/cardborders.png", "assets/statussheet.png", "assets/statusborders.png", "assets/typesheet.png"].concat(singles));
	var loadingBarGraphic = new PIXI.Graphics();
	preLoader.onProgress = function(e) {
		loadingBarGraphic.clear();
		loadingBarGraphic.beginFill(0xFFFFFF);
		loadingBarGraphic.drawRect(0, 284, 900*(1-this.loadCount/this.assetURLs.length), 32);
		loadingBarGraphic.endFill();
	}
	preLoader.onComplete = function() {
		var ui = require("./uiutil");
		ui.loadSounds("cardClick", "buttonClick", "permPlay", "creaturePlay");
		singles.forEach(function(single){
			exports[single.slice(7, -4)] = PIXI.Texture.fromFrame(single);
		});
		var names = {
			eicons: {name: "esheet", w: 32},
			ricons: {name: "raritysheet", w: 25},
			cardBacks: {name: "backsheet", w: 132},
			cardBorders: {name: "cardborders", w: 128},
			sicons: {name: "statussheet", w: 13},
			ticons: {name: "typesheet", w: 25},
			sborders: {name: "statusborders", w: 64}
		};
		for(var name in names){
			var obj = names[name], ts = [], tex = PIXI.Texture.fromFrame("assets/" + obj.name + ".png");
			for (var x = 0;x < tex.width;x += obj.w) ts.push(new PIXI.Texture(tex, new PIXI.Rectangle(x, 0, obj.w, tex.height)));
			exports[name] = ts;
		}
		exports.ricons[-1] = exports.ricons[5];
		exports.loaded = true;
		postload();
	}
	preload(loadingBarGraphic);
	preLoader.load();
}
var caimgcache = {}, crimgcache = {}, wsimgcache = {}, artcache = {}, artimagecache = {};
function makeArt(card, art, oldrend) {
	var rend = oldrend || new PIXI.RenderTexture(132, 256);
	var template = new PIXI.DisplayObjectContainer();
	template.addChild(new PIXI.Sprite(exports.cardBacks[card.element+(card.upped?13:0)]));
	var rarity = new PIXI.Sprite(exports.ricons[card.rarity]);
	rarity.anchor.set(0, 1);
	rarity.position.set(5, 252);
	template.addChild(rarity);
	if (art) {
		var artspr = new PIXI.Sprite(art);
		artspr.position.set(2, 20);
		if (card.shiny) artspr.filters = [shinyFilter];
		template.addChild(artspr);
	}
	var typemark = new PIXI.Sprite(exports.ticons[card.type]);
	typemark.anchor.set(1, 1);
	typemark.position.set(128, 252);
	template.addChild(typemark);
	var nametag = new PIXI.Text(card.name, { font: "12px Dosis", fill: card.upped ? "black" : "white" });
	nametag.position.set(2, 4);
	template.addChild(nametag);
	if (card.cost) {
		var text = new PIXI.Text(card.cost, { font: "12px Dosis", fill: card.upped ? "black" : "white" });
		text.anchor.x = 1;
		text.position.set(rend.width-3, 4);
		template.addChild(text);
		if (card.costele != card.element) {
			var eleicon = new PIXI.Sprite(exports.eicons[card.costele]);
			eleicon.position.set(rend.width-text.width-5, 10);
			eleicon.anchor.set(1, .5);
			eleicon.scale.set(.5, .5);
			template.addChild(eleicon);
		}
	}
	var infospr = new PIXI.Sprite(ui.getTextImage(card.info(), ui.mkFont(11, card.upped ? "black" : "white"), "", rend.width-4));
	infospr.position.set(2, 150);
	template.addChild(infospr);
	rend.render(template, null, true);
	return rend;
}
function getArtImage(code, cb){
	if (!(code in artimagecache)){
		var redcode = code;
		if (artpool){
			while (!(redcode in artpool) && redcode >= "6qo"){
				redcode = etgutil[redcode >= "g00"?"asShiny":"asUpped"](redcode, false);
			}
			if (!(redcode in artpool)) return cb(artimagecache[code] = undefined);
			else if (redcode in artimagecache) return cb(artimagecache[code] = artimagecache[redcode]);
		}
		var loader = new PIXI.ImageLoader("Cards/" + redcode + ".png");
		loader.addEventListener("loaded", function() {
			return cb(artimagecache[code] = PIXI.Texture.fromFrame("Cards/" + redcode + ".png"));
		});
		loader.load();
	}
	return cb(artimagecache[code]);
}
function getArt(code) {
	if (artcache[code]) return artcache[code];
	else {
		return getArtImage(code, function(art){
			return artcache[code] = makeArt(Cards.Codes[code], art, artcache[code]);
		});
	}
}
function getCardImage(code) {
	if (caimgcache[code]) return caimgcache[code];
	else {
		var card = Cards.Codes[code];
		var rend = new PIXI.RenderTexture(100, 20);
		var graphics = new PIXI.Graphics();
		graphics.lineStyle(1, card && card.shiny ? 0xdaa520 : 0x222222);
		graphics.beginFill(card ? ui.maybeLighten(card) : code == "0" ? 0x887766 : 0x111111);
		graphics.drawRect(0, 0, 99, 19);
		graphics.endFill();
		if (card) {
			var clipwidth = rend.width-2;
			if (card.cost) {
				var text = new PIXI.Text(card.cost, { font: "11px Dosis", fill: card.upped ? "black" : "white" });
				text.anchor.x = 1;
				text.position.set(rend.width-2, 5);
				graphics.addChild(text);
				clipwidth -= text.width+2;
				if (card.costele != card.element) {
					var eleicon = new PIXI.Sprite(exports.eicons[card.costele]);
					eleicon.position.set(clipwidth, 10);
					eleicon.anchor.set(1, .5);
					eleicon.scale.set(.5, .5);
					graphics.addChild(eleicon);
					clipwidth -= 18;
				}
			}
			var text = new PIXI.Text(card.name, { font: "11px Dosis", fill: card.upped ? "black" : "white" });
			text.position.set(2, 5);
			if (text.width > clipwidth){
				text.mask = new PIXI.Graphics();
				text.mask.beginFill();
				text.mask.drawRect(0, 0, clipwidth, 20);
				text.mask.endFill();
			}
			graphics.addChild(text);
		}
		rend.render(graphics);
		return caimgcache[code] = rend;
	}
}
function getInstImage(code, scale, cache){
	return cache[code] || getArtImage(code, function(art) {
		var card = Cards.Codes[code];
		var rend = new PIXI.RenderTexture(Math.ceil(128 * scale), Math.ceil(164 * scale));
		var border = new PIXI.Sprite(exports.cardBorders[card.element + (card.upped ? 13 : 0)]);
		var graphics = new PIXI.Graphics();
		border.addChild(graphics);
		graphics.beginFill(ui.maybeLighten(card));
		graphics.drawRect(0, 16, 128, 128);
		graphics.endFill();
		if (card.shiny){
			graphics.lineStyle(2, 0xdaa520);
			graphics.moveTo(0, 14);
			graphics.lineTo(128, 14);
			graphics.moveTo(0, 147);
			graphics.lineTo(128, 147);
		}
		if (art) {
			var artspr = new PIXI.Sprite(art);
			artspr.position.set(0, 16);
			if (card.shiny) artspr.filters = [shinyFilter];
			border.addChild(artspr);
		}
		var text = new PIXI.Text(card.name, { font: "16px Dosis", fill: card.upped ? "black" : "white" });
		text.anchor.x = .5;
		text.position.set(64, 144);
		border.addChild(text);
		var mtx = new PIXI.Matrix();
		mtx.scale(scale, scale);
		rend.render(border, mtx);
		return cache[code] = rend;
	});
}
function getCreatureImage(code) {
	return getInstImage(code, .5, crimgcache);
}
function getWeaponShieldImage(code) {
	return getInstImage(code, 5/8, wsimgcache);
}
var artpool;
exports.preloadCardArt = function(art){
	var pool = {};
	for(var i=0; i<art.length; i+=3){
		pool[art.substr(i, 3)] = true;
	}
	artpool = pool;
	(function loadArt(i){
		if (i == art.length) return;
		var code = art.substr(i, 3);
		var img = new Image();
		img.onload = function(){
			this.onload = undefined;
			artimagecache[code] = new PIXI.Texture(new PIXI.BaseTexture(this));
			loadArt(i+3);
		}
		img.src = "Cards/" + code + ".png";
	})(0);
}
if (typeof PIXI !== "undefined"){
	exports.nopic = PIXI.Texture.emptyTexture;
	exports.nopic.width = exports.nopic.height = 0;
	exports.load = load;
	exports.getPermanentImage = exports.getCreatureImage = getCreatureImage;
	exports.getArt = getArt;
	exports.getCardImage = getCardImage;
	exports.getWeaponShieldImage = getWeaponShieldImage;
	var shinyFilter = new PIXI.ColorMatrixFilter();
	shinyFilter.matrix = [
		0,1,0,0,
		0,0,1,0,
		1,0,0,0,
		0,0,0,1,
	];
}<|endoftext|>


<commit_before>define(function(require, exports, module) {
    main.consumes = [
        "Plugin", "scm", "proc", "c9"
    ];
    main.provides = ["scm.git"];
    return main;

    function main(options, imports, register) {
        var Plugin = imports.Plugin;
        var scm = imports.scm;
        var proc = imports.proc;
        var c9 = imports.c9;

        var basename = require("path").basename;
        var dirname = require("path").dirname;

        /***** Initialization *****/

        var plugin = new Plugin("Ajax.org", main.consumes);
        // var emit = plugin.getEmitter();

        var workspaceDir = c9.workspaceDir;

        /***** Methods *****/

        /**
         * Detect whether the path has a git repository
         */
        function detect(path, callback){

        }

        function addAll(callback){
            git("add -u", callback);
        }

        function addFileToStaging(paths, callback){
            git(["add", "-f", "--ignore-errors", "--"].concat(paths), callback);
        }

        function unstageAll(callback){
            git("reset --mixed", callback);
        }

        function unstage(paths, callback){
            git(["reset", "--mixed", "--"].concat(paths), callback);
        }

        function fetch(options, callback){
            var args = ["fetch"];
            if (options.prune) args.push("--prune");
            if (options.branch) args.push(options.branch);
            git(args, callback);
        }

        function pull(options, callback){
            var args = ["pull"];
            if (options.prune) args.push("--prune");
            if (options.branch) args.push(options.branch);
            git(args, callback);
        }

        function push(options, callback){
            var args = ["push"];
            if (options.force) args.push("--force");
            if (options.branch) args.push(options.branch);
            git(args, callback);
        }

        function git(args, cb) {
            if (typeof args == "string")
                args = args.split(/\s+/);

            proc.spawn("git", {
                args: args,
                cwd: workspaceDir
            }, function(e, p) {
                // if (e) console.error(e);

                buffer(p, function(stdout, stderr){
                    // console.log(e, stdout);

                    cb && cb(e, stdout, stderr);
                });
            });
        }

        function buffer(process, callback){
            var stdout = "", stderr = "";
            process.stdout.on("data", function(c){
                stdout += c;
            });
            process.stderr.on("data", function(c){
                stderr += c;
            });
            process.on("exit", function(c){
                callback(stdout, stderr);
            });
        }

        function getStatus(options, cb) {
            var t = Date.now();
            var args = [];
            var hash = options.hash;
            var base = options.base;
            if ((hash || base) && !options.twoWay) {
                args.push("diff", "--name-status", "-b", "-z",
                    "--no-textconv", "--no-ext-diff", "--no-color",
                    "--find-renames"
                );
                if (hash == "staging")
                    hash = "--cached";
                if (base == "staging")
                    base = "--cached";
                if (hash === 0 || base === 0) {
                    args.push(base || hash);
                } else {
                    args.push(base || hash + "^1", hash);
                }
            } else {
                options.twoWay = true;
                args.push("status", "--porcelain", "-b", "-z");
                // if (!ignored.isOpen)
                    args.push("--untracked-files=no");
                if (options.untracked == "all")
                    args.push("--untracked-files=all");
                if (options.ignored)
                    args.push("--ignored");
            }

            args.push("--");

            if (options.path)
                args.push(options.path);

            proc.execFile("git", {
                args: args,
                cwd: workspaceDir
            }, function(err, stdout, stderr) {
                if (err)  {
                    if (/fatal: bad revision/.test(err.message)) {
                        var EMPTY = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";
                        if (options.base != EMPTY) {
                            options.base = EMPTY;
                            return getStatus(options, cb);
                        }
                    }
                    return cb(err);
                }
                // console.log(err, stdout);
                // console.log(t-Date.now(), stdout.length);
                cb(err, stdout);
            });
        }

        function getLog(options, cb) {
            var t = Date.now();

            git(["rev-list", "HEAD", "--count"], function(err, stdout, stderr) {
                if (err) return cb(err);

                console.log(err, stdout);
                console.log(t-Date.now(), stdout.length);

                var args = ["log", "--topo-order", "--date=raw"];
                if (options.boundary !== false) args.push("--boundary");
                if (options.logOptions) args.push.apply(args, options.logOptions);
                // not using %D since it is missing on git 1.9
                args.push('--pretty=format:' + (options.format || "%h %p %d %B %an %ct %ae ").replace(/ /g, "%x00"));
                args.push("--all");
                args.push("HEAD");
                args.push("-n", options.count || 1000);
                if (options.from)
                    args.push("--skip=" + options.from);

                args.push("--");
                if (options.path)
                    args.push(options.path);

                git(args, function(err, stdout, stderr) {
                    if (err) return cb(err);

                    var x = stdout.trim().split("\x00\n");
                    var root = [];
                    var head;
                    // handle empty git history
                    if (x.length == 1 && !x[0]) {
                        x = [];
                    }
                    for (var i = 0; i < x.length; i++) {
                        var line = x[i].split("\x00");
                        var branches = undefined;
                        if (line[2]) {
                            branches = line[2]
                                .replace(/^\s*\(\s*/g, "")
                                .replace(/\s*\)\s*$/g, "");
                            if (/(^|, )HEAD[, ]/.test(branches))
                                head = line[0];
                        }
                        root.push({
                            hash: line[0],
                            parents: line[1],
                            message: line[3],
                            label: line[3].substring(0, line[3].indexOf("\n") + 1 || undefined),
                            branches: branches,
                            authorname: line[4],
                            authoremail: line[5],
                            date: line[6],
                        });
                    }
                    // console.log(err, x);
                    console.log(t-Date.now(), stdout.length);
                    root.unshift({
                        label: "// WIP",
                        hash: 0,
                        parents: head
                    });

                    cb(null, root);
                });

            });
        }

        function getFileAtHash(hash, path, cb) {
            if (!hash) {
                if (path[0] != "/")
                    path = "/" + path;
                return proc.readfile(path, {}, cb);
            }
            if (hash == "staging")
                hash = "";
            if (path[0] == "/")
                path = path.substr(1);
            proc.execFile("git", {
                args: ["show", hash + ":" + path],
                maxBuffer: 1000 * 1024,
                cwd: workspaceDir
            }, function(err, stdout, stderr) {
                cb(err, stdout, stderr);
            });
        }

        function loadDiff(options, callback) {
            var req = {};
            var args = ["diff",  "-U20000", options.oldPath, options.newPath];
            proc.execFile("git", {
                args: args,
                cwd: workspaceDir
            }, function(err, stdout, stderr) {
                if (err) return callback(err);
                if (!stdout) {
                    proc.execFile("git", {
                        args: ["show", options.oldPath],
                        maxBuffer: 1000 * 1024,
                        cwd: workspaceDir
                    }, function(err, stdout, stderr) {
                        if (err) return callback(err);
                        callback(err, {
                            request: req,
                            orig: stdout,
                            edit: stdout
                        });
                    });
                    return;
                }
                callback(null, {
                    request: req,
                    patch: stdout
                });
            });
            return req;
        }

        function addLinesToStaging(patch, cb) {
            proc.spawn("git", {
                args: ["apply", "--cached", "--unidiff-zero", "--whitespace=nowarn", "-"], // "--recount",
                cwd: workspaceDir
            }, function(err, p) {
                if (err) return cb(err);

                process = p.process;
                var stderr = "";
                var stdout = "";
                process.stdout.on("data", function(e) {
                    stdout += e;
                });
                process.stderr.on("data", function(e) {
                    stderr += e;
                });
                process.on("exit", function(e) {
                    cb(e, stdout, stderr);
                });
                process.stdin.write(patch);
                process.stdin.end();
            });
        }

        // TODO reload
        function updateCommitStatus(ammend, callback) {
            var args = ["commit", "--dry-run", "--porcelain", "--branch", "-z"];
            if (ammend)
                args.push("--amend");

            git(args, callback);
        }

        function commit(options, callback) {
            if (!options.message) return;
            var args = ["commit", options.ammend && "--amend", "-m", options.message].filter(Boolean);

            git(args, callback);
        }

        function listAllRefs(cb) {
            var args = ["for-each-ref", "--count=3000", "--sort=*objecttype", "--sort=-committerdate"];
            args.push(
                '--format=%(objectname:short) %(refname) %(upstream:trackshort) %(objecttype) %(subject) %(authorname) %(authoremail) %(committerdate:raw)'.replace(/ /g, "%00")
            );
            git(args, function(err, stdout) {
                if (err) return cb(err);

                var data = stdout.trim().split("\n").map(function(x) {
                    var parts = x.split("\x00");
                    return {
                        hash: parts[0],
                        name: parts[1],
                        upstream: parts[2],
                        type: parts[3],
                        subject: parts[4],
                        authorname: parts[5],
                        authoremail: parts[6],
                        committerdate: parts[7],
                    };
                });
                cb && cb(null, data);
            });
        }

        function getBlame(path, callback){
            proc.spawn("git", {
                args: ["blame", "-wp", "--", basename(path)],
                cwd: c9.workspaceDir + "/" + dirname(path)
            }, function(err, process) {
                if (err) return callback(err);
                buffer(process, function(stdout, stderr) {
                    callback(stderr, stdout);
                });
            });
        }

        /***** Lifecycle *****/

        plugin.on("load", function() {
            if (scm.register)
                scm.register("git", plugin);
        });
        plugin.on("unload", function() {
            if (scm.register)
                scm.unregister("git", plugin);
        });

        /***** Register and define API *****/

        /**
         */
        plugin.freezePublicAPI({
            /**
             *
             */
            detect: detect,

            /**
             *
             */
            addAll: addAll,

            /**
             *
             */
            addFileToStaging: addFileToStaging,

            /**
             *
             */
            unstageAll: unstageAll,

            /**
             *
             */
            unstage: unstage,

            /**
             *
             */
            fetch: fetch,

            /**
             *
             */
            pull: pull,

            /**
             *
             */
            git: git,

            /**
             *
             */
            push: push,

            /**
             *
             */
            buffer: buffer,

            /**
             *
             */
            getStatus: getStatus,

            /**
             *
             */
            getLog: getLog,

            /**
             *
             */
            getFileAtHash: getFileAtHash,

            /**
             *
             */
            loadDiff: loadDiff,

            /**
             *
             */
            addLinesToStaging: addLinesToStaging,

            /**
             *
             */
            updateCommitStatus: updateCommitStatus,

            /**
             *
             */
            commit: commit,

            /**
             *
             */
            listAllRefs: listAllRefs,

            /**
             *
             */
            getBlame: getBlame,

        });

        register(null, {
            "scm.git": plugin
        });
    }
});<commit_msg>code style<commit_after>define(function(require, exports, module) {
    main.consumes = [
        "Plugin", "scm", "proc", "c9"
    ];
    main.provides = ["scm.git"];
    return main;

    function main(options, imports, register) {
        var Plugin = imports.Plugin;
        var scm = imports.scm;
        var proc = imports.proc;
        var c9 = imports.c9;

        var basename = require("path").basename;
        var dirname = require("path").dirname;

        /***** Initialization *****/

        var plugin = new Plugin("Ajax.org", main.consumes);
        // var emit = plugin.getEmitter();

        var workspaceDir = c9.workspaceDir;

        /***** Methods *****/

        /**
         * Detect whether the path has a git repository
         */
        function detect(path, callback){

        }

        function addAll(callback){
            git("add -u", callback);
        }

        function addFileToStaging(paths, callback){
            git(["add", "-f", "--ignore-errors", "--"].concat(paths), callback);
        }

        function unstageAll(callback){
            git("reset --mixed", callback);
        }

        function unstage(paths, callback){
            git(["reset", "--mixed", "--"].concat(paths), callback);
        }

        function fetch(options, callback){
            var args = ["fetch"];
            if (options.prune) args.push("--prune");
            if (options.branch) args.push(options.branch);
            git(args, callback);
        }

        function pull(options, callback){
            var args = ["pull"];
            if (options.prune) args.push("--prune");
            if (options.branch) args.push(options.branch);
            git(args, callback);
        }

        function push(options, callback){
            var args = ["push"];
            if (options.force) args.push("--force");
            if (options.branch) args.push(options.branch);
            git(args, callback);
        }

        function git(args, cb) {
            if (typeof args == "string")
                args = args.split(/\s+/);

            proc.spawn("git", {
                args: args,
                cwd: workspaceDir
            }, function(e, p) {
                // if (e) console.error(e);

                buffer(p, function(stdout, stderr){
                    // console.log(e, stdout);

                    cb && cb(e, stdout, stderr);
                });
            });
        }

        function buffer(process, callback){
            var stdout = "", stderr = "";
            process.stdout.on("data", function(c){
                stdout += c;
            });
            process.stderr.on("data", function(c){
                stderr += c;
            });
            process.on("exit", function(c){
                callback(stdout, stderr);
            });
        }

        function getStatus(options, cb) {
            var t = Date.now();
            var args = [];
            var hash = options.hash;
            var base = options.base;
            if ((hash || base) && !options.twoWay) {
                args.push("diff", "--name-status", "-b", "-z",
                    "--no-textconv", "--no-ext-diff", "--no-color",
                    "--find-renames"
                );
                if (hash == "staging")
                    hash = "--cached";
                if (base == "staging")
                    base = "--cached";
                if (hash === 0 || base === 0) {
                    args.push(base || hash);
                } else {
                    args.push(base || hash + "^1", hash);
                }
            } else {
                options.twoWay = true;
                args.push("status", "--porcelain", "-b", "-z");
                // if (!ignored.isOpen)
                    args.push("--untracked-files=no");
                if (options.untracked == "all")
                    args.push("--untracked-files=all");
                if (options.ignored)
                    args.push("--ignored");
            }

            args.push("--");

            if (options.path)
                args.push(options.path);

            proc.execFile("git", {
                args: args,
                cwd: workspaceDir
            }, function(err, stdout, stderr) {
                if (err)  {
                    if (/fatal: bad revision/.test(err.message)) {
                        var EMPTY = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";
                        if (options.base != EMPTY) {
                            options.base = EMPTY;
                            return getStatus(options, cb);
                        }
                    }
                    return cb(err);
                }
                // console.log(err, stdout);
                // console.log(t-Date.now(), stdout.length);
                cb(err, stdout);
            });
        }

        function getLog(options, cb) {
            var t = Date.now();

            git(["rev-list", "HEAD", "--count"], function(err, stdout, stderr) {
                if (err) return cb(err);

                console.log(err, stdout);
                console.log(t-Date.now(), stdout.length);

                var args = ["log", "--topo-order", "--date=raw"];
                if (options.boundary !== false) args.push("--boundary");
                if (options.logOptions) args.push.apply(args, options.logOptions);
                // not using %D since it is missing on git 1.9
                args.push('--pretty=format:' + (options.format || "%h %p %d %B %an %ct %ae ").replace(/ /g, "%x00"));
                args.push("--all");
                args.push("HEAD");
                args.push("-n", options.count || 1000);
                if (options.from)
                    args.push("--skip=" + options.from);

                args.push("--");
                if (options.path)
                    args.push(options.path);

                git(args, function(err, stdout, stderr) {
                    if (err) return cb(err);

                    var data = stdout.trim().split("\x00\n");
                    var root = [];
                    var head;
                    // handle empty git history
                    if (data.length == 1 && !data[0]) {
                        data = [];
                    }
                    for (var i = 0; i < data.length; i++) {
                        var line = data[i].split("\x00");
                        var branches = line[2];
                        if (branches) {
                            branches = branches
                                .replace(/^\s*\(\s*/g, "")
                                .replace(/\s*\)\s*$/g, "");
                            if (/(^|, )HEAD[, ]/.test(branches))
                                head = line[0];
                        }
                        root.push({
                            hash: line[0],
                            parents: line[1],
                            message: line[3],
                            label: line[3].substring(0, line[3].indexOf("\n") + 1 || undefined),
                            branches: branches || undefined, // set to undefined to not keep in JSON.stringify
                            authorname: line[4],
                            authoremail: line[5],
                            date: line[6],
                        });
                    }
                    // console.log(err, x);
                    console.log(t-Date.now(), stdout.length);
                    root.unshift({
                        label: "// WIP",
                        hash: 0,
                        parents: head
                    });

                    cb(null, root);
                });

            });
        }

        function getFileAtHash(hash, path, cb) {
            if (!hash) {
                if (path[0] != "/")
                    path = "/" + path;
                return proc.readfile(path, {}, cb);
            }
            if (hash == "staging")
                hash = "";
            if (path[0] == "/")
                path = path.substr(1);
            proc.execFile("git", {
                args: ["show", hash + ":" + path],
                maxBuffer: 1000 * 1024,
                cwd: workspaceDir
            }, function(err, stdout, stderr) {
                cb(err, stdout, stderr);
            });
        }

        function loadDiff(options, callback) {
            var req = {};
            var args = ["diff",  "-U20000", options.oldPath, options.newPath];
            proc.execFile("git", {
                args: args,
                cwd: workspaceDir
            }, function(err, stdout, stderr) {
                if (err) return callback(err);
                if (!stdout) {
                    proc.execFile("git", {
                        args: ["show", options.oldPath],
                        maxBuffer: 1000 * 1024,
                        cwd: workspaceDir
                    }, function(err, stdout, stderr) {
                        if (err) return callback(err);
                        callback(err, {
                            request: req,
                            orig: stdout,
                            edit: stdout
                        });
                    });
                    return;
                }
                callback(null, {
                    request: req,
                    patch: stdout
                });
            });
            return req;
        }

        function addLinesToStaging(patch, cb) {
            proc.spawn("git", {
                args: ["apply", "--cached", "--unidiff-zero", "--whitespace=nowarn", "-"], // "--recount",
                cwd: workspaceDir
            }, function(err, p) {
                if (err) return cb(err);

                process = p.process;
                var stderr = "";
                var stdout = "";
                process.stdout.on("data", function(e) {
                    stdout += e;
                });
                process.stderr.on("data", function(e) {
                    stderr += e;
                });
                process.on("exit", function(e) {
                    cb(e, stdout, stderr);
                });
                process.stdin.write(patch);
                process.stdin.end();
            });
        }

        // TODO reload
        function updateCommitStatus(ammend, callback) {
            var args = ["commit", "--dry-run", "--porcelain", "--branch", "-z"];
            if (ammend)
                args.push("--amend");

            git(args, callback);
        }

        function commit(options, callback) {
            if (!options.message) return;
            var args = ["commit", options.ammend && "--amend", "-m", options.message].filter(Boolean);

            git(args, callback);
        }

        function listAllRefs(cb) {
            var args = ["for-each-ref", "--count=3000", "--sort=*objecttype", "--sort=-committerdate"];
            args.push(
                '--format=%(objectname:short) %(refname) %(upstream:trackshort) %(objecttype) %(subject) %(authorname) %(authoremail) %(committerdate:raw)'.replace(/ /g, "%00")
            );
            git(args, function(err, stdout) {
                if (err) return cb(err);

                var data = stdout.trim().split("\n").map(function(x) {
                    var parts = x.split("\x00");
                    return {
                        hash: parts[0],
                        name: parts[1],
                        upstream: parts[2],
                        type: parts[3],
                        subject: parts[4],
                        authorname: parts[5],
                        authoremail: parts[6],
                        committerdate: parts[7],
                    };
                });
                cb && cb(null, data);
            });
        }

        function getBlame(path, callback){
            proc.spawn("git", {
                args: ["blame", "-wp", "--", basename(path)],
                cwd: c9.workspaceDir + "/" + dirname(path)
            }, function(err, process) {
                if (err) return callback(err);
                buffer(process, function(stdout, stderr) {
                    callback(stderr, stdout);
                });
            });
        }

        /***** Lifecycle *****/

        plugin.on("load", function() {
            if (scm.register)
                scm.register("git", plugin);
        });
        plugin.on("unload", function() {
            if (scm.register)
                scm.unregister("git", plugin);
        });

        /***** Register and define API *****/

        /**
         */
        plugin.freezePublicAPI({
            /**
             *
             */
            detect: detect,

            /**
             *
             */
            addAll: addAll,

            /**
             *
             */
            addFileToStaging: addFileToStaging,

            /**
             *
             */
            unstageAll: unstageAll,

            /**
             *
             */
            unstage: unstage,

            /**
             *
             */
            fetch: fetch,

            /**
             *
             */
            pull: pull,

            /**
             *
             */
            git: git,

            /**
             *
             */
            push: push,

            /**
             *
             */
            buffer: buffer,

            /**
             *
             */
            getStatus: getStatus,

            /**
             *
             */
            getLog: getLog,

            /**
             *
             */
            getFileAtHash: getFileAtHash,

            /**
             *
             */
            loadDiff: loadDiff,

            /**
             *
             */
            addLinesToStaging: addLinesToStaging,

            /**
             *
             */
            updateCommitStatus: updateCommitStatus,

            /**
             *
             */
            commit: commit,

            /**
             *
             */
            listAllRefs: listAllRefs,

            /**
             *
             */
            getBlame: getBlame,

        });

        register(null, {
            "scm.git": plugin
        });
    }
});<|endoftext|>


<commit_before>;(function () {

    function Graph () {
        this.elements = [];
        this.scales   = {};
        this.d3Scales = {};
        return this;
    }

    Graph.prototype.rangeForDim = function (dim) {
        if (dim == 1) {
            return [0, this.width];
        } else if (dim == 2) {
            return [this.height, 0];
        } else {
            throw 'Only 2d graphics supported: Bad dim: ' + dim;
        }
    };

    Graph.prototype.render = function (id, data) {
        // Render the graph using the given data into the div with the given id.
        this.svg = d3.select(id).append('svg')
            .attr('width', this.width)
            .attr('height', this.height);

        this.svg.append('rect')
            .attr('x', 0)
            .attr('y', 0)
            .attr('width', this.width)
            .attr('height', this.height)
            .attr('fill', '#dcb')
            .attr('fill-opacity', 1);

        _.each(this.scales, function (s, dim) {
            this.d3Scales[dim] = s.d3Scale.domain([s.min, s.max]).range(this.rangeForDim(dim));
        }, this);

        _.each(this.elements, function (e) { e.render(this, data); }, this);
    };

    Graph.prototype.element = function (e) {
        this.elements.push(e);
        return this;
    };

    Graph.prototype.scale = function (s) {
        this.scales[s.dim] = s;
        return this;
    };

    function PointElement () {
        this.rFn = function (d) { return 5; };
        return this;
    }

    PointElement.prototype.render = function (graph, data) {
        var that = this;
        var circle = graph.svg.selectAll('circle')
            .data(data)
            .enter()
            .append('circle')
            .attr('cx', function (d) { return graph.d3Scales[1](that.xFn(d)) })
            .attr('cy', function (d) { return graph.d3Scales[2](that.yFn(d)) })
            .attr('r', this.rFn);
    };

    function LineElement () {
        return this;
    }

    LineElement.prototype.render = function (graph, data) {
        var e = this;
        function x (d) { return graph.d3Scales[1](e.xFn(d)); }
        function y (d) { return graph.d3Scales[2](e.yFn(d)); }

        var polyline = graph.svg.append('polyline')
            .attr('points', _.map(data, function (d) { return x(d) + ',' + y(d); }, this).join(' '))
            .attr('fill', 'none')
            .attr('stroke', 'black')
            .attr('stroke-width', 2);
    }

    function LinearScale () {
        this.d3Scale = d3.scale.linear();
        return this;
    }

    function LogScale () {
        this.d3Scale = d3.scale.log();
        return this;
    }

    ////////////////////////////////////////////////////////////////////////
    /// API

    function graph() { return build(Graph, arguments); }

    // Elements

    function point () { return build(PointElement, arguments); }

    function line () { return build(LineElement, arguments); }

    // Scales

    function linear () { return build(LinearScale, arguments); }

    function log () { return build(LogScale, arguments); }

   // Set the size of a graph.
    function size(w, h) {
        return function (g) {
            g.width = w;
            g.height = h;
        }
    }

    // Set the dimension of a scale.
    function dim (v) {
        return function (scale) { scale.dim = v; }
    }

    // Set the minimum value of a scale.
    function min (v) {
        return function (scale) { scale.min = v; }
    }

    // Set the maximum value of a scale.
    function max (v) {
        return function (scale) { scale.max = v; }
    }

    function position(expr) {
        var parse = expr.split(/([*\/+])/);
        var operands = [];
        var operators = [];
        _.each(parse, function (e, i) {
            if (i % 2 == 0) {
                operands.push(e);
            } else {
                operators.push(e);
            }
        });

        if (_.any(operators, function (op) { return op !== '*'; })) {
            throw "/ and + not implemented.";
        }

        return function (e) {
            e.xFn = function (d) { return d[operands[0]]; }
            e.yFn = function (d) { return d[operands[1]]; }
        }
    }

    ////////////////////////////////////////////////////////////////////////
    /// Internals

    // This is a kind of goofy way to do things but it enables us to
    // follow the Graphics Production Language pretty closely.
    function build (fn, args) {
        var obj = new fn();
        _.each(args, function (fn) { fn(obj); });
        return obj;
    }

    // Generate some random data.
    var data = (function () {
        var data = [];
        var x = 0;
        var y = 0;
        _.times(20, function () {
            x += Math.random() * 30;
            y += 20 - Math.random() * 30;
            data.push({
                d: x,
                r: y,
            });
        });
        return data;
    }());

    // Generate some random data.
    var semiLogData = (function () {
        var data = [];
        var x = 0;
        var y = 1;
        _.times(20, function () {
            x += Math.random() * 30;
            y *= Math.random() * 5;
            data.push({
                d: x,
                r: y,
            });
        });
        return data;
    }());

    $(document).ready(function() {

        var n = 0;
        function ex () {
            var id = 'example' + n++;
            d3.select('body').append('div').attr('id', id);
            return '#' + id;
        }

        function xMinFn (data) {
            return _.min(data, function (d) { return d.d; }).d;
        }

        function xMaxFn (data) {
            return _.max(data, function (d) { return d.d; }).d;
        }

        function yMinFn (data) {
            return _.min(data, function (d) { return d.r; }).r;
        }

        function yMaxFn (data) {
            return _.max(data, function (d) { return d.r; }).r;
        }

        var xMin = xMinFn(data);
        var xMax = xMaxFn(data);
        var yMin = yMinFn(data);
        var yMax = yMaxFn(data);

        graph(size(250, 150))
            .element(point(position('d*r')))
            .scale(linear(dim(1), min(xMin), max(xMax)))
            .scale(linear(dim(2), min(yMin), max(yMax)))
            .render(ex(), data);

        graph(size(250, 150))
            .element(line(position('d*r')))
            .scale(linear(dim(1), min(xMin), max(xMax)))
            .scale(linear(dim(2), min(yMin), max(yMax)))
            .render(ex(), data);

        graph(size(250, 150))
            .element(point(position('d*r')))
            .element(line(position('d*r')))
            .scale(linear(dim(1), min(xMin), max(xMax)))
            .scale(linear(dim(2), min(yMin), max(yMax)))
            .render(ex(), data);

        graph(size(250, 150))
            .element(point(position('d*r')))
            .element(line(position('d*r')))
            .scale(linear(dim(1), min(xMinFn(semiLogData)), max(xMaxFn(semiLogData))))
            .scale(log(dim(2), min(yMinFn(semiLogData)), max(yMaxFn(semiLogData))))
            .render(ex(), semiLogData);

    });

})();<commit_msg>Adding interval display.<commit_after>;(function () {

    function Graph () {
        this.elements = [];
        this.scales   = {};
        this.d3Scales = {};
        return this;
    }

    Graph.prototype.rangeForDim = function (dim) {
        if (dim == 1) {
            return [0, this.width];
        } else if (dim == 2) {
            return [this.height, 0];
        } else {
            throw 'Only 2d graphics supported: Bad dim: ' + dim;
        }
    };

    Graph.prototype.render = function (id, data) {
        // Render the graph using the given data into the div with the given id.
        this.svg = d3.select(id).append('svg')
            .attr('width', this.width)
            .attr('height', this.height);

        this.svg.append('rect')
            .attr('x', 0)
            .attr('y', 0)
            .attr('width', this.width)
            .attr('height', this.height)
            .attr('fill', '#dcb')
            .attr('fill-opacity', 1);

        // If a scale has not been specified for a dimension, we
        // should build a default linear scale with min and max

        _.each(this.scales, function (s, dim) {
            this.d3Scales[dim] = s.d3Scale.domain([s.min, s.max]).range(this.rangeForDim(dim));
        }, this);

        _.each(this.elements, function (e) { e.render(this, data); }, this);
    };

    Graph.prototype.element = function (e) {
        this.elements.push(e);
        return this;
    };

    Graph.prototype.scale = function (s) {
        this.scales[s.dim] = s;
        return this;
    };

    function PointElement () {
        this.rFn = function (d) { return 5; };
        return this;
    }

    PointElement.prototype.render = function (graph, data) {
        var that = this;
        var circle = graph.svg.selectAll('circle')
            .data(data)
            .enter()
            .append('circle')
            .attr('cx', function (d) { return graph.d3Scales[1](that.xFn(d)) })
            .attr('cy', function (d) { return graph.d3Scales[2](that.yFn(d)) })
            .attr('r', this.rFn);
    };

    function LineElement () {
        return this;
    }

    LineElement.prototype.render = function (graph, data) {
        var e = this;
        function x (d) { return graph.d3Scales[1](e.xFn(d)); }
        function y (d) { return graph.d3Scales[2](e.yFn(d)); }

        var polyline = graph.svg.append('polyline')
            .attr('points', _.map(data, function (d) { return x(d) + ',' + y(d); }, this).join(' '))
            .attr('fill', 'none')
            .attr('stroke', 'black')
            .attr('stroke-width', 2);
    }

    function IntervalElement () {
        return this;
    }

    IntervalElement.prototype.render = function (graph, data) {
        var that = this;

        var rect = graph.svg.selectAll('rect')
            .data(data)
            .enter()
            .append('rect')
            .attr('x', function (d) { return graph.d3Scales[1](that.xFn(d)) - 2.5; })
            .attr('width', 5)
            .attr('y', function (d) { return graph.d3Scales[2](that.yFn(d)); })
            .attr('height', function (d) { return graph.d3Scales[2](graph.scales[2].min) - graph.d3Scales[2](that.yFn(d)); });
    };

    // Scales

    function LinearScale () {
        this.d3Scale = d3.scale.linear();
        return this;
    }

    function LogScale () {
        this.d3Scale = d3.scale.log();
        return this;
    }

    ////////////////////////////////////////////////////////////////////////
    /// API

    function graph() { return build(Graph, arguments); }

    // Elements

    function point () { return build(PointElement, arguments); }

    function line () { return build(LineElement, arguments); }

    function interval () { return build(IntervalElement, arguments); }

    // Scales

    function linear () { return build(LinearScale, arguments); }

    function log () { return build(LogScale, arguments); }

   // Set the size of a graph.
    function size(w, h) {
        return function (g) {
            g.width = w;
            g.height = h;
        }
    }

    // Set the dimension of a scale.
    function dim (v) {
        return function (scale) { scale.dim = v; }
    }

    // Set the minimum value of a scale.
    function min (v) {
        return function (scale) { scale.min = v; }
    }

    // Set the maximum value of a scale.
    function max (v) {
        return function (scale) { scale.max = v; }
    }

    function position(expr) {
        var parse = expr.split(/([*\/+])/);
        var operands = [];
        var operators = [];
        _.each(parse, function (e, i) {
            if (i % 2 == 0) {
                operands.push(e);
            } else {
                operators.push(e);
            }
        });

        if (_.any(operators, function (op) { return op !== '*'; })) {
            throw "/ and + not implemented.";
        }

        return function (e) {
            e.xFn = function (d) { return d[operands[0]]; }
            e.yFn = function (d) { return d[operands[1]]; }
        }
    }

    ////////////////////////////////////////////////////////////////////////
    /// Internals

    // This is a kind of goofy way to do things but it enables us to
    // follow the Graphics Production Language pretty closely.
    function build (fn, args) {
        var obj = new fn();
        _.each(args, function (fn) { fn(obj); });
        return obj;
    }

    // Generate some random data.
    var data = (function () {
        var data = [];
        var x = 0;
        var y = 0;
        _.times(20, function () {
            x += Math.random() * 30;
            y += 20 - Math.random() * 30;
            data.push({
                d: x,
                r: y,
            });
        });
        return data;
    }());

    // Generate some random data for plotting semi-log.
    var semiLogData = (function () {
        var data = [];
        var x = 0;
        var y = 1;
        _.times(20, function () {
            x += Math.random() * 30;
            y *= Math.random() * 5;
            data.push({
                d: x,
                r: y,
            });
        });
        return data;
    }());

    $(document).ready(function() {

        var n = 0;
        function ex () {
            var id = 'example' + n++;
            d3.select('body').append('div').attr('id', id);
            return '#' + id;
        }

        function xMinFn (data) {
            return _.min(data, function (d) { return d.d; }).d;
        }

        function xMaxFn (data) {
            return _.max(data, function (d) { return d.d; }).d;
        }

        function yMinFn (data) {
            return _.min(data, function (d) { return d.r; }).r;
        }

        function yMaxFn (data) {
            return _.max(data, function (d) { return d.r; }).r;
        }

        var xMin = xMinFn(data);
        var xMax = xMaxFn(data);
        var yMin = yMinFn(data);
        var yMax = yMaxFn(data);

        // scatterplot
        graph(size(250, 150))
            .element(point(position('d*r')))
            .scale(linear(dim(1), min(xMin), max(xMax)))
            .scale(linear(dim(2), min(yMin), max(yMax)))
            .render(ex(), data);

        // line chart
        graph(size(250, 150))
            .element(line(position('d*r')))
            .scale(linear(dim(1), min(xMin), max(xMax)))
            .scale(linear(dim(2), min(yMin), max(yMax)))
            .render(ex(), data);

        // bar chart
        graph(size(250, 150))
            .element(interval(position('d*r')))
            .scale(linear(dim(1), min(xMin), max(xMax)))
            .scale(linear(dim(2), min(yMin), max(yMax)))
            .render(ex(), data);

        // combined points and line
        graph(size(250, 150))
            .element(point(position('d*r')))
            .element(line(position('d*r')))
            .scale(linear(dim(1), min(xMin), max(xMax)))
            .scale(linear(dim(2), min(yMin), max(yMax)))
            .render(ex(), data);

        // semi-log scale
        graph(size(250, 150))
            .element(point(position('d*r')))
            .element(line(position('d*r')))
            .scale(linear(dim(1), min(xMinFn(semiLogData)), max(xMaxFn(semiLogData))))
            .scale(log(dim(2), min(yMinFn(semiLogData)), max(yMaxFn(semiLogData))))
            .render(ex(), semiLogData);

    });

})();<|endoftext|>


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

// `git pull` from the repo and branch that a PR originates from.

var https = require('https');
var execSync = require('child_process').execSync;
var fs = require('fs');

var usage = '\n gpr [-b | -i | -D] {pr}'
var help = usage +
    '\n\n -b: Create new branch off master with gpr prefix.\n' +
    ' -i: Show the PR title and requestor.' +
    ' -D: Force delete the branch created.\n' +
    ' {pr}: PR number to pull the remote branch for.';

// Exit with a message
function exit(error) {
  console.log(error,'\n')
  process.exit();
};

// Exec with echo
function execho(command) {
  console.log('\n', command);
  try {
    execSync(command, function puts(error, stdout, stderr) { console.log(stdout) });
  } catch (err) {
   //console.error(err);
  }
};

// Get the repo name from the package.jason in the neareast parent directory
var npmPrefix = execSync('npm prefix', {cwd: process.cwd(), encoding: 'utf8'}).replace(/\s+/g, '');

// Read the package.json and extract the repo name
var packageFile = JSON.parse(fs.readFileSync(npmPrefix + '/package.json', 'utf8'));
var repo = packageFile.repository.url.split('/')
repo = repo[3]+ '/' + repo[4].slice(0, -4)

// Read the command-line args
var args = process.argv;
if (args.length < 3) {
  exit(usage);
} else if (args[2] == '-h' || args[2] == '--help') {
 exit(help);
} else {
  var prNumber = args[args.length - 1];
  if (~~prNumber === 0) { exit(usage + '\n\n <pr> must be a number.'); };
};

var options = {
  hostname: 'api.github.com',
  port: 443,
  path: '/repos/' + repo + '/pulls/' + prNumber,
  headers: {
    'User-Agent': 'git-pull'
  },
};

https.get(options, function(result) {
  var body = '';

  result.on('data', function(chunk) {
    body += chunk;
  });

  result.on('end', function() {
    var response = JSON.parse(body);

    if (typeof response.head === 'undefined') {
      exit('\n Couldn\'t find PR #' + prNumber)
    }

    if (args[2] === '-i') {
      console.log('\n' + response.title, '(@' + response.user.login + ')\n');
      process.exit();
    };

    if (args[2] === '-D') {
      execho('git checkout master');
      execho('git branch -D gpr/' + prNumber);
      process.exit();
    };

    if (args[2] === '-b') {
      execho('git checkout master');
      execho('git branch gpr/' + prNumber);
      execho('git checkout gpr/' + prNumber);
    }
    execho("git pull " + response.head.repo.clone_url + " " + response.head.ref);
  });

}).on('error', function(error) {
  console.log("Error: ", error);
});
<commit_msg>Default to creating a new branch, -b {branch-name}, pull only.<commit_after>#!/usr/local/bin/node

// `git pull` from the repo and branch that a PR originates from.

var https = require('https');
var execSync = require('child_process').execSync;
var fs = require('fs');

var usage = '\n gpr [-b {branch-name} | -i | -D] {PR#}'
var help = usage +
    '\n\n -b: Create new branch {branch-name} from master. Defaults to \'grp/PR#\'\n' +
    ' -i: Show the PR title and requestor.' +
    ' -D: Force delete the branch created.\n' +
    ' {pr}: PR number to pull the remote branch for.';

// Exit with a message
function exit(error) {
  console.log(error,'\n')
  process.exit();
};

// Exec with echo
function execho(command) {
  console.log('\n', command);
  try {
    execSync(command, function puts(error, stdout, stderr) { console.log(stdout) });
  } catch (err) {
   //console.error(err);
  }
};

// Get the repo name from the package.jason in the neareast parent directory
var npmPrefix = execSync('npm prefix', {cwd: process.cwd(), encoding: 'utf8'}).replace(/\s+/g, '');

// Read the package.json and extract the repo name
var packageFile = JSON.parse(fs.readFileSync(npmPrefix + '/package.json', 'utf8'));
var repo = packageFile.repository.url.split('/')
repo = repo[3]+ '/' + repo[4].slice(0, -4)

// Read the command-line args
var args = process.argv;
if (args.length < 3) {
  exit(usage);
} else if (args[2] == '-h' || args[2] == '--help') {
 exit(help);
} else {
  var prNumber = args[args.length - 1];
  if (~~prNumber === 0) { exit(usage + '\n\n <pr> must be a number.'); };
};

var options = {
  hostname: 'api.github.com',
  port: 443,
  path: '/repos/' + repo + '/pulls/' + prNumber,
  headers: {
    'User-Agent': 'git-pull'
  },
};

https.get(options, function(result) {
  var body = '';

  result.on('data', function(chunk) {
    body += chunk;
  });

  result.on('end', function() {
    var response = JSON.parse(body);

    if (typeof response.head === 'undefined') {
      exit('\n Couldn\'t find PR #' + prNumber)
    }

    pull = "git pull " + response.head.repo.clone_url + " " + response.head.ref;
    branch = 'gpr/' + prNumber

    switch(args[2]) {
      case '-i':
        console.log('\n' + response.title, '(@' + response.user.login + ')\n');
        process.exit();

      case 'pull':
        execho(pull);

      case '-D':
        execho('git checkout master');
        execho('git branch -D gpr/' + prNumber);
        process.exit();

      case '-b':
        branch = args[args.length - 2]

      default:
      execho('git checkout master');
      execho('git branch ' + branch);
      execho('git checkout gpr/' + prNumber);
      execho(pull);
    }
  });

}).on('error', function(error) {
  console.log("Error: ", error);
});
<|endoftext|>


<commit_before>define(function(require, module, exports) {
    main.consumes = [
        "Plugin", "build", "settings", "commands", "fs", "save",
        "menus", "tabManager", "ui", "dialog.error"
    ];
    main.provides = ["build.gui"];
    return main;

    function main(options, imports, register) {
        var Plugin      = imports.Plugin;
        var settings    = imports.settings;
        var commands    = imports.commands;
        var menus       = imports.menus;
        var save        = imports.save;
        var build       = imports.build;
        var fs          = imports.fs;
        var ui          = imports.ui;
        var tabs        = imports.tabManager;
        var showError   = imports["dialog.error"].show;
        var uCaseFirst  = require("c9/string").uCaseFirst;

        /***** Initialization *****/

        var plugin  = new Plugin("Ajax.org", main.consumes);
        // var emit    = plugin.getEmitter();

        var process, currentBuilder;

        var loaded = false;
        function load(){
            if (loaded) return false;
            loaded = true;

            // Commands
            commands.addCommand({
                name    : "build",
                group   : "Run & Debug",
                hint    : "builds the current file (focussed document)",
                bindKey : { mac: "Command-B", win: "Ctrl-B" },
                isAvailable : function(){
                    return getFocusTab() ? true : false;
                },
                exec : function(){
                    buildFocusTab();
                }
            }, plugin);

            commands.addCommand({
                name    : "stopbuild",
                group   : "Run & Debug",
                hint    : "stop a running build",
                bindKey : { mac: "Ctrl-Shift-C", win: "Ctrl-Shift-C" },
                isAvailable : function(){
                    return process && process.running;
                },
                exec    : function(){
                    process && process.stop();
                }
            }, plugin);

            // Settings
            settings.on("read", function(){
                settings.setDefaults("project/build", [
                    ["saveall", "true"],
                    ["builder", "auto"]
                ]);
                settings.setDefaults("user/build", [
                    ["autobuild", "true"]
                ]);

                var name = settings.get("project/build/@builder");
                setCurrentBuilder(name, function(){});
            });

            // Menus
            var c = 10000;
            menus.addItemByPath("Run/~", new ui.divider(), c += 100, plugin);

            var mnuBuildSystem = new ui.menu({
                "onprop.visible": function(e){
                    if (e.value) {
                        build.listBuilders(function(err, names){
                            var nodes = mnuBuildSystem.childNodes;
                            for (var i = nodes.length - 3; i >= 2; i--) {
                                mnuBuildSystem.removeChild(nodes[i]);
                            }

                            var builder = settings.get("project/build/@builder");
                            if (builder == "auto")
                                nodes[0].select();

                            var c = 300;
                            names.forEach(function(name){
                                menus.addItemToMenu(mnuBuildSystem, new ui.item({
                                    type     : "radio",
                                    caption  : uCaseFirst(name),
                                    value    : name,
                                    selected : builder == name
                                }), c++, plugin);
                            });
                        });
                    }
                },
                "onitemclick": function(e){
                    if (e.value == "new-build-system") {
                        tabs.open({
                            path   : settings.get("project/build/@path")
                              + "/New Build System",
                            active : true,
                            value  : '{\n'
                              + '    "caption" : "",\n'
                              + '    "cmd" : ["ls"],\n'
                              + '    "selector": "source.ext"\n'
                              + '}',
                            document : {
                                meta : {
                                    newfile: true
                                },
                                ace : {
                                    customType : "json"
                                }
                            }
                        }, function(){});
                        return;
                    }

                    setCurrentBuilder(e.value, function(){});
                    settings.set("project/build/@builder", e.value);
                }
            });

            menus.addItemByPath("Run/Build System/", mnuBuildSystem,
                c += 100, plugin);
            menus.addItemByPath("Run/Build", new ui.item({
                command : "build"
            }), c += 100, plugin);
            menus.addItemByPath("Run/Cancel Build", new ui.item({
                command : "stopbuild"
            }), c += 100, plugin);
            menus.addItemByPath("Run/Show Build Result", new ui.item({
                onclick: function(){
                    commands.exec("showoutput", null, { id: "build" });
                }
            }), c += 100, plugin);
            menus.addItemByPath("Run/Automatically Build Supported Files", new ui.item({
                type  : "check",
                value : "[{settings.model}::user/build/@autobuild]"
            }), c += 100, plugin);
            menus.addItemByPath("Run/Save All on Build", new ui.item({
                type  : "check",
                value : "[{settings.model}::project/build/@saveall]"
            }), c += 100, plugin);

            c = 0;
            menus.addItemByPath("Run/Build System/Automatic", new ui.item({
                type  : "radio",
                value : "auto"
            }), c += 100, plugin);
            menus.addItemByPath("Run/Build System/~", new ui.divider(), c += 100, plugin);
            menus.addItemByPath("Run/Build System/~", new ui.divider(), c += 1000, plugin);
            menus.addItemByPath("Run/Build System/New Build System", new ui.item({
                value : "new-build-system"
            }), c += 100, plugin);

            // Hook into FS and build file when writeFile is triggered
            save.on("afterSave", function(e){
                if (!settings.getBool("user/build/@autobuild"))
                    return;

                var ext = fs.getExtension(e.path);
                if (!ext)
                    return;

                // @todo consider making this a hash map
                if (currentBuilder == "auto") {
                    if (Object.keys(build.builders).every(function(name){
                        return build.builders[name].selector != "source." + ext;
                    })) return;
                }
                else if (currentBuilder.selector != "source." + ext)
                    return;

                buildFocusTab(true, e.path);
            });
        };

        /***** Methods *****/

        function setCurrentBuilder(name, callback){
            currentBuilder = name;
            if (currentBuilder != "auto") {
                build.getBuilder(currentBuilder, true, function(err, builder){
                    if (err)
                        currentBuilder = "auto";
                    else
                        currentBuilder = builder;
                    callback(err, builder);
                });
            }
        }

        function getFocusTab(){
            var tab = tabs.focussedTab;
            if (!tab) return false;
            if (tab.path) return tab;
            if (tab.editor.type != "output") return false;

            var splits = tab.pane.aml
                .parentNode.parentNode.getElementsByTagName("tab");
            if (splits.length > 1) {
                var idx = splits[0].cloud9pane == tab.pane ? 1 : 0;
                tab = splits[idx].cloud9pane.getTab();
                return tab;
            }
            return false;
        }

        function buildFocusTab(onlyBuild, path){
            if (!path) {
                var tab = getFocusTab();
                if (!tab) return;
                path = tab.path;
            }

            if (!onlyBuild)
                commands.exec("showoutput", null, { id: "build" });

            if (settings.get("project/build/@saveall"))
                save.saveAll(done);
            else
                done();

            function done(){
                process = build.build(currentBuilder,
                    { path: path }, "build", function(err, pid){
                        if (err && err.code != "EBUILDERNOTFOUND")
                            return showError(err);
                    });
            }
        }

        /***** Lifecycle *****/

        plugin.on("load", function(){
            load();
        });
        plugin.on("enable", function(){

        });
        plugin.on("disable", function(){

        });
        plugin.on("unload", function(){
            loaded = false;
        });

        /***** Register and define API *****/

        /**
         * UI for the {@link build} plugin. This plugin is responsible for the Run
         * menu in the main menu bar, as well as the settings and the
         * preferences UI for the run plugin.
         * @singleton
         */
        /**
         * @command build Builds the currently focussed tab.
         */
        /**
         * @command stopbuild Stops the running build.
         */
        plugin.freezePublicAPI({

        });

        register(null, {
            "build.gui": plugin
        });
    }
});
<commit_msg>Fixes +1171. Add a link to the documentation in the build system<commit_after>define(function(require, module, exports) {
    main.consumes = [
        "Plugin", "build", "settings", "commands", "fs", "save",
        "menus", "tabManager", "ui", "dialog.error"
    ];
    main.provides = ["build.gui"];
    return main;

    function main(options, imports, register) {
        var Plugin      = imports.Plugin;
        var settings    = imports.settings;
        var commands    = imports.commands;
        var menus       = imports.menus;
        var save        = imports.save;
        var build       = imports.build;
        var fs          = imports.fs;
        var ui          = imports.ui;
        var tabs        = imports.tabManager;
        var showError   = imports["dialog.error"].show;
        var uCaseFirst  = require("c9/string").uCaseFirst;

        /***** Initialization *****/

        var plugin  = new Plugin("Ajax.org", main.consumes);
        // var emit    = plugin.getEmitter();

        var process, currentBuilder;

        var loaded = false;
        function load(){
            if (loaded) return false;
            loaded = true;

            // Commands
            commands.addCommand({
                name    : "build",
                group   : "Run & Debug",
                hint    : "builds the current file (focussed document)",
                bindKey : { mac: "Command-B", win: "Ctrl-B" },
                isAvailable : function(){
                    return getFocusTab() ? true : false;
                },
                exec : function(){
                    buildFocusTab();
                }
            }, plugin);

            commands.addCommand({
                name    : "stopbuild",
                group   : "Run & Debug",
                hint    : "stop a running build",
                bindKey : { mac: "Ctrl-Shift-C", win: "Ctrl-Shift-C" },
                isAvailable : function(){
                    return process && process.running;
                },
                exec    : function(){
                    process && process.stop();
                }
            }, plugin);

            // Settings
            settings.on("read", function(){
                settings.setDefaults("project/build", [
                    ["saveall", "true"],
                    ["builder", "auto"]
                ]);
                settings.setDefaults("user/build", [
                    ["autobuild", "true"]
                ]);

                var name = settings.get("project/build/@builder");
                setCurrentBuilder(name, function(){});
            });

            // Menus
            var c = 10000;
            menus.addItemByPath("Run/~", new ui.divider(), c += 100, plugin);

            var mnuBuildSystem = new ui.menu({
                "onprop.visible": function(e){
                    if (e.value) {
                        build.listBuilders(function(err, names){
                            var nodes = mnuBuildSystem.childNodes;
                            for (var i = nodes.length - 3; i >= 2; i--) {
                                mnuBuildSystem.removeChild(nodes[i]);
                            }

                            var builder = settings.get("project/build/@builder");
                            if (builder == "auto")
                                nodes[0].select();

                            var c = 300;
                            names.forEach(function(name){
                                menus.addItemToMenu(mnuBuildSystem, new ui.item({
                                    type     : "radio",
                                    caption  : uCaseFirst(name),
                                    value    : name,
                                    selected : builder == name
                                }), c++, plugin);
                            });
                        });
                    }
                },
                "onitemclick": function(e){
                    if (e.value == "new-build-system") {
                        tabs.open({
                            path   : settings.get("project/build/@path")
                              + "/New Build System",
                            active : true,
                            value  : '// Create a custom Cloud9 build system - similar to the Sublime build system\n'
                              + '// For more information see http://docs.c9.io:8080/#!/api/run-method-run\n'
                              + '{\n'
                              + '    "caption" : "",\n'
                              + '    "cmd" : ["ls"],\n'
                              + '    "selector": "source.ext"\n'
                              + '}',
                            document : {
                                meta : {
                                    newfile: true
                                },
                                ace : {
                                    customType : "json"
                                }
                            }
                        }, function(){});
                        return;
                    }

                    setCurrentBuilder(e.value, function(){});
                    settings.set("project/build/@builder", e.value);
                }
            });

            menus.addItemByPath("Run/Build System/", mnuBuildSystem,
                c += 100, plugin);
            menus.addItemByPath("Run/Build", new ui.item({
                command : "build"
            }), c += 100, plugin);
            menus.addItemByPath("Run/Cancel Build", new ui.item({
                command : "stopbuild"
            }), c += 100, plugin);
            menus.addItemByPath("Run/Show Build Result", new ui.item({
                onclick: function(){
                    commands.exec("showoutput", null, { id: "build" });
                }
            }), c += 100, plugin);
            menus.addItemByPath("Run/Automatically Build Supported Files", new ui.item({
                type  : "check",
                value : "[{settings.model}::user/build/@autobuild]"
            }), c += 100, plugin);
            menus.addItemByPath("Run/Save All on Build", new ui.item({
                type  : "check",
                value : "[{settings.model}::project/build/@saveall]"
            }), c += 100, plugin);

            c = 0;
            menus.addItemByPath("Run/Build System/Automatic", new ui.item({
                type  : "radio",
                value : "auto"
            }), c += 100, plugin);
            menus.addItemByPath("Run/Build System/~", new ui.divider(), c += 100, plugin);
            menus.addItemByPath("Run/Build System/~", new ui.divider(), c += 1000, plugin);
            menus.addItemByPath("Run/Build System/New Build System", new ui.item({
                value : "new-build-system"
            }), c += 100, plugin);

            // Hook into FS and build file when writeFile is triggered
            save.on("afterSave", function(e){
                if (!settings.getBool("user/build/@autobuild"))
                    return;

                var ext = fs.getExtension(e.path);
                if (!ext)
                    return;

                // @todo consider making this a hash map
                if (currentBuilder == "auto") {
                    if (Object.keys(build.builders).every(function(name){
                        return build.builders[name].selector != "source." + ext;
                    })) return;
                }
                else if (currentBuilder.selector != "source." + ext)
                    return;

                buildFocusTab(true, e.path);
            });
        };

        /***** Methods *****/

        function setCurrentBuilder(name, callback){
            currentBuilder = name;
            if (currentBuilder != "auto") {
                build.getBuilder(currentBuilder, true, function(err, builder){
                    if (err)
                        currentBuilder = "auto";
                    else
                        currentBuilder = builder;
                    callback(err, builder);
                });
            }
        }

        function getFocusTab(){
            var tab = tabs.focussedTab;
            if (!tab) return false;
            if (tab.path) return tab;
            if (tab.editor.type != "output") return false;

            var splits = tab.pane.aml
                .parentNode.parentNode.getElementsByTagName("tab");
            if (splits.length > 1) {
                var idx = splits[0].cloud9pane == tab.pane ? 1 : 0;
                tab = splits[idx].cloud9pane.getTab();
                return tab;
            }
            return false;
        }

        function buildFocusTab(onlyBuild, path){
            if (!path) {
                var tab = getFocusTab();
                if (!tab) return;
                path = tab.path;
            }

            if (!onlyBuild)
                commands.exec("showoutput", null, { id: "build" });

            if (settings.get("project/build/@saveall"))
                save.saveAll(done);
            else
                done();

            function done(){
                process = build.build(currentBuilder,
                    { path: path }, "build", function(err, pid){
                        if (err && err.code != "EBUILDERNOTFOUND")
                            return showError(err);
                    });
            }
        }

        /***** Lifecycle *****/

        plugin.on("load", function(){
            load();
        });
        plugin.on("enable", function(){

        });
        plugin.on("disable", function(){

        });
        plugin.on("unload", function(){
            loaded = false;
        });

        /***** Register and define API *****/

        /**
         * UI for the {@link build} plugin. This plugin is responsible for the Run
         * menu in the main menu bar, as well as the settings and the
         * preferences UI for the run plugin.
         * @singleton
         */
        /**
         * @command build Builds the currently focussed tab.
         */
        /**
         * @command stopbuild Stops the running build.
         */
        plugin.freezePublicAPI({

        });

        register(null, {
            "build.gui": plugin
        });
    }
});
<|endoftext|>