<commit_before>//var camcmd_url = "CAMERA_URL";
var camcmd_cmd_url = "https://camcommand.herokuapp.com/commands/new";
var camcmd_new_url = "https://camcommand.herokuapp.com/commands/clear";
var camcmd_asset_path = "https://camcommand.herokuapp.com/";
var camcmd_show = true;

function camcmd_createWindow()
{
	var body = $('body');

	var camcmd_win = $("
");
	camcmd_win.css({'height' : camcmd_win.width()+'px'});
	camcmd_win.append($("
").append($("
?
"),$("
X
")));

	var camcmd_options = $("
");
	camcmd_options.append($("
Camera URL

<input class='camcmd_input' id='camcmd_url' name='camcmd_url'></input>
"));
	camcmd_win.append(camcmd_options);
	var grid = [];
	var grid_w = 3;
	var grid_h = 4;
	for(var y = 0; y < grid_h; ++y)
	{
		for(var x = 0; x < grid_w; ++x)
		{
			grid[x+(y*grid_w)] = $("
");
		}
	}

	//Control defs
	grid[1].append($("
").html($("")));
	grid[1].append($("
").html($("")));

	grid[3].append($("
").html($("")));
	grid[3].append($("
").html($("")));

	grid[5].append($("
").html($("")));
	grid[5].append($("
").html($("")));

	grid[7].append($("
").html($("")));
	grid[7].append($("
").html($("")));

	grid[9].append($("<button id='camcmd_tilt_center' type='button'>Center Tilt</button>"));
	grid[11].append($("<button id='camcmd_pan_center' type='button'>Center Pan</button>"));

	 //Attach grid
	var controls = $("
");
	for(var index = 0; index < grid_w * grid_h; ++index)
	{
		controls.append(grid[index]);
	}
	camcmd_win.append(controls);

	body.append(camcmd_win);
}

function camcmd_dispatchCommand(cmd)
{
	$.post(camcmd_cmd_url,{command : cmd});
}

function camcmd_startNewSession(cmd)
{
	$.post(camcmd_new_url, {comfirm : "yes"});
}

function camcmd_showOptions()
{
	$('#camcmd_options_window').slideToggle();
}

function camcmd_hideOptions()
{
	if($('#camcmd_options_window').css('display') != 'none')
	{
		$('#camcmd_options_window').slideToggle();
	}
}

function camcmd_toggleWindow()
{
	$('#camcmd_controls').slideToggle();
}

function camcmd_bindControls()
{

	$('#camcmd_up').mousedown(function() {
		camcmd_dispatchCommand("u");
	});
	$('#camcmd_big_up').mousedown(function() {
		camcmd_dispatchCommand("U");
	});
	$('#camcmd_down').mousedown(function(){
		camcmd_dispatchCommand("d");
	});
	$('#camcmd_big_down').mousedown(function() {
		camcmd_dispatchCommand("D");
	});
	$('#camcmd_right').mousedown(function() {
		camcmd_dispatchCommand("r");
	});
	$('#camcmd_big_right').mousedown(function() {
		camcmd_dispatchCommand("R");
	});
	$('#camcmd_left').mousedown(function() {
		camcmd_dispatchCommand("l");
	});
	$('#camcmd_big_left').mousedown(function() {
		camcmd_dispatchCommand("L");
	});

	$('#camcmd_options').mousedown(function(){
		camcmd_showOptions();
	});
	$('#camcmd_close').mousedown(function(){
		camcmd_toggleWindow();
	});
	$('#camcmd_tilt_center').click(function(){
		camcmd_dispatchCommand("t");
	});
	$('#camcmd_pan_center').click(function(){
		camcmd_dispatchCommand("p");
	});
	$('#camcmd_url').change(function(){
		camcmd_url = $(this).text();
	}).keypress(function(e) {
		if (e.which === 13) {
			camcmd_hideOptions();
		}
		e.stopPropagation();
	});

}

//(function() {
//  if (gapi && gapi.hangout) {
//    var initHangout = function(apiInitEvent) {
		//if (apiInitEvent.isApiReady) {
//			camcmd_createWindow();
//			camcmd_bindControls();
			//gapi.hangout.onApiReady.remove(initHangout);
		//}
    //};
    //gapi.hangout.onApiReady.add(initHangout);
  //}
//})();
<commit_msg>JS hook to clear/new<commit_after>//var camcmd_url = "CAMERA_URL";
var camcmd_cmd_url = "https://camcommand.herokuapp.com/commands/new";
var camcmd_new_url = "https://camcommand.herokuapp.com/commands/clear";
var camcmd_asset_path = "https://camcommand.herokuapp.com/";
var camcmd_show = true;

function camcmd_createWindow()
{
	camcmd_startNewSession();
	var body = $('body');

	var camcmd_win = $("
");
	camcmd_win.css({'height' : camcmd_win.width()+'px'});
	camcmd_win.append($("
").append($("
?
"),$("
X
")));

	var camcmd_options = $("
");
	camcmd_options.append($("
Camera URL

<input class='camcmd_input' id='camcmd_url' name='camcmd_url'></input>
"));
	camcmd_win.append(camcmd_options);
	var grid = [];
	var grid_w = 3;
	var grid_h = 4;
	for(var y = 0; y < grid_h; ++y)
	{
		for(var x = 0; x < grid_w; ++x)
		{
			grid[x+(y*grid_w)] = $("
");
		}
	}

	//Control defs
	grid[1].append($("
").html($("")));
	grid[1].append($("
").html($("")));

	grid[3].append($("
").html($("")));
	grid[3].append($("
").html($("")));

	grid[5].append($("
").html($("")));
	grid[5].append($("
").html($("")));

	grid[7].append($("
").html($("")));
	grid[7].append($("
").html($("")));

	grid[9].append($("<button id='camcmd_tilt_center' type='button'>Center Tilt</button>"));
	grid[11].append($("<button id='camcmd_pan_center' type='button'>Center Pan</button>"));

	 //Attach grid
	var controls = $("
");
	for(var index = 0; index < grid_w * grid_h; ++index)
	{
		controls.append(grid[index]);
	}
	camcmd_win.append(controls);

	body.append(camcmd_win);
}

function camcmd_dispatchCommand(cmd)
{
	$.post(camcmd_cmd_url,{command : cmd});
}

function camcmd_startNewSession()
{
	$.post(camcmd_new_url, {comfirm : "yes"});
}

function camcmd_showOptions()
{
	$('#camcmd_options_window').slideToggle();
}

function camcmd_hideOptions()
{
	if($('#camcmd_options_window').css('display') != 'none')
	{
		$('#camcmd_options_window').slideToggle();
	}
}

function camcmd_toggleWindow()
{
	$('#camcmd_controls').slideToggle();
}

function camcmd_bindControls()
{

	$('#camcmd_up').mousedown(function() {
		camcmd_dispatchCommand("u");
	});
	$('#camcmd_big_up').mousedown(function() {
		camcmd_dispatchCommand("U");
	});
	$('#camcmd_down').mousedown(function(){
		camcmd_dispatchCommand("d");
	});
	$('#camcmd_big_down').mousedown(function() {
		camcmd_dispatchCommand("D");
	});
	$('#camcmd_right').mousedown(function() {
		camcmd_dispatchCommand("r");
	});
	$('#camcmd_big_right').mousedown(function() {
		camcmd_dispatchCommand("R");
	});
	$('#camcmd_left').mousedown(function() {
		camcmd_dispatchCommand("l");
	});
	$('#camcmd_big_left').mousedown(function() {
		camcmd_dispatchCommand("L");
	});

	$('#camcmd_options').mousedown(function(){
		camcmd_showOptions();
	});
	$('#camcmd_close').mousedown(function(){
		camcmd_toggleWindow();
	});
	$('#camcmd_tilt_center').click(function(){
		camcmd_dispatchCommand("t");
	});
	$('#camcmd_pan_center').click(function(){
		camcmd_dispatchCommand("p");
	});
	$('#camcmd_url').change(function(){
		camcmd_url = $(this).text();
	}).keypress(function(e) {
		if (e.which === 13) {
			camcmd_hideOptions();
		}
		e.stopPropagation();
	});

}

//(function() {
//  if (gapi && gapi.hangout) {
//    var initHangout = function(apiInitEvent) {
		//if (apiInitEvent.isApiReady) {
//			camcmd_createWindow();
//			camcmd_bindControls();
			//gapi.hangout.onApiReady.remove(initHangout);
		//}
    //};
    //gapi.hangout.onApiReady.add(initHangout);
  //}
//})();
<|endoftext|>


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

var csv = require('fast-csv');
var fs = require('fs');
var options = require('commander');
var grouper = require('./lib/grouper');
var geocoder = require('./lib/geocoder');
var streamSplitter = require('./lib/streamSplitter');
var through2 = require('through2');

var package = JSON.parse(fs.readFileSync(__dirname+'/package.json', 'utf8'));

options
  .version(package.version)
  .option('-i, --input [file]', 'Input (csv file) [stdin]', '-')
  .option('-o, --output [file]', 'Output (csv file) [stdout]', '-')
  .option('-s, --street-col [col]', 'Street col [street]', 'street')
  .option('-z, --zipcode-col [col]', 'Zipcode col [zipcode]', 'zipcode')
  .option('-c, --city-col [col]', 'City col [city]', 'city')
  .option('-S, --state-col [col]', 'State col [state]', 'state') // short forms are dumb
  .option('-d, --delimiter [symbol]', 'CSV delimiter in input file', ',')
  .option('-O, --output-split [column]', 'Write to multiple files divided by column', '')
  .option('-a, --auth-id [id]', 'SmartyStreets auth id [environment variable smartystreets_auth_id]', process.env.SMARTYSTREETS_AUTH_ID)
  .option('-A, --auth-token [token]', 'SmartyStreets auth token [environment variable smartystreets_auth_token]', process.env.SMARTYSTREETS_AUTH_TOKEN)
  .option('-j, --concurrency [jobs]', 'Maximum number of concurrent requests [48]', 48)
  .option('-✈, --column-definition [mode]', 'Column definition mode or file [standard]', 'standard')
  .option('-p, --column-prefix [text]', 'Prefix for smartystreets columns in the output file [ss_]', 'ss_')
  .option('-x, --column-suffix [text]', 'Suffix for smartystreets columns in the output file', '')
  .option('-q, --quiet', 'Quiet mode - turn off progress messages')
  .option('-l, --log-interval [num]', 'Show progress after every X number of rows [1000]', 1000)
  .parse(process.argv);

options.concurrency = parseInt(options.concurrency);

if (!options.concurrency) {
  console.error('Invalid concurrency');
  options.help();
}

if (!options.authId) {
  console.error('Please specify a SmartyStreets auth id');
  options.help();
}

if (!options.authToken) {
  console.error('Please specify a SmartyStreets auth token');
  options.help();
}

if (!options.input) {
  console.error('Please specify an input file');
  options.help();
}
if (!options.output) {
  console.error('Please specify an input file');
  options.help();
}

var columnModes = ['mail', 'standard', 'complete', 'basic'];
if (columnModes.indexOf(options.columnDefinition) != -1) {
  //modes are in structure/mode.json
  options.structure = JSON.parse( fs.readFileSync(__dirname+'/structure/'+options.columnDefinition+'.json', 'utf8') );
} else if (options.columnDefinition.substr(0, 1) == '{') {
  //it's a JSON object
  options.structure = JSON.parse(options.columnDefinition);
} else {
  //it's a JSON file
  options.structure = JSON.parse( fs.readFileSync(options.columnDefinition, 'utf8') );
}

var readStream = options.input == '-' ? process.stdin : fs.createReadStream(options.input);

var writeStream;
if (options.outputSplit) {
  try {
    fs.mkdirSync(options.output);
  } catch(e) {
    if ( e.code != 'EEXIST' ) throw e;
  }

  var firstRow = true, rowIndex, headers;

  writeStream = streamSplitter(function(row){
    if (firstRow) {
      firstRow = false;
      rowIndex = row.indexOf(options.outputSplit);
      headers = row;

      if (rowIndex == -1) {
        console.error('couldn\'t find column', options.outputSplit, 'in', row);
        process.exit();
      }

      return false;
    }

    return row[rowIndex];
  }, function(streamName){
    var source = csv.createWriteStream();
    source.write(headers);
    source.pipe( fs.createWriteStream(options.output+'/'+streamName+'.csv') );
    return source;
  }, {objectMode: true});
} else if (options.output == '-') {
  writeStream = csv.createWriteStream();
  writeStream.pipe( process.stdout );
} else {
  writeStream = csv.createWriteStream();
  writeStream.pipe( fs.createWriteStream(options.output) );
}

readStream.pipe(csv({headers: true, delimiter: options.delimiter}))
  .pipe(grouper(70))
  .pipe(geocoder(options))
  .pipe(writeStream);<commit_msg>truncate output split columns to 2 characters<commit_after>#!/usr/bin/env node

var csv = require('fast-csv');
var fs = require('fs');
var options = require('commander');
var grouper = require('./lib/grouper');
var geocoder = require('./lib/geocoder');
var streamSplitter = require('./lib/streamSplitter');
var through2 = require('through2');

var package = JSON.parse(fs.readFileSync(__dirname+'/package.json', 'utf8'));

options
  .version(package.version)
  .option('-i, --input [file]', 'Input (csv file) [stdin]', '-')
  .option('-o, --output [file]', 'Output (csv file) [stdout]', '-')
  .option('-s, --street-col [col]', 'Street col [street]', 'street')
  .option('-z, --zipcode-col [col]', 'Zipcode col [zipcode]', 'zipcode')
  .option('-c, --city-col [col]', 'City col [city]', 'city')
  .option('-S, --state-col [col]', 'State col [state]', 'state') // short forms are dumb
  .option('-d, --delimiter [symbol]', 'CSV delimiter in input file', ',')
  .option('-O, --output-split [column]', 'Write to multiple files divided by column', '')
  .option('-a, --auth-id [id]', 'SmartyStreets auth id [environment variable smartystreets_auth_id]', process.env.SMARTYSTREETS_AUTH_ID)
  .option('-A, --auth-token [token]', 'SmartyStreets auth token [environment variable smartystreets_auth_token]', process.env.SMARTYSTREETS_AUTH_TOKEN)
  .option('-j, --concurrency [jobs]', 'Maximum number of concurrent requests [48]', 48)
  .option('-✈, --column-definition [mode]', 'Column definition mode or file [standard]', 'standard')
  .option('-p, --column-prefix [text]', 'Prefix for smartystreets columns in the output file [ss_]', 'ss_')
  .option('-x, --column-suffix [text]', 'Suffix for smartystreets columns in the output file', '')
  .option('-q, --quiet', 'Quiet mode - turn off progress messages')
  .option('-l, --log-interval [num]', 'Show progress after every X number of rows [1000]', 1000)
  .parse(process.argv);

options.concurrency = parseInt(options.concurrency);

if (!options.concurrency) {
  console.error('Invalid concurrency');
  options.help();
}

if (!options.authId) {
  console.error('Please specify a SmartyStreets auth id');
  options.help();
}

if (!options.authToken) {
  console.error('Please specify a SmartyStreets auth token');
  options.help();
}

if (!options.input) {
  console.error('Please specify an input file');
  options.help();
}
if (!options.output) {
  console.error('Please specify an input file');
  options.help();
}

var columnModes = ['mail', 'standard', 'complete', 'basic'];
if (columnModes.indexOf(options.columnDefinition) != -1) {
  //modes are in structure/mode.json
  options.structure = JSON.parse( fs.readFileSync(__dirname+'/structure/'+options.columnDefinition+'.json', 'utf8') );
} else if (options.columnDefinition.substr(0, 1) == '{') {
  //it's a JSON object
  options.structure = JSON.parse(options.columnDefinition);
} else {
  //it's a JSON file
  options.structure = JSON.parse( fs.readFileSync(options.columnDefinition, 'utf8') );
}

var readStream = options.input == '-' ? process.stdin : fs.createReadStream(options.input);

var writeStream;
if (options.outputSplit) {
  try {
    fs.mkdirSync(options.output);
  } catch(e) {
    if ( e.code != 'EEXIST' ) throw e;
  }

  var firstRow = true, rowIndex, headers;

  writeStream = streamSplitter(function(row){
    if (firstRow) {
      firstRow = false;
      rowIndex = row.indexOf(options.outputSplit);
      headers = row;

      if (rowIndex == -1) {
        console.error('couldn\'t find column', options.outputSplit, 'in', row);
        process.exit();
      }

      return false;
    }

    var cell = row[rowIndex];

    while (cell.length < 5) {
      cell = '0'+cell;
    }

    return row[rowIndex].substr(0, 2);
  }, function(streamName){
    var source = csv.createWriteStream();
    source.write(headers);
    source.pipe( fs.createWriteStream(options.output+'/'+streamName+'.csv') );
    return source;
  }, {objectMode: true});
} else if (options.output == '-') {
  writeStream = csv.createWriteStream();
  writeStream.pipe( process.stdout );
} else {
  writeStream = csv.createWriteStream();
  writeStream.pipe( fs.createWriteStream(options.output) );
}

readStream.pipe(csv({headers: true, delimiter: options.delimiter}))
  .pipe(grouper(70))
  .pipe(geocoder(options))
  .pipe(writeStream);<|endoftext|>


<commit_before>/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

// Functions which will be available to external callers

var fs = require('fs'),
        util = require('util'),
        readline = require('readline'),
        path = require('path'),
        os  =   require('os')
        downloadUrl = require('./download'),
        manifest = require('./manifest');

;

var IMG_MAXLEVEL = 2;

var walk = function(dir, level, accept, transform) {
    var results = [];

    if( level > IMG_MAXLEVEL ) return results;

    var list = fs.readdirSync(dir);
    list.forEach(function(file) {
        file = path.join(dir,file);
        var stat = fs.statSync(file);
        if (stat && stat.isDirectory()) {
            results = results.concat(walk(file, level+1, accept, transform));
        }
        else {
            if( !accept || accept(file)) {
                results.push( (!transform) ? file : transform(file) );
            }
        }
    });
    return results;
};

var chooseImage = function( folder, callback ) {

    var images = walk(folder, 1,
        function(file) { return path.extname(path.basename(file))==='.png'; },
        function(file) { return path.relative( folder, file ); }

    );

    var index = 0;
    images.forEach( function(file) {

        console.log( util.format( "[%d] %s", index++, file ));
    });

    var rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });

    rl.question(
            "Choose image: ",
            function(answer) {

                var n = parseInt(answer);

                callback(images[n]);

                rl.close();
            });
};

function project(argv) {

        var args = require('minimist')(argv);
        //console.dir(args);

        if (args._.length === 0)
            throw "not enought parameters provided!"

        var processed = false;

        switch (args._[0]) {
            case "open":
                processed = _open(args);
                break;
            case "create":
                processed = _create(args);
                break;
        }

        if (!processed) {
            throw "not right parameters provided!"
        }

        return processed;
}

/*
* > cordova-poc project create --name=<name> --url=<url> [--output=<output parent folder>]
*/
function _create(args) {

        if (!args.name)
            throw "no name provided!"
        if (!args.url)
            throw "no url provided!"

		var ourdir = path.join( (args.o)?args.o:'',
                        (args.output)?args.output:'',
                        path.basename(args.name) );

        downloadUrl( args.url,  ourdir );

        return true;
}

/*
* > cordova-poc project open --path=<project path>
*                   [--zip]
*                   [--output=<zip output folder>]
*                   [--set-name=<poc name>]
*                   [--set-icon]
*                   [--set-version=<version number>]
*
*/
function _open(args) {

        if (!args.path)
            throw "no path provided!"

        var stats = fs.lstatSync( args.path );

        if( !stats.isDirectory() )
            throw  util.format( "path %s doesn't exist!", args.path );

        process.chdir( args.path );

        var update = false;

        var finalize = function(o) {

            console.log( "MANIFEST:" );
            console.dir( o );

            if(updated) {
                manifest.createMF( JSON.stringify(o) );
            }

            if( args.zip )
                _makeZip( args );

        } ;
        manifest.readOrCreateMF(function(content) {
                var o = JSON.parse( content );

                console.dir( o );

                if( args['set-name'] ) {
                    updated = true;
                    o.name = args['set-name'];
                }
                if( args['set-version'] ) {
                    updated = true;
                    o.cordova = args['set-version'];
                }
                if( args['set-icon'] ) {
                    updated = true;
                    chooseImage(args.path, function(icon) {

                        if( icon ) o.icon = icon;

                        finalize(o);
                    });
                }
                else {
                    finalize(o);
                }

        });

        //console.dir(args);

        return true;
}

/**
 *
 * @param {string} folder description
 * @param {string} target description
*/
function ZIPIT( folder, target )
{
        var archiver = require('archiver');

        var output = fs.createWriteStream(target);
        var archive = archiver('zip');

        output.on('close', function() {
          console.log(archive.pointer() + ' total bytes');
          console.log('archiver has been finalized and the output file descriptor has closed.');
        });

        archive.on('error', function(err) {
          throw err;
        });

        archive.pipe(output);

        archive.bulk([
                { expand: true, cwd: folder, src: ['**/*.*'] }
        ]);

        archive.finalize();

}

/**
 *
 * @param {object} args arguments
 *
*/
function _makeZip( args ) {

        console.log( "ZIPPING" );

        ZIPIT( args.path,
            path.join( (args.o)?args.o:'',
                        (args.output)?args.output:'',
                        path.basename(args.path) + ".zip" ));
}

module.exports = project;
<commit_msg>source format<commit_after>/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

// Functions which will be available to external callers

var fs = require('fs'),
        util = require('util'),
        readline = require('readline'),
        path = require('path'),
        os  =   require('os')
        downloadUrl = require('./download'),
        manifest = require('./manifest');

;

var IMG_MAXLEVEL = 2;

var walk = function(dir, level, accept, transform) {
    var results = [];

    if( level > IMG_MAXLEVEL ) return results;

    var list = fs.readdirSync(dir);
    list.forEach(function(file) {
        file = path.join(dir,file);
        var stat = fs.statSync(file);
        if (stat && stat.isDirectory()) {
            results = results.concat(walk(file, level+1, accept, transform));
        }
        else {
            if( !accept || accept(file)) {
                results.push( (!transform) ? file : transform(file) );
            }
        }
    });
    return results;
};

var chooseImage = function( folder, callback ) {

    var images = walk(folder, 1,
        function(file) { return path.extname(path.basename(file))==='.png'; },
        function(file) { return path.relative( folder, file ); }

    );

    var index = 0;
    images.forEach( function(file) {

        console.log( util.format( "[%d] %s", index++, file ));
    });

    var rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });

    rl.question(
            "Choose image: ",
            function(answer) {

                var n = parseInt(answer);

                callback(images[n]);

                rl.close();
            });
};

function project(argv) {

        var args = require('minimist')(argv);
        //console.dir(args);

        if (args._.length === 0)
            throw "not enought parameters provided!"

        var processed = false;

        switch (args._[0]) {
            case "open":
                processed = _open(args);
                break;
            case "create":
                processed = _create(args);
                break;
        }

        if (!processed) {
            throw "not right parameters provided!";
        }

        return processed;
}

/*
* > cordova-poc project create --name=<name> --url=<url> [--output=<output parent folder>]
*/
function _create(args) {

        if (!args.name)
            throw "no name provided!";
        if (!args.url)
            throw "no url provided!";

		var outdir = path.join( (args.o)?args.o:'',
                        (args.output)?args.output:'',
                        path.basename(args.name) );

        downloadUrl( args.url,  outdir );

        return true;
}

/*
* > cordova-poc project open --path=<project path>
*                   [--zip]
*                   [--output=<zip output folder>]
*                   [--set-name=<poc name>]
*                   [--set-icon]
*                   [--set-version=<version number>]
*
*/
function _open(args) {

        if (!args.path)
            throw "no path provided!";

        var stats = fs.lstatSync( args.path );

        if( !stats.isDirectory() )
            throw  util.format( "path %s doesn't exist!", args.path );

        process.chdir( args.path );

        var updated = false;

        var finalize = function(o) {

            console.log( "MANIFEST:" );
            console.dir( o );

            if(updated) {
                manifest.createMF( JSON.stringify(o) );
            }

            if( args.zip )
                _makeZip( args );

        } ;
        manifest.readOrCreateMF(function(content) {
                var o = JSON.parse( content );

                console.dir( o );

                if( args['set-name'] ) {
                    updated = true;
                    o.name = args['set-name'];
                }
                if( args['set-version'] ) {
                    updated = true;
                    o.cordova = args['set-version'];
                }
                if( args['set-icon'] ) {
                    updated = true;
                    chooseImage(args.path, function(icon) {

                        if( icon ) o.icon = icon;

                        finalize(o);
                    });
                }
                else {
                    finalize(o);
                }

        });

        //console.dir(args);

        return true;
}

/**
 *
 * @param {string} folder description
 * @param {string} target description
*/
function ZIPIT( folder, target )
{
        var archiver = require('archiver');

        var output = fs.createWriteStream(target);
        var archive = archiver('zip');

        output.on('close', function() {
          console.log(archive.pointer() + ' total bytes');
          console.log('archiver has been finalized and the output file descriptor has closed.');
        });

        archive.on('error', function(err) {
          throw err;
        });

        archive.pipe(output);

        archive.bulk([
                { expand: true, cwd: folder, src: ['**/*.*'] }
        ]);

        archive.finalize();

}

/**
 *
 * @param {object} args arguments
 *
*/
function _makeZip( args ) {

        console.log( "ZIPPING" );

        ZIPIT( args.path,
            path.join( (args.o)?args.o:'',
                        (args.output)?args.output:'',
                        path.basename(args.path) + ".zip" ));
}

module.exports = project;
<|endoftext|>


<commit_before>/*!
  backbone.fetch-cache v0.1.0
  by Andy Appleton - https://github.com/mrappleton/backbone-fetch-cache.git
 */

(function() {
  // Setup
  var modelFetch = Backbone.Model.prototype.fetch,
      collectionFetch = Backbone.Collection.prototype.fetch,
      supportLocalStorage = typeof window.localStorage !== 'undefined';

  Backbone.fetchCache = (Backbone.fetchCache || {});
  Backbone.fetchCache._cache = (Backbone.fetchCache._cache || {});

  if (typeof Backbone.fetchCache.localStorage === 'undefined') {
    Backbone.fetchCache.localStorage = true;
  }

  // Shared methods
  function setCache(instance, opts) {
    opts = (opts || {});
    var url = _.isFunction(instance.url) ? instance.url() : instance.url,
        expires = false;

    // need url to use as cache key so return if we can't get it
    if (!url) { return; }

    if (opts.expires !== false) {
      expires = (new Date()).getTime() + ((opts.expires || 5 * 60) * 1000);
    }

    Backbone.fetchCache._cache[url] = {
      expires: expires,
      value: instance.toJSON()
    };

    Backbone.fetchCache.setLocalStorage();
  }

  function setLocalStorage() {
    if (!supportLocalStorage || !Backbone.fetchCache.localStorage) { return; }
    localStorage.setItem('backboneCache', JSON.stringify(Backbone.fetchCache._cache));
  }

  function getLocalStorage() {
    if (!supportLocalStorage || !Backbone.fetchCache.localStorage) { return; }
    Backbone.fetchCache._cache = JSON.parse(localStorage.getItem('backboneCache')) || {};
  }

  // Instance methods
  Backbone.Model.prototype.fetch = function(opts) {
    opts = (opts || {});
    var url = _.isFunction(this.url) ? this.url() : this.url,
        data = Backbone.fetchCache._cache[url],
        expired = false,
        attributes = false;

    if (data) {
      expired = data.expires;
      expired = expired && data.expires < (new Date()).getTime();
      attributes = data.value;
    }

    if (!expired && opts.cache && attributes) {
      this.set(attributes, opts);
      if (_.isFunction(opts.success)) { opts.success(this); }
      // Mimic actual fetch behaviour buy returning a fulfilled promise
      return ( new $.Deferred() ).resolve(this);
    }

    // Delegate to the actual fetch method and store the attibutes in the cache
    return modelFetch.apply(this, arguments).done(
      _.bind(Backbone.fetchCache.setCache, null, this, opts)
    );
  };

  Backbone.Collection.prototype.fetch = function(opts) {
    opts = (opts || {});
    var url = _.isFunction(this.url) ? this.url() : this.url,
        data = Backbone.fetchCache._cache[url],
        expired = false,
        attributes = false;

    if (data) {
      expired = data.expires;
      expired = expired && data.expires < (new Date()).getTime();
      attributes = data.value;
    }

    if (!expired && opts.cache && attributes) {
      this[opts.add ? 'add' : 'reset'](this.parse(attributes), opts);
      if (_.isFunction(opts.success)) { opts.success(this); }
      // Mimic actual fetch behaviour buy returning a fulfilled promise
      return ( new $.Deferred() ).resolve(this);
    }

    // Delegate to the actual fetch method and store the attibutes in the cache
    return collectionFetch.apply(this, arguments).done(
      _.bind(Backbone.fetchCache.setCache, null, this, opts)
    );
  };

  // Prime the cache from localStorage on initialization
  getLocalStorage();

  // Exports
  Backbone.fetchCache.setCache = setCache;
  Backbone.fetchCache.setLocalStorage = setLocalStorage;
  Backbone.fetchCache.getLocalStorage = getLocalStorage;
})();
<commit_msg>Another typo<commit_after>/*!
  backbone.fetch-cache v0.1.0
  by Andy Appleton - https://github.com/mrappleton/backbone-fetch-cache.git
 */

(function() {
  // Setup
  var modelFetch = Backbone.Model.prototype.fetch,
      collectionFetch = Backbone.Collection.prototype.fetch,
      supportLocalStorage = typeof window.localStorage !== 'undefined';

  Backbone.fetchCache = (Backbone.fetchCache || {});
  Backbone.fetchCache._cache = (Backbone.fetchCache._cache || {});

  if (typeof Backbone.fetchCache.localStorage === 'undefined') {
    Backbone.fetchCache.localStorage = true;
  }

  // Shared methods
  function setCache(instance, opts) {
    opts = (opts || {});
    var url = _.isFunction(instance.url) ? instance.url() : instance.url,
        expires = false;

    // need url to use as cache key so return if we can't get it
    if (!url) { return; }

    if (opts.expires !== false) {
      expires = (new Date()).getTime() + ((opts.expires || 5 * 60) * 1000);
    }

    Backbone.fetchCache._cache[url] = {
      expires: expires,
      value: instance.toJSON()
    };

    Backbone.fetchCache.setLocalStorage();
  }

  function setLocalStorage() {
    if (!supportLocalStorage || !Backbone.fetchCache.localStorage) { return; }
    localStorage.setItem('backboneCache', JSON.stringify(Backbone.fetchCache._cache));
  }

  function getLocalStorage() {
    if (!supportLocalStorage || !Backbone.fetchCache.localStorage) { return; }
    Backbone.fetchCache._cache = JSON.parse(localStorage.getItem('backboneCache')) || {};
  }

  // Instance methods
  Backbone.Model.prototype.fetch = function(opts) {
    opts = (opts || {});
    var url = _.isFunction(this.url) ? this.url() : this.url,
        data = Backbone.fetchCache._cache[url],
        expired = false,
        attributes = false;

    if (data) {
      expired = data.expires;
      expired = expired && data.expires < (new Date()).getTime();
      attributes = data.value;
    }

    if (!expired && opts.cache && attributes) {
      this.set(attributes, opts);
      if (_.isFunction(opts.success)) { opts.success(this); }
      // Mimic actual fetch behaviour buy returning a fulfilled promise
      return ( new $.Deferred() ).resolve(this);
    }

    // Delegate to the actual fetch method and store the attributes in the cache
    return modelFetch.apply(this, arguments).done(
      _.bind(Backbone.fetchCache.setCache, null, this, opts)
    );
  };

  Backbone.Collection.prototype.fetch = function(opts) {
    opts = (opts || {});
    var url = _.isFunction(this.url) ? this.url() : this.url,
        data = Backbone.fetchCache._cache[url],
        expired = false,
        attributes = false;

    if (data) {
      expired = data.expires;
      expired = expired && data.expires < (new Date()).getTime();
      attributes = data.value;
    }

    if (!expired && opts.cache && attributes) {
      this[opts.add ? 'add' : 'reset'](this.parse(attributes), opts);
      if (_.isFunction(opts.success)) { opts.success(this); }
      // Mimic actual fetch behaviour buy returning a fulfilled promise
      return ( new $.Deferred() ).resolve(this);
    }

    // Delegate to the actual fetch method and store the attributes in the cache
    return collectionFetch.apply(this, arguments).done(
      _.bind(Backbone.fetchCache.setCache, null, this, opts)
    );
  };

  // Prime the cache from localStorage on initialization
  getLocalStorage();

  // Exports
  Backbone.fetchCache.setCache = setCache;
  Backbone.fetchCache.setLocalStorage = setLocalStorage;
  Backbone.fetchCache.getLocalStorage = getLocalStorage;
})();
<|endoftext|>


<commit_before>'use strict';
(function(root) {
    /****************************
     Public Constructor
     ****************************/

    function Promise(resolver) {
        var promise = new PendingPromise();
        var self = this;

        this.then = function then(onFulfilled, onRejected) {
            var deferred = new Deferred(self.constructor);
            return promise.resolve(
                deferred,
                isFunction(onFulfilled) ? onFulfilled : deferred.resolve,
                isFunction(onRejected) ? onRejected : deferred.reject,
                self
            );
        };

        var _reject = function reject() {
            _resolve = _reject = noop;
            var reasons = toArray.apply(void 0, arguments);
            var p = new RejectedPromise(reasons);
            promise.resolveQueued(p);
            promise = p;
        };
        var _resolve = function resolve() {
            var deferred = {
                promise: self,
                reject: _reject,
                resolve: function resolve() {
                    var values = toArray.apply(void 0, arguments);
                    var p = new FulfilledPromise(values);
                    promise.resolveQueued(p);
                    promise = p;
                }
            };
            _resolve = _reject = noop;
            doResolve.apply(deferred, arguments);
        };

        tryCatchResolver(resolver, function resolve() {
            apply(_resolve, arguments);
        }, function reject() {
            apply(_reject, arguments);
        });
    }

    /****************************
     Public Instance Methods
     ****************************/

    Promise.prototype.catch = function(onRejected) {
        return this.then(void 0, onRejected);
    };

    Promise.prototype.throw = function() {
        return this.catch(function(error) {
            // Defer it, so our promise doesn't catch
            // it and turn it into a rejected promise.
            defer(function() {
                throw error;
            });

            throw error;
        });
    };

    /****************************
     Public Static Methods
     ****************************/

    Promise.resolve = function resolve(obj) {
        if (isObject(obj) && obj.constructor === this) {
            return obj;
        }

        var values = toArray.apply(void 0, arguments);
        return new this(function(resolve) {
            resolve.apply(void 0, values);
        });
    };

    Promise.reject = function reject() {
        var reasons = toArray.apply(void 0, arguments);
        return new this(function(_, reject) {
            reject.apply(void 0, reasons);
        });
    };

    Promise.deferred = function deferred() {
        return new Deferred(this);
    };

    Promise.all = function all(promises) {
        var Constructor = this;
        return new Constructor(function(resolve, reject) {
            var l = promises.length;
            var values = new Array(l);
            var times = l;

            if (times === 0) {
                return resolve(values);
            }
            var resolveAfter = function() {
                if (--times === 0) { resolve(values); }
            };

            for (var i = 0; i < l; i++) {
                Constructor.resolve(promises[i]).then(fillSlot(values, i, resolveAfter), reject);
            }
        });
    };

    Promise.race = function race(promises) {
        var Constructor = this;
        return new Constructor(function(resolve, reject) {
            for (var i = 0, l = promises.length; i < l; i++) {
                Constructor.resolve(promises[i]).then(resolve, reject);
            }
        });
    };

    /****************************
      Private functions
     ****************************/

    function Deferred(Promise) {
        var deferred = this;
        this.promise = new Promise(function(resolve, reject) {
            deferred.resolve = resolve;
            deferred.reject = reject;
        });
    }

    function FulfilledPromise(values) {
        this.values = values;
    }
    FulfilledPromise.prototype.resolve = function(deferred, onFulfilled, _, previous) {
        if (!onFulfilled) { return previous; }
        defer(tryCatchDeferred(deferred, onFulfilled, this.values));
        return deferred.promise;
    };

    function RejectedPromise(reasons) {
        this.reasons = reasons;
    }
    RejectedPromise.prototype.resolve = function(deferred, _, onRejected, previous) {
        if (!onRejected) { return previous; }
        defer(tryCatchDeferred(deferred, onRejected, this.reasons));
        return deferred.promise;
    };

    function PendingPromise() {
        this.queue = [];
    }
    PendingPromise.prototype.resolve = function(deferred, onFulfilled, onRejected) {
        this.queue.push({
            deferred: deferred,
            onFulfilled: onFulfilled,
            onRejected: onRejected
        });
        return deferred.promise;
    };
    PendingPromise.prototype.resolveQueued = function(promise) {
        var queue = this.queue;
        for (var i = 0, l = queue.length; i < l; i++) {
            var next = queue[i];
            promise.resolve(next.deferred, next.onFulfilled, next.onRejected);
        }
    };

    function noop() {}
    function isFunction(fn) {
        return typeof fn === 'function';
    }
    function isObject(obj) {
        return obj && (typeof obj === 'object' || typeof obj === 'function');
    }
    function fillSlot(array, index, fn) {
        return function(value) {
            array[index] = value;
            if (fn) { fn(); }
        };
    }
    function toArray() {
        var l = arguments.length;
        var array = new Array(l);
        for (var i = 0; i < l; i++) {
            array[i] = arguments[i];
        }
        return array;
    }
    function tryCatchResolver(resolver, resolve, reject) {
        try {
            resolver(resolve, reject);
        } catch (e) {
            reject(e);
        }
    }
    function tryCatchDeferred(deferred, fn, args) {
        return function() {
            try {
                var result = fn.apply(void 0, args);
                if (deferred.resolve === fn || deferred.reject === fn) { return; }
                doResolve.call(deferred, result);
            } catch (e) {
                deferred.reject(e);
            }
        };
    }

    var nextTick = typeof process !== 'undefined' && isFunction(process.nextTick) ? process.nextTick
     : typeof setImmediate !== 'undefined' ? setImmediate
     : function(fn) { setTimeout(fn, 0); };
    var defer = (function() {
        var queue = [];
        var l = 0;
        function flush() {
            for (var i = 0; i < l; i++) {
                queue[i]();
            }
            queue = [];
            l = 0;
        }
        return function defer(fn) {
            l = queue.push(fn);
            if (l === 1) { nextTick(flush); }
        };
    })();

    function doResolve(x) {
        var deferred = this;
        var _reject = deferred.reject;
        var then;
        try {
            if (x === deferred.promise) {
                throw new TypeError('A promise cannot be fulfilled with itself.');
            }
            if (isObject(x) && (then = x.then) && isFunction(then)) {
                var _resolve = function resolvePromise() {
                    _resolve = _reject = noop;
                    doResolve.apply(deferred, arguments);
                };
                _reject = function rejectPromise() {
                    _resolve = _reject = noop;
                    deferred.reject.apply(void 0, arguments);
                };
                then.call(
                    x,
                    function() { _resolve.apply(void 0, arguments); },
                    function() { _reject.apply(void 0, arguments); }
                );
            } else {
                deferred.resolve.apply(void 0, arguments);
            }
        } catch (e) {
            _reject(e);
        }
    }

    if (typeof exports !== 'undefined') {
        if (typeof module !== 'undefined' && module.exports) {
            exports = module.exports = Promise;
        }
        exports.Promise = Promise;
    } else {
        root.Promise = Promise;
    }
})(this);
<commit_msg>Introduce apply() helper<commit_after>'use strict';
(function(root) {
    /****************************
     Public Constructor
     ****************************/

    function Promise(resolver) {
        var promise = new PendingPromise();
        var self = this;

        this.then = function then(onFulfilled, onRejected) {
            var deferred = new Deferred(self.constructor);
            return promise.resolve(
                deferred,
                isFunction(onFulfilled) ? onFulfilled : deferred.resolve,
                isFunction(onRejected) ? onRejected : deferred.reject,
                self
            );
        };

        var _reject = function reject() {
            _resolve = _reject = noop;
            var reasons = toArray.apply(void 0, arguments);
            var p = new RejectedPromise(reasons);
            promise.resolveQueued(p);
            promise = p;
        };
        var _resolve = function resolve() {
            var deferred = {
                promise: self,
                reject: _reject,
                resolve: function resolve() {
                    var values = toArray.apply(void 0, arguments);
                    var p = new FulfilledPromise(values);
                    promise.resolveQueued(p);
                    promise = p;
                }
            };
            _resolve = _reject = noop;
            doResolve.apply(deferred, arguments);
        };

        tryCatchResolver(resolver, function resolve() {
            apply(_resolve, arguments);
        }, function reject() {
            apply(_reject, arguments);
        });
    }

    /****************************
     Public Instance Methods
     ****************************/

    Promise.prototype.catch = function(onRejected) {
        return this.then(void 0, onRejected);
    };

    Promise.prototype.throw = function() {
        return this.catch(function(error) {
            // Defer it, so our promise doesn't catch
            // it and turn it into a rejected promise.
            defer(function() {
                throw error;
            });

            throw error;
        });
    };

    /****************************
     Public Static Methods
     ****************************/

    Promise.resolve = function resolve(obj) {
        if (isObject(obj) && obj.constructor === this) {
            return obj;
        }

        var values = toArray.apply(void 0, arguments);
        return new this(function(resolve) {
            apply(resolve, values);
        });
    };

    Promise.reject = function reject() {
        var reasons = toArray.apply(void 0, arguments);
        return new this(function(_, reject) {
            apply(reject, reasons);
        });
    };

    Promise.deferred = function deferred() {
        return new Deferred(this);
    };

    Promise.all = function all(promises) {
        var Constructor = this;
        return new Constructor(function(resolve, reject) {
            var l = promises.length;
            var values = new Array(l);
            var times = l;

            if (times === 0) {
                return resolve(values);
            }
            var resolveAfter = function() {
                if (--times === 0) { resolve(values); }
            };

            for (var i = 0; i < l; i++) {
                Constructor.resolve(promises[i]).then(fillSlot(values, i, resolveAfter), reject);
            }
        });
    };

    Promise.race = function race(promises) {
        var Constructor = this;
        return new Constructor(function(resolve, reject) {
            for (var i = 0, l = promises.length; i < l; i++) {
                Constructor.resolve(promises[i]).then(resolve, reject);
            }
        });
    };

    /****************************
      Private functions
     ****************************/

    function Deferred(Promise) {
        var deferred = this;
        this.promise = new Promise(function(resolve, reject) {
            deferred.resolve = resolve;
            deferred.reject = reject;
        });
    }

    function FulfilledPromise(values) {
        this.values = values;
    }
    FulfilledPromise.prototype.resolve = function(deferred, onFulfilled, _, previous) {
        if (!onFulfilled) { return previous; }
        defer(tryCatchDeferred(deferred, onFulfilled, this.values));
        return deferred.promise;
    };

    function RejectedPromise(reasons) {
        this.reasons = reasons;
    }
    RejectedPromise.prototype.resolve = function(deferred, _, onRejected, previous) {
        if (!onRejected) { return previous; }
        defer(tryCatchDeferred(deferred, onRejected, this.reasons));
        return deferred.promise;
    };

    function PendingPromise() {
        this.queue = [];
    }
    PendingPromise.prototype.resolve = function(deferred, onFulfilled, onRejected) {
        this.queue.push({
            deferred: deferred,
            onFulfilled: onFulfilled,
            onRejected: onRejected
        });
        return deferred.promise;
    };
    PendingPromise.prototype.resolveQueued = function(promise) {
        var queue = this.queue;
        for (var i = 0, l = queue.length; i < l; i++) {
            var next = queue[i];
            promise.resolve(next.deferred, next.onFulfilled, next.onRejected);
        }
    };

    function noop() {}
    function isFunction(fn) {
        return typeof fn === 'function';
    }
    function isObject(obj) {
        return obj && (typeof obj === 'object' || typeof obj === 'function');
    }
    function fillSlot(array, index, fn) {
        return function(value) {
            array[index] = value;
            if (fn) { fn(); }
        };
    function apply(fn, args) {
        return (args.length > 1) ? fn.apply(void 0, args) : fn(args[0]);
    }
    }
    function toArray() {
        var l = arguments.length;
        var array = new Array(l);
        for (var i = 0; i < l; i++) {
            array[i] = arguments[i];
        }
        return array;
    }
    function tryCatchResolver(resolver, resolve, reject) {
        try {
            resolver(resolve, reject);
        } catch (e) {
            reject(e);
        }
    }
    function tryCatchDeferred(deferred, fn, args) {
        return function() {
            try {
                var result = apply(fn, args);
                if (deferred.resolve === fn || deferred.reject === fn) { return; }
                doResolve.call(deferred, result);
            } catch (e) {
                deferred.reject(e);
            }
        };
    }

    var nextTick = typeof process !== 'undefined' && isFunction(process.nextTick) ? process.nextTick
     : typeof setImmediate !== 'undefined' ? setImmediate
     : function(fn) { setTimeout(fn, 0); };
    var defer = (function() {
        var queue = [];
        var l = 0;
        function flush() {
            for (var i = 0; i < l; i++) {
                queue[i]();
            }
            queue = [];
            l = 0;
        }
        return function defer(fn) {
            l = queue.push(fn);
            if (l === 1) { nextTick(flush); }
        };
    })();

    function doResolve(x) {
        var deferred = this;
        var _reject = deferred.reject;
        var then;
        try {
            if (x === deferred.promise) {
                throw new TypeError('A promise cannot be fulfilled with itself.');
            }
            if (isObject(x) && (then = x.then) && isFunction(then)) {
                var _resolve = function resolvePromise() {
                    _resolve = _reject = noop;
                    doResolve.apply(deferred, arguments);
                };
                _reject = function rejectPromise() {
                    _resolve = _reject = noop;
                    apply(deferred.reject, arguments);
                };
                then.call(
                    x,
                    function() { apply(_resolve, arguments); },
                    function() { apply(_reject, arguments); }
                );
            } else {
                apply(deferred.resolve, arguments);
            }
        } catch (e) {
            _reject(e);
        }
    }

    if (typeof exports !== 'undefined') {
        if (typeof module !== 'undefined' && module.exports) {
            exports = module.exports = Promise;
        }
        exports.Promise = Promise;
    } else {
        root.Promise = Promise;
    }
})(this);
<|endoftext|>


<commit_before>/*!
Copyright 2013 Yahoo! Inc. All rights reserved.
Licensed under the BSD License.
http://yuilibrary.com/license/
*/

/*jslint expr: true */
/*global define */

(function (global, factory) {
    var built = factory();
    /* istanbul ignore else */
    if (typeof module === 'object' && module) {
        module.exports = built;
    }
    /* istanbul ignore next */
    if (typeof define === 'function' && define.amd) {
        define(factory);
    }
    global.PromisePolyfill = built;
    global.Promise || (global.Promise = built);
}(typeof global !== 'undefined' ? global : /* istanbul ignore next */ this, function () {

    function isArray(obj) {
        return Object.prototype.toString.call(obj) === '[object Array]';
    }

    function assign(obj, props) {
        for (var prop in props) {
            /* istanbul ignore else */
            if (props.hasOwnProperty(prop)) {
                obj[prop] = props[prop];
            }
        }
    }

    /**
    A promise represents a value that may not yet be available. Promises allow
    you to chain asynchronous operations, write synchronous looking code and
    handle errors throughout the process.

    This constructor takes a function as a parameter where you can insert the logic
    that fulfills or rejects this promise. The fulfillment value and the rejection
    reason can be any JavaScript value. It's encouraged that rejection reasons be
    error objects

    var fulfilled = new Promise(function (resolve) {
        resolve('I am a fulfilled promise');
    });

    var rejected = new Promise(function (resolve, reject) {
        reject(new Error('I am a rejected promise'));
    });

    @class Promise
    @constructor
    @param {Function} fn A function where to insert the logic that resolves this
            promise. Receives `resolve` and `reject` functions as parameters.
            This function is called synchronously.
    **/
    function Promise(fn) {
        if (!(this instanceof Promise)) {
            throw new TypeError(this + 'is not a promise');
        }
        if (typeof fn !== 'function') {
            throw new TypeError('Promise resolver ' + fn + ' is not a function');
        }

        var resolver = new Resolver();

        /**
        A reference to the resolver object that handles this promise

        @property _resolver
        @type Object
        @private
        */
        this._resolver = resolver;

        try {
            fn(function (value) {
                resolver.resolve(value);
            }, function (reason) {
                resolver.reject(reason);
            });
        } catch (e) {
            resolver.reject(e);
        }
    }

    assign(Promise.prototype, {
        /**
        Schedule execution of a callback to either or both of "fulfill" and
        "reject" resolutions for this promise. The callbacks are wrapped in a new
        promise and that promise is returned.  This allows operation chaining ala
        `functionA().then(functionB).then(functionC)` where `functionA` returns
        a promise, and `functionB` and `functionC` _may_ return promises.

        Asynchronicity of the callbacks is guaranteed.

        @method then
        @param {Function} [callback] function to execute if the promise
                    resolves successfully
        @param {Function} [errback] function to execute if the promise
                    resolves unsuccessfully
        @return {Promise} A promise wrapping the resolution of either "resolve" or
                    "reject" callback
        **/
        then: function (callback, errback) {
            // using this.constructor allows for customized promises to be
            // returned instead of plain ones
            var resolve, reject,
                promise = new this.constructor(function (res, rej) {
                    resolve = res;
                    reject = rej;
                });

            this._resolver._addCallbacks(
                typeof callback === 'function' ?
                    Promise._makeCallback(promise, resolve, reject, callback) : resolve,
                typeof errback === 'function' ?
                    Promise._makeCallback(promise, resolve, reject, errback) : reject
            );

            return promise;
        },

        /*
        A shorthand for `promise.then(undefined, callback)`.

        Returns a new promise and the error callback gets the same treatment as in
        `then`: errors get caught and turned into rejections, and the return value
        of the callback becomes the fulfilled value of the returned promise.

        @method catch
        @param [Function] errback Callback to be called in case this promise is
                            rejected
        @return {Promise} A new promise modified by the behavior of the error
                            callback
        */
        'catch': function (errback) {
            return this.then(undefined, errback);
        }
    });

    /**
    Wraps the callback in another function to catch exceptions and turn them
    into rejections.

    @method _makeCallback
    @param {Promise} promise Promise that will be affected by this callback
    @param {Function} fn Callback to wrap
    @return {Function}
    @static
    @private
    **/
    Promise._makeCallback = function (promise, resolve, reject, fn) {
        // callbacks and errbacks only get one argument
        return function (valueOrReason) {
            var result;

            // Promises model exception handling through callbacks
            // making both synchronous and asynchronous errors behave
            // the same way
            try {
                // Use the argument coming in to the callback/errback from the
                // resolution of the parent promise.
                // The function must be called as a normal function, with no
                // special value for |this|, as per Promises A+
                result = fn(valueOrReason);
            } catch (e) {
                // calling return only to stop here
                reject(e);
                return;
            }

            if (result === promise) {
                reject(new TypeError('Cannot resolve a promise with itself'));
                return;
            }

            resolve(result);
        };
    };

    /**
    Logs a message. This method is designed to be overwritten with  YUI's `log`
    function.

    @method _log
    @param {String} msg Message to log
    @param {String} type Log level. One of 'error', 'warn', 'info'.
    @static
    @private
    **/
    Promise._log = function (msg, type) { /* istanbul ignore else */ if (typeof console !== 'undefined') { console[type](msg); } };

    /*
    Ensures that a certain value is a promise. If it is not a promise, it wraps it
    in one.

    This method can be copied or inherited in subclasses. In that case it will
    check that the value passed to it is an instance of the correct class.
    This means that `PromiseSubclass.resolve()` will always return instances of
    `PromiseSubclass`.

    @method resolve
    @param {Any} Any object that may or may not be a promise
    @return {Promise}
    @static
    */
    Promise.resolve = function (value) {
        if (value && value.constructor === this) {
            return value;
        }
        /*jshint newcap: false */
        return new this(function (resolve) {
        /*jshint newcap: true */
            resolve(value);
        });
    };

    /*
    A shorthand for creating a rejected promise.

    @method reject
    @param {Any} reason Reason for the rejection of this promise. Usually an Error
        Object
    @return {Promise} A rejected promise
    @static
    */
    Promise.reject = function (reason) {
        /*jshint newcap: false */
        var promise = new this(function () {});
       /*jshint newcap: true */

       // Do not go through resolver.reject() because an immediately rejected promise
       // always has no callbacks which would trigger an unnecessary warning
       promise._resolver._result = reason;
       promise._resolver._status = 'rejected';

       return promise;
    };

    /*
    Returns a promise that is resolved or rejected when all values are resolved or
    any is rejected. This is useful for waiting for the resolution of multiple
    promises, such as reading multiple files in Node.js or making multiple XHR
    requests in the browser.

    @method all
    @param {Any[]} values An array of any kind of values, promises or not. If a value is not
    @return [Promise] A promise for an array of all the fulfillment values
    @static
    */
    Promise.all = function (values) {
        var Promise = this;
        return new Promise(function (resolve, reject) {
            if (!isArray(values)) {
                reject(new TypeError('Promise.all expects an array of values or promises'));
                return;
            }

            var remaining = values.length,
                i         = 0,
                length    = values.length,
                results   = [];

            function oneDone(index) {
                return function (value) {
                    results[index] = value;

                    remaining--;

                    if (!remaining) {
                        resolve(results);
                    }
                };
            }

            if (length < 1) {
                return resolve(results);
            }

            for (; i < length; i++) {
                Promise.resolve(values[i]).then(oneDone(i), reject);
            }
        });
    };

    /*
    Returns a promise that is resolved or rejected when any of values is either
    resolved or rejected. Can be used for providing early feedback in the UI
    while other operations are still pending.

    @method race
    @param {Any[]} values An array of values or promises
    @return {Promise}
    @static
    */
    Promise.race = function (values) {
        var Promise = this;
        return new Promise(function (resolve, reject) {
            if (!isArray(values)) {
                reject(new TypeError('Promise.race expects an array of values or promises'));
                return;
            }

            // just go through the list and resolve and reject at the first change
            // This abuses the fact that calling resolve/reject multiple times
            // doesn't change the state of the returned promise
            for (var i = 0, count = values.length; i < count; i++) {
                Promise.resolve(values[i]).then(resolve, reject);
            }
        });
    };

    /**
    Forces a function to be run asynchronously, but as fast as possible. In Node.js
    this is achieved using `setImmediate` or `process.nextTick`. In YUI this is
    replaced with `Y.soon`.

    @method async
    @param {Function} callback The function to call asynchronously
    @static
    **/
    /* istanbul ignore next */
    Promise.async = typeof setImmediate !== 'undefined' ?
                        function (fn) {setImmediate(fn);} :
                    typeof process !== 'undefined' && process.nextTick ?
                        process.nextTick :
                    function (fn) {setTimeout(fn, 0);};

    /**
    Represents an asynchronous operation. Provides a
    standard API for subscribing to the moment that the operation completes either
    successfully (`fulfill()`) or unsuccessfully (`reject()`).

    @class Promise.Resolver
    @constructor
    **/
    function Resolver() {
        /**
        List of success callbacks

        @property _callbacks
        @type Array
        @private
        **/
        this._callbacks = [];

        /**
        List of failure callbacks

        @property _errbacks
        @type Array
        @private
        **/
        this._errbacks = [];

        /**
        The status of the operation. This property may take only one of the following
        values: 'pending', 'fulfilled' or 'rejected'.

        @property _status
        @type String
        @default 'pending'
        @private
        **/
        this._status = 'pending';

        /**
        This value that this promise represents.

        @property _result
        @type Any
        @private
        **/
        this._result = null;
    }

    assign(Resolver.prototype, {
        /**
        Resolves the promise, signaling successful completion of the
        represented operation. All "onFulfilled" subscriptions are executed and passed
        the value provided to this method. After calling `fulfill()`, `reject()` and
        `notify()` are disabled.

        @method fulfill
        @param {Any} value Value to pass along to the "onFulfilled" subscribers
        **/
        fulfill: function (value) {
            var status = this._status;

            if (status === 'pending' || status === 'accepted') {
                this._result = value;
                this._status = 'fulfilled';
            }

            if (this._status === 'fulfilled') {
                this._notify(this._callbacks, this._result);

                // Reset the callback list so that future calls to fulfill()
                // won't call the same callbacks again. Promises keep a list
                // of callbacks, they're not the same as events. In practice,
                // calls to fulfill() after the first one should not be made by
                // the user but by then()
                this._callbacks = [];

                // Once a promise gets fulfilled it can't be rejected, so
                // there is no point in keeping the list. Remove it to help
                // garbage collection
                this._errbacks = null;
            }
        },

        /**
        Resolves the promise, signaling *un*successful completion of the
        represented operation. All "onRejected" subscriptions are executed with
        the value provided to this method. After calling `reject()`, `resolve()`
        and `notify()` are disabled.

        @method reject
        @param {Any} reason Value to pass along to the "reject" subscribers
        **/
        reject: function (reason) {
            var status = this._status;

            if (status === 'pending' || status === 'accepted') {
                this._result = reason;
                this._status = 'rejected';
                if (!this._errbacks.length) {Promise._log('Promise rejected but no error handlers were registered to it', 'info');}
            }

            if (this._status === 'rejected') {
                this._notify(this._errbacks, this._result);

                // See fulfill()
                this._callbacks = null;
                this._errbacks = [];
            }
        },

        /*
        Given a certain value A passed as a parameter, this method resolves the
        promise to the value A.

        If A is a promise, `resolve` will cause the resolver to adopt the state of A
        and once A is resolved, it will resolve the resolver's promise as well.
        This behavior "flattens" A by calling `then` recursively and essentially
        disallows promises-for-promises.

        This is the default algorithm used when using the function passed as the
        first argument to the promise initialization function. This means that
        the following code returns a promise for the value 'hello world':

            var promise1 = new Promise(function (resolve) {
                resolve('hello world');
            });
            var promise2 = new Promise(function (resolve) {
                resolve(promise1);
            });
            promise2.then(function (value) {
                assert(value === 'hello world'); // true
            });

        @method resolve
        @param [Any] value A regular JS value or a promise
        */
        resolve: function (value) {
            if (this._status === 'pending') {
                this._status = 'accepted';
                this._value = value;

                if ((this._callbacks && this._callbacks.length) ||
                    (this._errbacks && this._errbacks.length)) {
                    this._unwrap(this._value);
                }
            }
        },

        /**
        If `value` is a promise or a thenable, it will be unwrapped by
        recursively calling its `then` method. If not, the resolver will be
        fulfilled with `value`.

        This method is called when the promise's `then` method is called and
        not in `resolve` to allow for lazy promises to be accepted and not
        resolved immediately.

        @method _unwrap
        @param {Any} value A promise, thenable or regular value
        @private
        **/
        _unwrap: function (value) {
            var self = this, unwrapped = false, then;

            if (!value || (typeof value !== 'object' &&
                typeof value !== 'function')) {
                self.fulfill(value);
                return;
            }

            try {
                then = value.then;

                if (typeof then === 'function') {
                    then.call(value, function (value) {
                        if (!unwrapped) {
                            unwrapped = true;
                            self._unwrap(value);
                        }
                    }, function (reason) {
                        if (!unwrapped) {
                            unwrapped = true;
                            self.reject(reason);
                        }
                    });
                } else {
                    self.fulfill(value);
                }
            } catch (e) {
                if (!unwrapped) {
                    self.reject(e);
                }
            }
        },

        /**
        Schedule execution of a callback to either or both of "resolve" and
        "reject" resolutions of this resolver. If the resolver is not pending,
        the correct callback gets called automatically.

        @method _addCallbacks
        @param {Function} [callback] function to execute if the Resolver
                    resolves successfully
        @param {Function} [errback] function to execute if the Resolver
                    resolves unsuccessfully
        **/
        _addCallbacks: function (callback, errback) {
            var callbackList = this._callbacks,
                errbackList  = this._errbacks;

            // Because the callback and errback are represented by a Resolver, it
            // must be fulfilled or rejected to propagate through the then() chain.
            // The same logic applies to resolve() and reject() for fulfillment.
            if (callbackList) {
                callbackList.push(callback);
            }
            if (errbackList) {
                errbackList.push(errback);
            }

            switch (this._status) {
                case 'accepted':
                    this._unwrap(this._value);
                    break;
                case 'fulfilled':
                    this.fulfill(this._result);
                    break;
                case 'rejected':
                    this.reject(this._result);
                    break;
            }
        },

        /**
        Executes an array of callbacks from a specified context, passing a set of
        arguments.

        @method _notify
        @param {Function[]} subs The array of subscriber callbacks
        @param {Any} result Value to pass the callbacks
        @protected
        **/
        _notify: function (subs, result) {
            // Since callback lists are reset synchronously, the subs list never
            // changes after _notify() receives it. Avoid calling Y.soon() for
            // an empty list
            if (subs.length) {
                // Calling all callbacks after Promise.async to guarantee
                // asynchronicity. Because setTimeout can cause unnecessary
                // delays that *can* become noticeable in some situations
                // (especially in Node.js)
                Promise.async(function () {
                    var i, len;

                    for (i = 0, len = subs.length; i < len; ++i) {
                        subs[i](result);
                    }
                });
            }
        }

    });

    Promise.Resolver = Resolver;

    return Promise;

}));

<commit_msg>Remove logging<commit_after>/*!
Copyright 2013 Yahoo! Inc. All rights reserved.
Licensed under the BSD License.
http://yuilibrary.com/license/
*/

/*jslint expr: true */
/*global define */

(function (global, factory) {
    var built = factory();
    /* istanbul ignore else */
    if (typeof module === 'object' && module) {
        module.exports = built;
    }
    /* istanbul ignore next */
    if (typeof define === 'function' && define.amd) {
        define(factory);
    }
    global.PromisePolyfill = built;
    global.Promise || (global.Promise = built);
}(typeof global !== 'undefined' ? global : /* istanbul ignore next */ this, function () {

    function isArray(obj) {
        return Object.prototype.toString.call(obj) === '[object Array]';
    }

    function assign(obj, props) {
        for (var prop in props) {
            /* istanbul ignore else */
            if (props.hasOwnProperty(prop)) {
                obj[prop] = props[prop];
            }
        }
    }

    /**
    A promise represents a value that may not yet be available. Promises allow
    you to chain asynchronous operations, write synchronous looking code and
    handle errors throughout the process.

    This constructor takes a function as a parameter where you can insert the logic
    that fulfills or rejects this promise. The fulfillment value and the rejection
    reason can be any JavaScript value. It's encouraged that rejection reasons be
    error objects

    var fulfilled = new Promise(function (resolve) {
        resolve('I am a fulfilled promise');
    });

    var rejected = new Promise(function (resolve, reject) {
        reject(new Error('I am a rejected promise'));
    });

    @class Promise
    @constructor
    @param {Function} fn A function where to insert the logic that resolves this
            promise. Receives `resolve` and `reject` functions as parameters.
            This function is called synchronously.
    **/
    function Promise(fn) {
        if (!(this instanceof Promise)) {
            throw new TypeError(this + 'is not a promise');
        }
        if (typeof fn !== 'function') {
            throw new TypeError('Promise resolver ' + fn + ' is not a function');
        }

        var resolver = new Resolver();

        /**
        A reference to the resolver object that handles this promise

        @property _resolver
        @type Object
        @private
        */
        this._resolver = resolver;

        try {
            fn(function (value) {
                resolver.resolve(value);
            }, function (reason) {
                resolver.reject(reason);
            });
        } catch (e) {
            resolver.reject(e);
        }
    }

    assign(Promise.prototype, {
        /**
        Schedule execution of a callback to either or both of "fulfill" and
        "reject" resolutions for this promise. The callbacks are wrapped in a new
        promise and that promise is returned.  This allows operation chaining ala
        `functionA().then(functionB).then(functionC)` where `functionA` returns
        a promise, and `functionB` and `functionC` _may_ return promises.

        Asynchronicity of the callbacks is guaranteed.

        @method then
        @param {Function} [callback] function to execute if the promise
                    resolves successfully
        @param {Function} [errback] function to execute if the promise
                    resolves unsuccessfully
        @return {Promise} A promise wrapping the resolution of either "resolve" or
                    "reject" callback
        **/
        then: function (callback, errback) {
            // using this.constructor allows for customized promises to be
            // returned instead of plain ones
            var resolve, reject,
                promise = new this.constructor(function (res, rej) {
                    resolve = res;
                    reject = rej;
                });

            this._resolver._addCallbacks(
                typeof callback === 'function' ?
                    Promise._makeCallback(promise, resolve, reject, callback) : resolve,
                typeof errback === 'function' ?
                    Promise._makeCallback(promise, resolve, reject, errback) : reject
            );

            return promise;
        },

        /*
        A shorthand for `promise.then(undefined, callback)`.

        Returns a new promise and the error callback gets the same treatment as in
        `then`: errors get caught and turned into rejections, and the return value
        of the callback becomes the fulfilled value of the returned promise.

        @method catch
        @param [Function] errback Callback to be called in case this promise is
                            rejected
        @return {Promise} A new promise modified by the behavior of the error
                            callback
        */
        'catch': function (errback) {
            return this.then(undefined, errback);
        }
    });

    /**
    Wraps the callback in another function to catch exceptions and turn them
    into rejections.

    @method _makeCallback
    @param {Promise} promise Promise that will be affected by this callback
    @param {Function} fn Callback to wrap
    @return {Function}
    @static
    @private
    **/
    Promise._makeCallback = function (promise, resolve, reject, fn) {
        // callbacks and errbacks only get one argument
        return function (valueOrReason) {
            var result;

            // Promises model exception handling through callbacks
            // making both synchronous and asynchronous errors behave
            // the same way
            try {
                // Use the argument coming in to the callback/errback from the
                // resolution of the parent promise.
                // The function must be called as a normal function, with no
                // special value for |this|, as per Promises A+
                result = fn(valueOrReason);
            } catch (e) {
                // calling return only to stop here
                reject(e);
                return;
            }

            if (result === promise) {
                reject(new TypeError('Cannot resolve a promise with itself'));
                return;
            }

            resolve(result);
        };
    };

    /*
    Ensures that a certain value is a promise. If it is not a promise, it wraps it
    in one.

    This method can be copied or inherited in subclasses. In that case it will
    check that the value passed to it is an instance of the correct class.
    This means that `PromiseSubclass.resolve()` will always return instances of
    `PromiseSubclass`.

    @method resolve
    @param {Any} Any object that may or may not be a promise
    @return {Promise}
    @static
    */
    Promise.resolve = function (value) {
        if (value && value.constructor === this) {
            return value;
        }
        /*jshint newcap: false */
        return new this(function (resolve) {
        /*jshint newcap: true */
            resolve(value);
        });
    };

    /*
    A shorthand for creating a rejected promise.

    @method reject
    @param {Any} reason Reason for the rejection of this promise. Usually an Error
        Object
    @return {Promise} A rejected promise
    @static
    */
    Promise.reject = function (reason) {
        /*jshint newcap: false */
        var promise = new this(function () {});
       /*jshint newcap: true */

       // Do not go through resolver.reject() because an immediately rejected promise
       // always has no callbacks which would trigger an unnecessary warning
       promise._resolver._result = reason;
       promise._resolver._status = 'rejected';

       return promise;
    };

    /*
    Returns a promise that is resolved or rejected when all values are resolved or
    any is rejected. This is useful for waiting for the resolution of multiple
    promises, such as reading multiple files in Node.js or making multiple XHR
    requests in the browser.

    @method all
    @param {Any[]} values An array of any kind of values, promises or not. If a value is not
    @return [Promise] A promise for an array of all the fulfillment values
    @static
    */
    Promise.all = function (values) {
        var Promise = this;
        return new Promise(function (resolve, reject) {
            if (!isArray(values)) {
                reject(new TypeError('Promise.all expects an array of values or promises'));
                return;
            }

            var remaining = values.length,
                i         = 0,
                length    = values.length,
                results   = [];

            function oneDone(index) {
                return function (value) {
                    results[index] = value;

                    remaining--;

                    if (!remaining) {
                        resolve(results);
                    }
                };
            }

            if (length < 1) {
                return resolve(results);
            }

            for (; i < length; i++) {
                Promise.resolve(values[i]).then(oneDone(i), reject);
            }
        });
    };

    /*
    Returns a promise that is resolved or rejected when any of values is either
    resolved or rejected. Can be used for providing early feedback in the UI
    while other operations are still pending.

    @method race
    @param {Any[]} values An array of values or promises
    @return {Promise}
    @static
    */
    Promise.race = function (values) {
        var Promise = this;
        return new Promise(function (resolve, reject) {
            if (!isArray(values)) {
                reject(new TypeError('Promise.race expects an array of values or promises'));
                return;
            }

            // just go through the list and resolve and reject at the first change
            // This abuses the fact that calling resolve/reject multiple times
            // doesn't change the state of the returned promise
            for (var i = 0, count = values.length; i < count; i++) {
                Promise.resolve(values[i]).then(resolve, reject);
            }
        });
    };

    /**
    Forces a function to be run asynchronously, but as fast as possible. In Node.js
    this is achieved using `setImmediate` or `process.nextTick`. In YUI this is
    replaced with `Y.soon`.

    @method async
    @param {Function} callback The function to call asynchronously
    @static
    **/
    /* istanbul ignore next */
    Promise.async = typeof setImmediate !== 'undefined' ?
                        function (fn) {setImmediate(fn);} :
                    typeof process !== 'undefined' && process.nextTick ?
                        process.nextTick :
                    function (fn) {setTimeout(fn, 0);};

    /**
    Represents an asynchronous operation. Provides a
    standard API for subscribing to the moment that the operation completes either
    successfully (`fulfill()`) or unsuccessfully (`reject()`).

    @class Promise.Resolver
    @constructor
    **/
    function Resolver() {
        /**
        List of success callbacks

        @property _callbacks
        @type Array
        @private
        **/
        this._callbacks = [];

        /**
        List of failure callbacks

        @property _errbacks
        @type Array
        @private
        **/
        this._errbacks = [];

        /**
        The status of the operation. This property may take only one of the following
        values: 'pending', 'fulfilled' or 'rejected'.

        @property _status
        @type String
        @default 'pending'
        @private
        **/
        this._status = 'pending';

        /**
        This value that this promise represents.

        @property _result
        @type Any
        @private
        **/
        this._result = null;
    }

    assign(Resolver.prototype, {
        /**
        Resolves the promise, signaling successful completion of the
        represented operation. All "onFulfilled" subscriptions are executed and passed
        the value provided to this method. After calling `fulfill()`, `reject()` and
        `notify()` are disabled.

        @method fulfill
        @param {Any} value Value to pass along to the "onFulfilled" subscribers
        **/
        fulfill: function (value) {
            var status = this._status;

            if (status === 'pending' || status === 'accepted') {
                this._result = value;
                this._status = 'fulfilled';
            }

            if (this._status === 'fulfilled') {
                this._notify(this._callbacks, this._result);

                // Reset the callback list so that future calls to fulfill()
                // won't call the same callbacks again. Promises keep a list
                // of callbacks, they're not the same as events. In practice,
                // calls to fulfill() after the first one should not be made by
                // the user but by then()
                this._callbacks = [];

                // Once a promise gets fulfilled it can't be rejected, so
                // there is no point in keeping the list. Remove it to help
                // garbage collection
                this._errbacks = null;
            }
        },

        /**
        Resolves the promise, signaling *un*successful completion of the
        represented operation. All "onRejected" subscriptions are executed with
        the value provided to this method. After calling `reject()`, `resolve()`
        and `notify()` are disabled.

        @method reject
        @param {Any} reason Value to pass along to the "reject" subscribers
        **/
        reject: function (reason) {
            var status = this._status;

            if (status === 'pending' || status === 'accepted') {
                this._result = reason;
                this._status = 'rejected';
            }

            if (this._status === 'rejected') {
                this._notify(this._errbacks, this._result);

                // See fulfill()
                this._callbacks = null;
                this._errbacks = [];
            }
        },

        /*
        Given a certain value A passed as a parameter, this method resolves the
        promise to the value A.

        If A is a promise, `resolve` will cause the resolver to adopt the state of A
        and once A is resolved, it will resolve the resolver's promise as well.
        This behavior "flattens" A by calling `then` recursively and essentially
        disallows promises-for-promises.

        This is the default algorithm used when using the function passed as the
        first argument to the promise initialization function. This means that
        the following code returns a promise for the value 'hello world':

            var promise1 = new Promise(function (resolve) {
                resolve('hello world');
            });
            var promise2 = new Promise(function (resolve) {
                resolve(promise1);
            });
            promise2.then(function (value) {
                assert(value === 'hello world'); // true
            });

        @method resolve
        @param [Any] value A regular JS value or a promise
        */
        resolve: function (value) {
            if (this._status === 'pending') {
                this._status = 'accepted';
                this._value = value;

                if ((this._callbacks && this._callbacks.length) ||
                    (this._errbacks && this._errbacks.length)) {
                    this._unwrap(this._value);
                }
            }
        },

        /**
        If `value` is a promise or a thenable, it will be unwrapped by
        recursively calling its `then` method. If not, the resolver will be
        fulfilled with `value`.

        This method is called when the promise's `then` method is called and
        not in `resolve` to allow for lazy promises to be accepted and not
        resolved immediately.

        @method _unwrap
        @param {Any} value A promise, thenable or regular value
        @private
        **/
        _unwrap: function (value) {
            var self = this, unwrapped = false, then;

            if (!value || (typeof value !== 'object' &&
                typeof value !== 'function')) {
                self.fulfill(value);
                return;
            }

            try {
                then = value.then;

                if (typeof then === 'function') {
                    then.call(value, function (value) {
                        if (!unwrapped) {
                            unwrapped = true;
                            self._unwrap(value);
                        }
                    }, function (reason) {
                        if (!unwrapped) {
                            unwrapped = true;
                            self.reject(reason);
                        }
                    });
                } else {
                    self.fulfill(value);
                }
            } catch (e) {
                if (!unwrapped) {
                    self.reject(e);
                }
            }
        },

        /**
        Schedule execution of a callback to either or both of "resolve" and
        "reject" resolutions of this resolver. If the resolver is not pending,
        the correct callback gets called automatically.

        @method _addCallbacks
        @param {Function} [callback] function to execute if the Resolver
                    resolves successfully
        @param {Function} [errback] function to execute if the Resolver
                    resolves unsuccessfully
        **/
        _addCallbacks: function (callback, errback) {
            var callbackList = this._callbacks,
                errbackList  = this._errbacks;

            // Because the callback and errback are represented by a Resolver, it
            // must be fulfilled or rejected to propagate through the then() chain.
            // The same logic applies to resolve() and reject() for fulfillment.
            if (callbackList) {
                callbackList.push(callback);
            }
            if (errbackList) {
                errbackList.push(errback);
            }

            switch (this._status) {
                case 'accepted':
                    this._unwrap(this._value);
                    break;
                case 'fulfilled':
                    this.fulfill(this._result);
                    break;
                case 'rejected':
                    this.reject(this._result);
                    break;
            }
        },

        /**
        Executes an array of callbacks from a specified context, passing a set of
        arguments.

        @method _notify
        @param {Function[]} subs The array of subscriber callbacks
        @param {Any} result Value to pass the callbacks
        @protected
        **/
        _notify: function (subs, result) {
            // Since callback lists are reset synchronously, the subs list never
            // changes after _notify() receives it. Avoid calling Y.soon() for
            // an empty list
            if (subs.length) {
                // Calling all callbacks after Promise.async to guarantee
                // asynchronicity. Because setTimeout can cause unnecessary
                // delays that *can* become noticeable in some situations
                // (especially in Node.js)
                Promise.async(function () {
                    var i, len;

                    for (i = 0, len = subs.length; i < len; ++i) {
                        subs[i](result);
                    }
                });
            }
        }

    });

    Promise.Resolver = Resolver;

    return Promise;

}));

<|endoftext|>


<commit_before>function Promise(worker) {
  this.onResolve = undefined;

  this.resolve = function(result) {
    this.onResolve(result);
  }

  this.then = function(onResolve) {
    this.onResolve = onResolve;
  }

  worker(this.resolve.bind(this));
}

module.exports = function(worker) {
  return new Promise(worker);
}<commit_msg>fix deferred resolve<commit_after>function Promise(worker) {
  this.onResolve = undefined;
  this.result = undefined;
  this.state = 'pending';

  this.resolve = function(result) {
    this.result = result;
    this.state = 'resolved';
    if (this.onResolve)
      this.onResolve(result);
  }

  this.then = function(onResolve) {
    if (this.state === 'resolved')
      onResolve(this.result);
    else if (this.state === 'pending')
      this.onResolve = onResolve;
  }

  worker(this.resolve.bind(this));
}

module.exports = function(worker) {
  return new Promise(worker);
}<|endoftext|>


<commit_before>angular.module('main').
	directive('draggable', [function() {
		return  {
			restrict: 'A',
			scope: {
				data: '='
			},
			link: function(scope, element, attrs) {
				if (attrs['draggable'] === 'true') {
					var el = element[0];
			        el.draggable = true;

			        el.addEventListener('dragstart', function(e) {
		                e.dataTransfer.effectAllowed = 'move';
		                e.dataTransfer.setData('data', JSON.stringify(scope.data));
		                scope.$emit('dragstart');
		                this.classList.add('drag');
		                return false;
		            }, false);

			        el.addEventListener('dragend', function(e) {
			            scope.$emit('dragend');
			            this.classList.remove('drag');
			            return false;
			        }, false);
			   	}
			}
		};
	}]);

angular.module('main').
	directive('droppable', function() {
	    return {
	    	scope: {
	    		ondrop: '&',
	    		branchName: '=',
	    		context: '&'
	    	},
	        link: function(scope, element, attrs) {
	            var el = element[0];

	            el.addEventListener('dragover', function(e) {
				    e.dataTransfer.dropEffect = 'move';
				    // allows us to drop
				    if (e.preventDefault) e.preventDefault();
				    this.classList.add('over');
				    return false;
				}, false);

				el.addEventListener('dragenter', function(e) {
				    this.classList.add('over');
				    return false;
				}, false);

				el.addEventListener('dragleave', function(e) {
					this.classList.remove('over');
				    return false;
				}, false);

				el.addEventListener('drop', function(e) {
			        // Stops some browsers from redirecting.
			        if (e.stopPropagation) e.stopPropagation();

			        this.classList.remove('over');

			        var item = JSON.parse(e.dataTransfer.getData('data'));
			        scope.$apply(function(scope) {
					    var fn = scope.ondrop();
					    if ('undefined' !== typeof fn) {
					    	if (scope.context) {
					    		fn.apply(scope.context(), [scope.branchName, item]);
					    	}
					    	else {
					    		fn(scope.branchName, item);
					    	}
					    }
					});

			        return false;
				}, false);
	        }
	    }
	});<commit_msg>fix MJS drag and drop in IE<commit_after>angular.module('main').
	directive('draggable', [function() {
		return  {
			restrict: 'A',
			scope: {
				data: '='
			},
			link: function(scope, element, attrs) {
				if (attrs['draggable'] === 'true') {
					var el = element[0];
			        el.draggable = true;

			        el.addEventListener('dragstart', function(e) {
		                e.dataTransfer.effectAllowed = 'move';
		                try{
			                e.dataTransfer.setData('data', JSON.stringify(scope.data));
			            }
			            catch(exception) {
			                e.dataTransfer.setData('text', JSON.stringify(scope.data));
			            }
		                scope.$emit('dragstart');
		                this.classList.add('drag');
		                return false;
		            }, false);

			        el.addEventListener('dragend', function(e) {
			            scope.$emit('dragend');
			            this.classList.remove('drag');
			            return false;
			        }, false);
			   	}
			}
		};
	}]);

angular.module('main').
	directive('droppable', function() {
	    return {
	    	scope: {
	    		ondrop: '&',
	    		branchName: '=',
	    		context: '&'
	    	},
	        link: function(scope, element, attrs) {
	            var el = element[0];

	            el.addEventListener('dragover', function(e) {
				    e.dataTransfer.dropEffect = 'move';
				    // allows us to drop
				    if (e.preventDefault) e.preventDefault();
				    this.classList.add('over');
				    return false;
				}, false);

				el.addEventListener('dragenter', function(e) {
				    this.classList.add('over');
				    return false;
				}, false);

				el.addEventListener('dragleave', function(e) {
					this.classList.remove('over');
				    return false;
				}, false);

				el.addEventListener('drop', function(e) {
					var item;

			        // Stops some browsers from redirecting.
			        if (e.stopPropagation) e.stopPropagation();

			        this.classList.remove('over');

			        try {
			        	item = JSON.parse(e.dataTransfer.getData('data'));
				    }
				    catch(exception) {
				    	item = JSON.parse(e.dataTransfer.getData('text'));
				    }
			        scope.$apply(function(scope) {
					    var fn = scope.ondrop();
					    if ('undefined' !== typeof fn) {
					    	if (scope.context) {
					    		fn.apply(scope.context(), [scope.branchName, item]);
					    	}
					    	else {
					    		fn(scope.branchName, item);
					    	}
					    }
					});

			        return false;
				}, false);
	        }
	    }
	});<|endoftext|>