<commit_before>function imageLoader(imgSrc ,callback){
  var img = new Image();
  img.onload = function(){
    callback(img);
  }
  img.src = imgSrc;
}

function saveToClipboard(str) {
    var textArea = document.createElement('textarea');
    textArea.style.cssText = 'position:absolute;left:-100%';

    document.body.appendChild(textArea);

    textArea.value = str;
    textArea.select();
    document.execCommand('copy');

    document.body.removeChild(textArea);
}

var canvasUtils = {
  appendImageToCanvas: function(argObj) {
    var canvasData = argObj.canvasData;
    var imageSrc = argObj.imageSrc;
    var pageHeight = argObj.pageHeight;
    var imageHeight = argObj.imageHeight;
    var width = argObj.width;
    var top = argObj.top;
    var scale = argObj.scale || 1.0;
    var callback = argObj.callback;
    // If 1st argument is Object (maybe <canvas>), convert to dataURL.
    if(typeof canvasData === 'object'){
      canvasData = canvasData.toDataURL();
    }
    var canvas = document.createElement('canvas');
    canvas.width = width / scale;
    canvas.height = pageHeight / scale;
    var ctx = canvas.getContext('2d');
    imageLoader(canvasData, function(img) {
      ctx.drawImage(img, 0, 0);
      imageLoader(imageSrc, function(img) {
        ctx.drawImage(img, 0, 0, width, imageHeight * scale, 0, top / scale, width / scale, imageHeight);
        callback(canvas);
      })
    });
  },
  trimImage: function(argObj) {
    var imageData = argObj.imageData;
    var startX = argObj.startX;
    var startY = argObj.startY;
    var width = argObj.width;
    var height = argObj.height;
    var scale = argObj.scale  || 1.0;
    var zoom = argObj.zoom || 1.0;
    var callback = argObj.callback || function(){};
    if(typeof imageData === 'string' && imageData.substr(0,5) === 'data:'){
      imageLoader(imageData, function(img){
        var canvas = document.createElement('canvas');
        canvas.width = width;
        canvas.height = height;
        var ctx = canvas.getContext('2d');
        startX *= scale;
        startY *= scale;
        height *= scale * zoom;
        width *= scale * zoom;
        ctx.drawImage(img, startX, startY, width, height, 0, 0, width, height);
        callback(canvas);
      })
    }else if(typeof imageData === 'object'){
      //maybe <canvas>
      this.appendImageToCanvas({
        canvasData: document.createElement('canvas'),
        imageSrc: imageData,
        pageHeight: height,
        imageHeight: height * scale,
        width: width * scale,
        top: 0,
        scale: scale,
        callback: function(canvas){
        var ctx = canvas.getContext('2d');
        var originalWidth = width;
        var originalHeight = height;
        startX *= scale;
        startY *= scale;
        height *= scale * zoom;
        width *= scale * zoom;
        imageLoader(canvas.toDataURL('image/png'), function(img){
          ctx.drawImage(img, startX, startY, width, height, 0, 0, originalWidth, originalHeight);
          callback(canvas);
        })
      }})
    }
  }
}
<commit_msg>improvement for retina display!<commit_after>function imageLoader(imgSrc ,callback){
  var img = new Image();
  img.onload = function(){
    callback(img);
  }
  img.src = imgSrc;
}

function saveToClipboard(str) {
    var textArea = document.createElement('textarea');
    textArea.style.cssText = 'position:absolute;left:-100%';

    document.body.appendChild(textArea);

    textArea.value = str;
    textArea.select();
    document.execCommand('copy');

    document.body.removeChild(textArea);
}

var canvasUtils = {
  appendImageToCanvas: function(argObj) {
    var canvasData = argObj.canvasData;
    var imageSrc = argObj.imageSrc;
    var pageHeight = argObj.pageHeight;
    var imageHeight = argObj.imageHeight;
    var width = argObj.width;
    var top = argObj.top;
    var scale = argObj.scale || 1.0;
    var callback = argObj.callback;
    // If 1st argument is Object (maybe <canvas>), convert to dataURL.
    if(typeof canvasData === 'object'){
      canvasData = canvasData.toDataURL();
    }
    var canvas = document.createElement('canvas');
    canvas.width = width / scale;
    canvas.height = pageHeight;
    var ctx = canvas.getContext('2d');
    imageLoader(canvasData, function(img) {
      ctx.drawImage(img, 0, 0);
      imageLoader(imageSrc, function(img) {
        ctx.drawImage(img, 0, 0, width, imageHeight * scale, 0, top, width / scale, imageHeight);
        callback(canvas);
      })
    });
  },
  trimImage: function(argObj) {
    var imageData = argObj.imageData;
    var startX = argObj.startX;
    var startY = argObj.startY;
    var width = argObj.width;
    var height = argObj.height;
    var scale = argObj.scale  || 1.0;
    var zoom = argObj.zoom || 1.0;
    var callback = argObj.callback || function(){};
    if(typeof imageData === 'string' && imageData.substr(0,5) === 'data:'){
      imageLoader(imageData, function(img){
        var canvas = document.createElement('canvas');
        canvas.width = width * scale;
        canvas.height = height * scale;
        var ctx = canvas.getContext('2d');
        startX *= scale;
        startY *= scale;
        height *= scale * zoom;
        width *= scale * zoom;
        ctx.drawImage(img, startX, startY, width, height, 0, 0, width, height);
        callback(canvas);
      })
    }else if(typeof imageData === 'object'){
      //maybe <canvas>
      this.appendImageToCanvas({
        canvasData: document.createElement('canvas'),
        imageSrc: imageData,
        pageHeight: height,
        imageHeight: height * scale,
        width: width * scale,
        top: 0,
        scale: scale,
        callback: function(canvas){
        var ctx = canvas.getContext('2d');
        var originalWidth = width;
        var originalHeight = height;
        startX *= scale;
        startY *= scale;
        height *= scale * zoom;
        width *= scale * zoom;
        imageLoader(canvas.toDataURL('image/png'), function(img){
          ctx.drawImage(img, startX, startY, width, height, 0, 0, originalWidth, originalHeight);
          callback(canvas);
        })
      }})
    }
  }
}
<|endoftext|>


<commit_before>const pad = n => n < 10 ? `0${n}` : n

export const getTimeObj = (lapse) => {
  const millisecond = pad(Math.floor((lapse % 1000) / 10))
  const second = pad(Math.floor(lapse / 1000))
  const minute = pad(Math.floor(second / 60))
  return { minute, second, millisecond }
}

export const isSpace = (event) => event.which === 32
<commit_msg>Fix seconds calculation<commit_after>const pad = n => n < 10 ? `0${n}` : n

export const getTimeObj = (lapse) => {
  const millisecond = pad(Math.floor((lapse % 1000) / 10))
  const second = pad(Math.floor(lapse / 1000) % 60)
  const minute = pad(Math.floor(lapse / 60000))
  return { minute, second, millisecond }
}

export const isSpace = (event) => event.which === 32
<|endoftext|>


<commit_before> /*!
 * jQuery PLugin Base v1.2
 * https://github.com/marcosfreitas/jquery-plugin-base/
 *
 * Copyright 2015, 2016 Marcos Freitas
 * Released under the MIT license
 */

;(function($) {
	'use strict'; // ecma script 5

	// the __function is a method or event's name
	$.MyPlugin = function (__function, options) {

		/*! default properties */

		var __default = {
			'name' : 'marcos',
			'lastname' : 'freitas',
			'yearold' : 25
		},

		// merging new properties to default
		config = $.extend({}, __default, options),

		/*! private properties */

		// if you have requests to an Restful API, you can change the 'verb' of the priv.ajax.method to POST, PUT, DELETE or UPDATE.
		// - waiting maximum 15 seconds for a request
		priv = {
			'ajax' : {
				'interval_requests' : 3000,
				'max_time_waiting'  : 15,
				'method' : 'GET'
			}
		},

		/*! global vars */

		// a counter used on private.recursive
		recursive_cron = 0,
		// an object to store the values on global way like:  database.user = {name="marcos"}
		database = {},

		/*! private methods, they can't be called from instances */
		privates = {

			// call the function recursively until the limit and turn to success or error of requests
			recursive : function (callback) {

				if (priv.ajax.interval_requests/1000 <= priv.ajax.max_time_waiting) {
					console.warn('waiting '+priv.ajax.interval_requests+' seconds...');
					recursive_cron =
						setInterval(function() {

							priv.ajax.interval_requests += 3000;
							clearInterval(recursive_cron);
							// call the function passed
							callback();

						}, priv.ajax.interval_requests)
					;
				} else {
					priv.ajax.interval_requests = 3000;
					clearInterval(recursive_cron);
					return false ;
				}

				return true;
			},

			// make all the ajax request and return a promise
			// jsonp_callback is optional, he define the cross-domain and o dataType as jsonp
			get : function (url, jsonp_callback) {

				try {

					var o = {};

					// request's parameters
					o.cache  = false;
					o.timeout = 10000;
					o.url    = url;
					o.method = priv.ajax.method;

					if (typeof jsonp_callback !== 'undefined') {
						o.crossDomain = true;
						o.jsonpCallback = jsonp_callback;
						o.dataType      = 'jsonp';
					} else {
						o.dataType = 'json';
					}
					return $.ajax(o);

				} catch (e) {
					console.error('I couldn\'t do this...');
				}
			},
		},

		methods = {

			init : function (param, param2) {
				console.log(param, param2);
			},

			b : function (param, param2) {
				console.log(param, param2);
			},

			/*! a example for a method what do a request to a api */
			fake : function(url) {

				if (typeof url === 'undefined') {
					url = 'http://www.mocky.io/v2/56969c1125000012061affbb';
				}

				var _fake = privates.get(url);

				// Promises running after _fake respond
				$.when(_fake).then(
					// the number of parameters to this function is in accord with number of variables (requests) previously defined like '_fake'
					// will receive a json
					function __response(json) {
						// here is the code executed on .done() of $.ajax()
						if (typeof json === 'object') {

							console.info(json);
							events.onFinish();

						} else {
							// calling recursively, after many attempts trigger a error
							if (!privates.recursive(methods.fake)) {
								$.error('The request has been failed')
							}
						}

						// here put what you need to now...

					},
					// trigger error because the request has been failed
					function __error(e) {
						$.error(e);
					}
				);
			}
		},

		events = {
			// you can organizze this like you want
			onClick: function() {},
			onHover: function() {},
			onFinish: function() { console.log('this don\'t represent the "on load" of the browser, but the load after any task what you has been defined, like a ajax request...') }
		};

		/*! Modify this only if you understand, be careful */
	   // call the methods or events
	   var arr_options = Array();

	    if (typeof options !== 'undefined') {
	    	try {
			// Array.prototype.slice não funciona até o IE 8 e no chrome 14
		        // http://stackoverflow.com/questions/7056925/how-does-array-prototype-slice-call-work
		        // se não for um array ele vai separar a string em letras
		        // para passar corretamente parâmetros para os métodos ou funçõesé preciso que opções seja um array,
		        // ou um array-like (um objeto com índices numéricos e uma propriedade 'length')
		        // repassa todos os elementos do array, mas depende de quantos a função está esperando receber
		        arr_options = Array.prototype.slice.call(options, 0);
		} catch(err){
		        // slow but works on IE
		            arr_options = [];
		        var length = options.length;
		        for(var o=0; o < length; o++){
		            arr_options.push(options[o]);
		        }
		    }
	    }

	    // the functions at methods and events can be "returned" calling methods['onload'] by example
	    if ( methods[__function] ) {
		// the apply() method call the function with a value (this) and arguments provided like an array (or a object "array-like").
		return methods[__function].apply( this, arr_options);
	    }
	    else if ( events[__function] ) {
	    	return events[__function].apply( this, arr_options);
	    }
	    // don't found anything, method or event, with that name (__func)
	    // so call the init method passing the options if this is a object
	    else if ( typeof options === 'object' ) {
	    	return methods.init.apply( this, options );
	    }
	    // finaly call the method init passing the selector object jquery or not
	    else if ( typeof __function === 'undefined' && typeof options === 'undefined' ) {
	    	 // if only the plugin is for the type $.fn
	    	 return methods.init(this);
	    	 //return methods.init();
	    }
	    else {
	    	$.error( 'The method or event "' +  __function + '" don not exists on MyPLugin.js' );
	    }

	};

})(jQuery);
<commit_msg>Update myplugin.js<commit_after> /*!
 * jQuery PLugin Base v1.2
 * https://github.com/marcosfreitas/jquery-plugin-base/
 *
 * Copyright 2015, 2016 Marcos Freitas
 * Released under the MIT license
 */

;(function($) {
	'use strict'; // ecma script 5

	// the __function is a method or event's name
	$.MyPlugin = function (__function, options) {

		/*! default properties */

		var __default = {
			'name' : 'marcos',
			'lastname' : 'freitas',
			'yearold' : 25
		},

		// merging new properties to default
		config = $.extend({}, __default, options),

		/*! private properties */

		// if you have requests to an Restful API, you can change the 'verb' of the priv.ajax.method to POST, PUT, DELETE or UPDATE.
		// - waiting maximum 15 seconds for a request
		priv = {
			'ajax' : {
				'interval_requests' : 3000,
				'max_time_waiting'  : 15,
				'method' : 'GET'
			}
		},

		/*! global vars */

		// a counter used on private.recursive
		recursive_cron = 0,
		// an object to store the values on global way like:  database.user = {name="marcos"}
		database = {},

		/*! private methods, they can't be called from instances */
		privates = {

			// call the function recursively until the limit and turn to success or error of requests
			recursive : function (callback) {

				if (priv.ajax.interval_requests/1000 <= priv.ajax.max_time_waiting) {
					console.warn('waiting '+priv.ajax.interval_requests+' seconds...');
					recursive_cron =
						setInterval(function() {

							priv.ajax.interval_requests += 3000;
							clearInterval(recursive_cron);
							// call the function passed
							callback();

						}, priv.ajax.interval_requests)
					;
				} else {
					priv.ajax.interval_requests = 3000;
					clearInterval(recursive_cron);
					return false ;
				}

				return true;
			},

			// make all the ajax request and return a promise
			// jsonp_callback is optional, he define the cross-domain and o dataType as jsonp
			get : function (url, jsonp_callback) {

				try {

					var o = {};

					// request's parameters
					o.cache  = false;
					o.timeout = 10000;
					o.url    = url;
					o.method = priv.ajax.method;

					if (typeof jsonp_callback !== 'undefined') {
						o.crossDomain = true;
						o.jsonpCallback = jsonp_callback;
						o.dataType      = 'jsonp';
					} else {
						o.dataType = 'json';
					}
					return $.ajax(o);

				} catch (e) {
					console.error('I couldn\'t do this...');
				}
			},
		},

		methods = {

			init : function (param, param2) {
				console.log(param, param2);
			},

			b : function (param, param2) {
				console.log(param, param2);
			},

			/*! a example for a method what do a request to a api */
			fake : function(url) {

				if (typeof url === 'undefined') {
					url = 'http://www.mocky.io/v2/56969c1125000012061affbb';
				}

				var _fake = privates.get(url);

				// Promises running after _fake respond
				$.when(_fake).then(
					// the number of parameters to this function is in accord with number of variables (requests) previously defined like '_fake'
					// will receive a json
					function __response(json) {
						// here is the code executed on .done() of $.ajax()
						if (typeof json === 'object') {

							console.info(json);
							events.onFinish();

						} else {
							// calling recursively, after many attempts trigger a error
							if (!privates.recursive(methods.fake)) {
								$.error('The request has been failed')
							}
						}

						// here put what you need to now...

					},
					// trigger error because the request has been failed
					function __error(e) {
						$.error(e);
					}
				);
			}
		},

		events = {
			// you can organizze this like you want
			onClick: function() {},
			onHover: function() {},
			onFinish: function() { console.log('this don\'t represent the "on load" of the browser, but the load after any task what you has been defined, like a ajax request...') }
		};

		/*! Modify this only if you understand, be careful */
	   // call the methods or events
	   var arr_options = Array();

	    if (typeof options !== 'undefined') {
	    	try {
			// Array.prototype.slice não funciona até o IE 8 e no chrome 14
		        // http://stackoverflow.com/questions/7056925/how-does-array-prototype-slice-call-work
		        // se não for um array ele vai separar a string em letras
		        // para passar corretamente parâmetros para os métodos ou funçõesé preciso que opções seja um array,
		        // ou um array-like (um objeto com índices numéricos e uma propriedade 'length')
		        // repassa todos os elementos do array, mas depende de quantos a função está esperando receber
		        arr_options = Array.prototype.slice.call(options, 0);
		} catch(err){
		        // slow but works on IE
		            arr_options = [];
		        var length = options.length;
		        for(var o=0; o < length; o++){
		            arr_options.push(options[o]);
		        }
		    }
	    }

	    // the functions at methods and events can be "returned" calling methods['onload'] by example
	    if ( methods[__function] ) {
		// the apply() method call the function with a value (this) and arguments provided like an array (or a object "array-like").
		return methods[__function].apply( this, arr_options);
	    }
	    else if ( events[__function] ) {
	    	return events[__function].apply( this, arr_options);
	    }
	    // don't found anything, method or event, with that name (__func)
	    // so call the init method passing the options if this is a object
	    else if ( typeof options === 'object' || typeof __function === 'object' ) {
	    	return methods.init.apply( this, options );
	    }
	    // finaly call the method init passing the selector object jquery or not
	    else if ( typeof __function === 'undefined' && typeof options === 'undefined' ) {
	    	 // if only the plugin is for the type $.fn
	    	 return methods.init(this);
	    	 //return methods.init();
	    }
	    else {
	    	$.error( 'The method or event "' +  __function + '" don not exists on MyPLugin.js' );
	    }

	};

})(jQuery);
<|endoftext|>


<commit_before>define([
           'dojo/_base/declare',
           'dojo/_base/array',
           'JBrowse/Store/LRUCache',
           'JBrowse/Model/XHRBlob',
           'JBrowse/Model/BGZip/BGZBlob',
           'JBrowse/Model/TabixIndex'
       ],
       function(
           declare,
           array,
           LRUCache,
           XHRBlob,
           BGZBlob,
           TabixIndex
       ) {

return declare( null, {

    constructor: function( args ) {
        this.browser = args.browser;
        this.index = new TabixIndex({ blob: new BGZBlob( args.tbi ), browser: args.browser } );
        this.data  = new BGZBlob( args.file );
        this.indexLoaded = this.index.load();
    },

    getLines: function( ref, min, max, itemCallback, finishCallback, errorCallback ) {
        var thisB = this;
        var args = Array.prototype.slice.call(arguments);
        this.indexLoaded.then(function() {
            thisB._fetch.apply( thisB, args );
        }, errorCallback);
    },

    _fetch: function( ref, min, max, itemCallback, finishCallback, errorCallback ) {
        var regRef = this.browser.regularizeReferenceName( ref );

        errorCallback = errorCallback || function(e) { console.error(e, e.stack); };

        var chunks = this.index.blocksForRange( ref, min, max);
        if ( ! chunks ) {
            errorCallback('Error in index fetch ('+[ref,min,max].join(',')+')');
            return;
        }

        // toString function is used by the cache for making cache keys
        chunks.toString = chunks.toUniqueString = function() {
            return this.join(', ');
        };

        var fetchError;
        try {
            this._fetchChunkData( chunks, function( items, error ) {
                if( fetchError )
                    return;

                if( error ) {
                    errorCallback( error );
                } else {
                    array.forEach( items, function(item) {
                        if( !( item.end < min || item.start > max )
                            && ( ref === undefined || item._regularizedRef == regRef ) ) {
                                itemCallback( item );
                            }
                    });
                    finishCallback();
                }
            });
        } catch( e ) {
            errorCallback( e );
        }
    },

    _fetchChunkData: function( chunks, callback ) {
        var thisB = this;

        if( ! chunks.length ) {
            callback([]);
            return;
        }

        var allItems = [];
        var chunksProcessed = 0;

        var cache = this.chunkCache = this.chunkCache || new LRUCache({
            name: 'TabixIndexedFileChunkedCache',
            fillCallback: dojo.hitch( this, '_readChunkItems' ),
            sizeFunction: function( chunkItems ) {
                return chunkItems.length;
            },
            maxSize: 100000 // cache up to 100,000 items
        });

        var error;
        array.forEach( chunks, function( c ) {
            cache.get( c, function( chunkItems, e ) {
                error = error || e;
                allItems.push.apply( allItems, chunkItems );
                if( ++chunksProcessed == chunks.length )
                    callback( allItems, error );
            });
        });
    },

    _readChunkItems: function( chunk, callback ) {
        var thisB = this;
        var items = [];

        thisB.data.read(chunk.minv.block, chunk.maxv.block - chunk.minv.block + 1, function( data ) {
            data = new Uint8Array(data);

            // throw away the first (probably incomplete) line
            var parseStart = array.indexOf( data, thisB._newlineCode, 0 ) + 1;

            try {
                thisB.parseItems(
                    data,
                    parseStart,
                    function(i) { items.push(i); },
                    function() { callback(items); }
                );
            } catch( e ) {
                callback( null, e );
            }
        },
        function(e) {
            callback( null, e );
        });
    },

    parseItems: function( data, blockStart, itemCallback, finishCallback ) {
        var that = this;
        var itemCount = 0;

        var maxItemsWithoutYielding = 300;
        var parseState = { data: data, offset: blockStart };

        while ( true ) {
            // if we've read no more than a certain number of items this cycle, read another one
            if( itemCount <= maxItemsWithoutYielding ) {
                var item = this.parseItem( parseState ); //< increments parseState.offset
                if( item ) {
                    itemCallback( item );
                    itemCount++;
                }
                else {
                    finishCallback();
                    return;
                }
            }
            // if we're not done but we've read a good chunk of
            // items, schedule the rest of our work in a timeout to continue
            // later, avoiding blocking any UI stuff that needs to be done
            else {
                window.setTimeout( function() {
                    that.parseItems( data, parseState.offset, itemCallback, finishCallback );
                }, 1);
                return;
            }
        }
    },

    // stub method, override in subclasses or instances
    parseItem: function( parseState ) {
        var metaChar = this.index.metaChar;

        var line;
        do {
            line = this._getline( parseState );
        } while( line && line[0] == metaChar );

        if( !line )
            return null;

        // function extractColumn( colNum ) {
        //     var skips = '';
        //     while( colNum-- > 1 )
        //         skips += '^[^\t]*\t';
        //     var match = (new Regexp( skips+'([^\t]*)' )).exec( line );
        //     if( ! match )
        //         return null;
        //     return match[1];
        // }
        var fields = line.split( "\t" );
        var item = { // note: index column numbers are 1-based
            ref:   fields[this.index.columnNumbers.ref-1],
            _regularizedRef: this.browser.regularizeReferenceName( fields[this.index.columnNumbers.ref-1] ),
            start: parseInt(fields[this.index.columnNumbers.start-1]),
            end:   parseInt(fields[this.index.columnNumbers.end-1]),
            fields: fields
        };
        return item;
    },

    _newlineCode: "\n".charCodeAt(0),

    _getline: function( parseState ) {
        var data = parseState.data;
        var newlineIndex = array.indexOf( data, this._newlineCode, parseState.offset );

        if( newlineIndex == -1 ) // no more lines
            return null;

        var line = '';
        for( var i = parseState.offset; i < newlineIndex; i++ )
            line += String.fromCharCode( data[i] );
        parseState.offset = newlineIndex+1;
        return line;
    }
});
});
<commit_msg>optimize chunk traversal in VCF backend, references #249<commit_after>define([
           'dojo/_base/declare',
           'dojo/_base/array',
           'JBrowse/Store/LRUCache',
           'JBrowse/Model/XHRBlob',
           'JBrowse/Model/BGZip/BGZBlob',
           'JBrowse/Model/TabixIndex'
       ],
       function(
           declare,
           array,
           LRUCache,
           XHRBlob,
           BGZBlob,
           TabixIndex
       ) {

return declare( null, {

    constructor: function( args ) {
        this.browser = args.browser;
        this.index = new TabixIndex({ blob: new BGZBlob( args.tbi ), browser: args.browser } );
        this.data  = new BGZBlob( args.file );
        this.indexLoaded = this.index.load();
    },

    getLines: function( ref, min, max, itemCallback, finishCallback, errorCallback ) {
        var thisB = this;
        var args = Array.prototype.slice.call(arguments);
        this.indexLoaded.then(function() {
            thisB._fetch.apply( thisB, args );
        }, errorCallback);
    },

    _fetch: function( ref, min, max, itemCallback, finishCallback, errorCallback ) {
        errorCallback = errorCallback || function(e) { console.error(e, e.stack); };

        var chunks = this.index.blocksForRange( ref, min, max);
        if ( ! chunks ) {
            errorCallback('Error in index fetch ('+[ref,min,max].join(',')+')');
            return;
        }

        // toString function is used by the cache for making cache keys
        chunks.toString = chunks.toUniqueString = function() {
            return this.join(', ');
        };

        var fetchError;
        try {
            this._fetchChunkData(
                chunks,
                ref,
                min,
                max,
                itemCallback,
                finishCallback,
                errorCallback
            );
        } catch( e ) {
            errorCallback( e );
        }
    },

    _fetchChunkData: function( chunks, ref, min, max, itemCallback, endCallback, errorCallback ) {
        var thisB = this;

        if( ! chunks.length ) {
            endCallback();
            return;
        }

        var allItems = [];
        var chunksProcessed = 0;

        var cache = this.chunkCache = this.chunkCache || new LRUCache({
            name: 'TabixIndexedFileChunkedCache',
            fillCallback: dojo.hitch( this, '_readChunkItems' ),
            sizeFunction: function( chunkItems ) {
                return chunkItems.length;
            },
            maxSize: 100000 // cache up to 100,000 items
        });

        var regRef = this.browser.regularizeReferenceName( ref );

        var haveError;
        array.forEach( chunks, function( c ) {
            cache.get( c, function( chunkItems, e ) {
                if( e && !haveError )
                    errorCallback( e );
                if(( haveError = haveError || e )) {
                    return;
                }

                for( var i = 0; i< chunkItems.length; i++ ) {
                    var item = chunkItems[i];
                    if( item._regularizedRef == regRef ) {
                        // on the right ref seq
                        if( item.start > max ) // past end of range, can stop iterating
                            break;
                        else if( item.end >= min ) // must be in range
                            itemCallback( item );
                    }
                }
                if( ++chunksProcessed == chunks.length ) {
                    endCallback();
                }
            });
        });
    },

    _readChunkItems: function( chunk, callback ) {
        var thisB = this;
        var items = [];

        thisB.data.read(chunk.minv.block, chunk.maxv.block - chunk.minv.block + 1, function( data ) {
            data = new Uint8Array(data);

            // throw away the first (probably incomplete) line
            var parseStart = array.indexOf( data, thisB._newlineCode, 0 ) + 1;

            try {
                thisB.parseItems(
                    data,
                    parseStart,
                    function(i) { items.push(i); },
                    function() { callback(items); }
                );
            } catch( e ) {
                callback( null, e );
            }
        },
        function(e) {
            callback( null, e );
        });
    },

    parseItems: function( data, blockStart, itemCallback, finishCallback ) {
        var that = this;
        var itemCount = 0;

        var maxItemsWithoutYielding = 300;
        var parseState = { data: data, offset: blockStart };

        while ( true ) {
            // if we've read no more than a certain number of items this cycle, read another one
            if( itemCount <= maxItemsWithoutYielding ) {
                var item = this.parseItem( parseState ); //< increments parseState.offset
                if( item ) {
                    itemCallback( item );
                    itemCount++;
                }
                else {
                    finishCallback();
                    return;
                }
            }
            // if we're not done but we've read a good chunk of
            // items, schedule the rest of our work in a timeout to continue
            // later, avoiding blocking any UI stuff that needs to be done
            else {
                window.setTimeout( function() {
                    that.parseItems( data, parseState.offset, itemCallback, finishCallback );
                }, 1);
                return;
            }
        }
    },

    // stub method, override in subclasses or instances
    parseItem: function( parseState ) {
        var metaChar = this.index.metaChar;

        var line;
        do {
            line = this._getline( parseState );
        } while( line && line[0] == metaChar );

        if( !line )
            return null;

        // function extractColumn( colNum ) {
        //     var skips = '';
        //     while( colNum-- > 1 )
        //         skips += '^[^\t]*\t';
        //     var match = (new Regexp( skips+'([^\t]*)' )).exec( line );
        //     if( ! match )
        //         return null;
        //     return match[1];
        // }
        var fields = line.split( "\t" );
        var item = { // note: index column numbers are 1-based
            ref:   fields[this.index.columnNumbers.ref-1],
            _regularizedRef: this.browser.regularizeReferenceName( fields[this.index.columnNumbers.ref-1] ),
            start: parseInt(fields[this.index.columnNumbers.start-1]),
            end:   parseInt(fields[this.index.columnNumbers.end-1]),
            fields: fields
        };
        return item;
    },

    _newlineCode: "\n".charCodeAt(0),

    _getline: function( parseState ) {
        var data = parseState.data;
        var newlineIndex = array.indexOf( data, this._newlineCode, parseState.offset );

        if( newlineIndex == -1 ) // no more lines
            return null;

        var line = '';
        for( var i = parseState.offset; i < newlineIndex; i++ )
            line += String.fromCharCode( data[i] );
        parseState.offset = newlineIndex+1;
        return line;
    }
});
});
<|endoftext|>


<commit_before>;(function(window, undefined) {
  var supportHashChange = 'onhashchange' in window;

  function getHash() {
    if (!supportHashChange) {
      return window.location.href.replace(/^[^#]#?(.*)$/, '$1');
    }
    var hash = window.location.hash;
    if (hash.charAt(0) === '#') {
      hash = hash.substr(1);
    }
    if (hash === '') hash = '/';
    return hash;
  }

  function onHashChange(cbk) {
    var hash = getHash();
    cbk.call(cbk, hash);
    if (supportHashChange) {
      window.onhashchange = function() {
        var hash = getHash();
        cbk.call(cbk, hash);
      };
      return;
    }
    window.___href___ = window.location.href;
    window.setInterval(function() {
      if (window.___href___ !== window.location.href) {
        window.__href__ = window.location.href;
        var hash = getHash();
        cbk.call(cbk, hash);
      }
    }, 50);
  }

  function getRequest(hash) {
    var params = {},
        kvPair = [],
        partList,
        path,
        query,
        part,
        key,
        value,
        index;
    if (hash.charAt(0) === '#') {
      hash = hash.substr(1);
    }
    index = hash.indexOf('?');
    if (index < 0) {
      return {
        path: hash,
        params: params
      };
    }
    path = hash.substr(0, index);
    query = hash.substr(index + 1);
    partList = query.split('&');

    for (var i = 0, l = partList.length; i < l; i++) {
      part = partList[i];
      kvPair = part.split('=');
      switch (kvPair.length) {
        case 1:
          key = kvPair[0];
          value = null;
          break;
        case 2:
          key = kvPair[0];
          value = kvPair[1];
          break;
        default:
          continue;
      }
      params[key] = value;
    }

    return {
      path: path,
      params: params
    };
  }

  window.router = function(routerPairs) {
    onHashChange(function(hash) {
      var request = getRequest(hash),
          path = request.path,
          args = [request],
          match,
          pair,
          router,
          handler;

      if (typeof path !== 'string') {
        return;
      }

      for (var i = 0, l = routerPairs.length; i < l; i++) {
        pair = routerPairs[i];
        router = pair[0];
        handler = pair[1];
        if (typeof router === 'string') {
          router = new RegExp(router);
        }
        match = path.match(router);
        if (!match) {
          continue;
        }
        args.push.apply(args, match.slice(1));
        handler.apply(handler, args);
        break;
      }
    });
  };
})(window);
<commit_msg>add ft<commit_after>;(function(window, undefined) {
  var supportHashChange = 'onhashchange' in window;

  function getHash() {
    if (!supportHashChange) {
      return window.location.href.replace(/^[^#]#?(.*)$/, '$1');
    }
    var hash = window.location.hash;
    if (hash.charAt(0) === '#') {
      hash = hash.substr(1);
    }
    if (hash === '') hash = '/';
    return hash;
  }

  function onHashChange(cbk) {
    var hash = getHash();
    cbk.call(cbk, hash);
    if (supportHashChange) {
      window.onhashchange = function() {
        var hash = getHash();
        cbk.call(cbk, hash);
      };
      return;
    }
    window.___href___ = window.location.href;
    window.setInterval(function() {
      if (window.___href___ !== window.location.href) {
        window.__href__ = window.location.href;
        var hash = getHash();
        cbk.call(cbk, hash);
      }
    }, 50);
  }

  function getRequest(hash) {
    var params = {},
        kvPair = [],
        partList,
        path,
        query,
        part,
        key,
        value,
        index;
    if (hash.charAt(0) === '#') {
      hash = hash.substr(1);
    }
    index = hash.indexOf('?');
    if (index < 0) {
      return {
        path: hash,
        params: params
      };
    }
    path = hash.substr(0, index);
    query = hash.substr(index + 1);
    partList = query.split('&');

    for (var i = 0, l = partList.length; i < l; i++) {
      part = partList[i];
      kvPair = part.split('=');
      switch (kvPair.length) {
        case 1:
          key = kvPair[0];
          value = null;
          break;
        case 2:
          key = kvPair[0];
          value = kvPair[1];
          break;
        default:
          continue;
      }
      params[key] = value;
    }

    return {
      path: path,
      params: params,
      isCurrent: function() {
        return getHash() === path;
      }
    };
  }

  window.router = function(routerPairs) {
    onHashChange(function(hash) {
      var request = getRequest(hash),
          path = request.path,
          args = [request],
          match,
          pair,
          router,
          handler;

      if (typeof path !== 'string') {
        return;
      }

      for (var i = 0, l = routerPairs.length; i < l; i++) {
        pair = routerPairs[i];
        router = pair[0];
        handler = pair[1];
        if (typeof router === 'string') {
          router = new RegExp(router);
        }
        match = path.match(router);
        if (!match) {
          continue;
        }
        args.push.apply(args, match.slice(1));
        handler.apply(handler, args);
        break;
      }
    });
  };
})(window);
<|endoftext|>


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

var OPC = new require('./opc')

var fc = new OPC('localhost', 7890);

var sp = require('serialport');
var SerialPort = require('serialport').SerialPort;
var portName = "/dev/ttyArduino";

var runState = "down";

var BRIGHTEN = 100;
var DARKEN = 101;

var BRIGHTEN_S = 200;
var DARKEN_S = 201;

var SWEEP = 300;

var pixelLength = 300;
var particleCount = 200;

var environmentLength = 2000;

var defaultScale = 7;

var pixels = [];
var particles = [];

var lookup = [];

var coordT = [];

var dist_v = [];

var timerIdle = true;

// MAIN COMPUTER PROGRAM!

initialize();
setInterval(evaluate, 30);

function initialize() {
	serialport = new SerialPort(portName , { baudrate : 115200, parser: sp.parsers.readline("|") }, false);
	openPort();

	// Init coord lookup
	var coordRatio = ( ( pixelLength ) / environmentLength );
	for ( var t=0; t<environmentLength+1; t++ ){ coordT[t] = Math.floor( t * coordRatio ); }

	// Init scaling lookup

	lookup[defaultScale] = { 'environmentLength': defaultScale * pixelLength, 'positions': [] };

	for ( var p=0; p < lookup[defaultScale].environmentLength; p++ ){
		var div = p / defaultScale;
		var calc = {
			'left': Math.floor( div ),
			'right': Math.floor( div ) + 1,
			'wleft': 1 - ( div ) % 1,
			'wright': ( div ) % 1
		};

		lookup[defaultScale].positions.push( calc );
	}

	// Init pixel array
	for ( var i=0; i<pixelLength + 3; i++ ) { pixels.push({ 'r':0, 'g':0, 'b':0 }); }
}

function evaluate() {
	if ( runState == "open") {
  	updateParticles();
  	evaluateEnvironment();
  	draw();
	} else {
		if ( timerIdle ) {
			setTimeout( function() {
				openPort();
				timerIdle = true;
			}, 5000);
			timerIdle = false;
		}
	}
}

function updateParticles() {
  for ( var i=0; i<particles.length; i++ ){
	particles[i].position += particles[i].vel;

	// recycle particles

	if ( particles[i].method == BRIGHTEN_S || particles[i].method == DARKEN_S ) {
		if ( particles[i].position > lookup[particles[i].scale].environmentLength-1 ) {
			particles[i] = getRandParticle();
		}
	} else if ( particles[i].method == BRIGHTEN || particles[i].method == DARKEN || particles[i].method == SWEEP ) {
		if ( particles[i].position > environmentLength ) {
			particles[i] = getRandParticle();
		}
	}

  }
}

function evaluateEnvironment() {

	// fill particle list
	if ( particles.length < particleCount ) {
		particles.push( getRandParticle() );
	}
}

function draw() {
  if ( runState == "open" ) {

		// Initialize
		for ( var i=0; i<pixels.length; i++ ) {
			pixels[i].red = 20;
			pixels[i].green = 20;
			pixels[i].blue = 40;
		}

	  // Compose
	  for ( var i=0; i<particles.length; i++ ){
			particles[i].method();
	  }

	  // Render

	//	try {
	    for ( var i=0; i<pixels.length; i++ ){
	      fc.setPixel( pixels.length-i, pixels[i].red, pixels[i].green, pixels[i].blue );
	    }
	    fc.writePixels();
	//	} catch( err ) {
	//		console.log('fc write err: ' + error);
	//		runState = "fc write err";
	//	}

  } else {
    // display runstate graphics

  }
}

function methodBrighten() {
	var dest = coordT[particles[i].position];

	pixels[dest].red += particles[i].color.r;
	pixels[dest].green += particles[i].color.g;
	pixels[dest].blue += particles[i].color.b;
}

function methodDarken() {
	var dest = coordT[particles[i].position];

	pixels[dest].red -= particles[i].color.r;
	pixels[dest].green -= particles[i].color.g;
	pixels[dest].blue -= particles[i].color.b;
}

function methodBrightenSmooth() {
	var pcalc = lookup[particles[i].scale].positions[particles[i].position];
	methodValueSmooth( pcalc );
}

function methodDarkenSmooth() {
	var pcalc = lookup[particles[i].scale].positions[particles[i].position];
	if ( particles[i].method == DARKEN_S ) {
		pcalc.wleft *= -1;
		pcalc.wright *= -1;
	}
	methodValueSmooth( pcalc );
}

function methodValueSmooth( pcalc ){
	pixels[pcalc.left].red += particles[i].color.r * pcalc.wleft;
	pixels[pcalc.left].green += particles[i].color.g * pcalc.wleft;
	pixels[pcalc.left].blue += particles[i].color.b * pcalc.wleft;

	pixels[pcalc.right].red += particles[i].color.r * pcalc.wright;
	pixels[pcalc.right].green += particles[i].color.g * pcalc.wright;
	pixels[pcalc.right].blue += particles[i].color.b * pcalc.wright;
}

function methodSweep() {
	var pcalc = lookup[particles[i].scale].positions[particles[i].position];

	var taillen = 6;
	var fraction = 1/taillen;

	for ( var t=0; t < taillen; t++ ) {
		try {
		var tail = pcalc.right - t;
	} catch ( err ) {
		console.log( i + " | " + particles[i].position );
	}
		if ( tail > 0 ) {
			var factor = ( 6 - t ) * ( fraction );
			pixels[tail].red += particles[i].color.r * factor;
			pixels[tail].green += particles[i].color.g * factor;
			pixels[tail].blue += particles[i].color.b * factor;
		}
	}
	var frontedge = pcalc.right + 1;
	if ( frontedge < pixelLength - 2 ) {
		pixels[frontedge].red = 0;
		pixels[frontedge].green = 0;
		pixels[frontedge].blue = 0;
	}
}

function getRandParticle() {
	var r = Math.random();

	if ( r < .10 ) {
		return getParticle( 4, 0, 1, methodBrightenSmooth, defaultScale, 10, 10, 85 );
	} else if ( r < .15 ) {
		return getParticle( 3, 0, 1, methodSweep, defaultScale, 60, 10, 15 );
	} else {
		return getParticle( 2, 0, 1, methodBrightenSmooth, defaultScale, 5, 5, 10 );
	}
}

function getParticle( v, p, r, g, b ) {
	return getParticle( v, p, 1, methodBrighten, defaultScale, r, g, b );
}

function getParticle( v, p, i, m, s, r, g, b ) {
  var p = {
    'vel': v,
    'position': p,
    'intensity': i,
	'method': m,
	'scale': s,
    'color': { 'r': r, 'g': g, 'b': b }
  };
  return p;
}

// Serial Access

function listPorts() {
  serialport.list(function (err, ports) {
    ports.forEach(function(port) {
      console.log(port.comName);
    });
  });
  return ports;
}

function openPort() {
	serialport.on('error', function(err){
		console.log('serialport general error' + err);
	});

  serialport.open(function (error) {
    if ( error ) {
      console.log('open err: ' + error);
//			runState = "conn open err";
	runState = "open";
    } else {
      console.log('open');
			runState = "open";

      serialport.on('data', function(data) {
    		var c = data.trim();
				try{
					//console.log('rcv: ' + c);
	    		dist_v = JSON.parse(c);
					//dist_v = {};
	    		//console.log(' 12: ' + dist_v[12] );
				} catch( err ){
					console.log('parse err ' + err);
				}
	    });

    }
  });

}
<commit_msg>updates as methods<commit_after>#!/usr/bin/env node

var OPC = new require('./opc')

var fc = new OPC('localhost', 7890);

var sp = require('serialport');
var SerialPort = require('serialport').SerialPort;
var portName = "/dev/ttyArduino";

var runState = "down";

var BRIGHTEN = 100;
var DARKEN = 101;

var BRIGHTEN_S = 200;
var DARKEN_S = 201;

var SWEEP = 300;

var pixelLength = 300;
var particleCount = 200;

var environmentLength = 2000;

var defaultScale = 7;

var pixels = [];
var particles = [];

var lookup = [];

var coordT = [];

var dist_v = [];

var timerIdle = true;

// MAIN COMPUTER PROGRAM!

initialize();
setInterval(evaluate, 30);

function initialize() {
	serialport = new SerialPort(portName , { baudrate : 115200, parser: sp.parsers.readline("|") }, false);
	openPort();

	// Init coord lookup
	var coordRatio = ( ( pixelLength ) / environmentLength );
	for ( var t=0; t<environmentLength+1; t++ ){ coordT[t] = Math.floor( t * coordRatio ); }

	// Init scaling lookup

	lookup[defaultScale] = { 'environmentLength': defaultScale * pixelLength, 'positions': [] };

	for ( var p=0; p < lookup[defaultScale].environmentLength; p++ ){
		var div = p / defaultScale;
		var calc = {
			'left': Math.floor( div ),
			'right': Math.floor( div ) + 1,
			'wleft': 1 - ( div ) % 1,
			'wright': ( div ) % 1
		};

		lookup[defaultScale].positions.push( calc );
	}

	// Init pixel array
	for ( var i=0; i<pixelLength + 3; i++ ) { pixels.push({ 'r':0, 'g':0, 'b':0 }); }
}

function evaluate() {
	if ( runState == "open") {
  	updateParticles();
  	evaluateEnvironment();
  	draw();
	} else {
		if ( timerIdle ) {
			setTimeout( function() {
				openPort();
				timerIdle = true;
			}, 5000);
			timerIdle = false;
		}
	}
}

function updateParticles() {
  for ( var i=0; i<particles.length; i++ ){
		particles[i].update();
  }
}

function evaluateEnvironment() {
	// fill particle list
	if ( particles.length < particleCount ) {
		particles.push( getRandParticle() );
	}
}

function draw() {
  if ( runState == "open" ) {

		// Initialize
		initAllPixels( 20, 20, 40 );

	  // Compose
	  for ( var i=0; i<particles.length; i++ ){ particles[i].method(); }

	  // Render
	//	try {
	    for ( var i=0; i<pixels.length; i++ ){
	      fc.setPixel( pixels.length-i, pixels[i].red, pixels[i].green, pixels[i].blue );
	    }
	    fc.writePixels();
	//	} catch( err ) {
	//		console.log('fc write err: ' + error);
	//		runState = "fc write err";
	//	}

  } else {
    // display runstate graphics

  }
}

// update methods

function update_Discrete() {
	particles[i].position += particles[i].vel;

	// recycle rules
	if ( this.position > environmentLength ) {
		this = getRandParticle();
	}
}

function update_Smooth() {
	particles[i].position += particles[i].vel;

	// recycle rules
	if ( this.position > lookup[this.scale].environmentLength-1 ) {
		this = getRandParticle();
	}
}

function update_Glower() {
	particles[i].position += particles[i].vel;

	// recycle rules
	if ( this.position > lookup[this.scale].environmentLength-1 ) {
		this = getRandParticle();
	}
}

// draw methods

function method_Brighten() {
	var dest = coordT[this.position];

	pixels[dest].red += this.color.r;
	pixels[dest].green += this.color.g;
	pixels[dest].blue += this.color.b;
}

function method_Darken() {
	var dest = coordT[this.position];

	pixels[dest].red -= this.color.r;
	pixels[dest].green -= this.color.g;
	pixels[dest].blue -= this.color.b;
}

function method_BrightenSmooth() {
	var pcalc = lookup[this.scale].positions[this.position];
	methodValueSmooth( pcalc );
}

function method_DarkenSmooth() {
	var pcalc = lookup[this.scale].positions[this.position];
	if ( this.method == DARKEN_S ) {
		pcalc.wleft *= -1;
		pcalc.wright *= -1;
	}
	methodValueSmooth( pcalc );
}

function methodValueSmooth( pcalc ){
	pixels[pcalc.left].red += this.color.r * pcalc.wleft;
	pixels[pcalc.left].green += this.color.g * pcalc.wleft;
	pixels[pcalc.left].blue += this.color.b * pcalc.wleft;

	pixels[pcalc.right].red += this.color.r * pcalc.wright;
	pixels[pcalc.right].green += this.color.g * pcalc.wright;
	pixels[pcalc.right].blue += this.color.b * pcalc.wright;
}

function method_Sweep() {
	var pcalc = lookup[this.scale].positions[this.position];

	var taillen = 6;
	var fraction = 1/taillen;

	for ( var t=0; t < taillen; t++ ) {
		try {
		var tail = pcalc.right - t;
	} catch ( err ) {
		console.log( i + " | " + this.position );
	}
		if ( tail > 0 ) {
			var factor = ( 6 - t ) * ( fraction );
			pixels[tail].red += this.color.r * factor;
			pixels[tail].green += this.color.g * factor;
			pixels[tail].blue += this.color.b * factor;
		}
	}
	var frontedge = pcalc.right + 1;
	if ( frontedge < pixelLength - 2 ) {
		pixels[frontedge].red = 0;
		pixels[frontedge].green = 0;
		pixels[frontedge].blue = 0;
	}
}

function setPixel( i, r, g, b ) {
	pixels[i].red = r;
	pixels[i].green = g;
	pixels[i].blue = b;
}

function initAllPixels( r, g, b ){
	for ( var i=0; i<pixels.length; i++ ) {
		pixels[i].red = r;
		pixels[i].green = g;
		pixels[i].blue = b;
	}
}

function getRandParticle() {
	var r = Math.random();

	if ( r < .10 ) {
		return getParticle( 4, 0, 1, method_BrightenSmooth, update_Smooth, defaultScale, 10, 10, 85 );
	} else if ( r < .15 ) {
		return getParticle( 3, 0, 1, method_Sweep, update_Smooth, defaultScale, 60, 10, 15 );
	} else {
		return getParticle( 2, 0, 1, method_BrightenSmooth, update_Smooth, defaultScale, 5, 5, 10 );
	}
}

function getParticle( v, p, r, g, b ) {
	return getParticle( v, p, 1, method_Brighten, update_Discrete, defaultScale, r, g, b );
}

function getParticle( v, p, i, m, u, s, r, g, b ) {
  var p = {
    'vel': v,
    'position': p,
    'intensity': i,
		'method': m,
		'update': u
		'scale': s,
    'color': { 'r': r, 'g': g, 'b': b }
  };
  return p;
}

// Serial Access

function listPorts() {
  serialport.list(function (err, ports) {
    ports.forEach(function(port) {
      console.log(port.comName);
    });
  });
  return ports;
}

function openPort() {
	serialport.on('error', function(err){
		console.log('serialport general error' + err);
	});

  serialport.open(function (error) {
    if ( error ) {
      console.log('open err: ' + error);
//			runState = "conn open err";
	runState = "open";
    } else {
      console.log('open');
			runState = "open";

      serialport.on('data', function(data) {
    		var c = data.trim();
				try{
					//console.log('rcv: ' + c);
	    		dist_v = JSON.parse(c);
					//dist_v = {};
	    		//console.log(' 12: ' + dist_v[12] );
				} catch( err ){
					console.log('parse err ' + err);
				}
	    });

    }
  });

}
<|endoftext|>


<commit_before>'use strict';

var Q = require('q');
var gulpUtil = require('gulp-util');
var childProcess = require('child_process');
var jetpack = require('fs-jetpack');
var asar = require('asar');
var utils = require('./utils');

var projectDir;
var releasesDir;
var tmpDir;
var finalAppDir;
var manifest;

var init = function () {
    projectDir = jetpack;
    tmpDir = projectDir.dir('./tmp', { empty: true });
    releasesDir = projectDir.dir('./releases');
    manifest = projectDir.read('app/package.json', 'json');
    finalAppDir = tmpDir.cwd(manifest.productName + '.app');

    return Q();
};

var copyRuntime = function () {
    return projectDir.copyAsync('node_modules/electron-prebuilt/dist/Electron.app', finalAppDir.path());
};

var cleanupRuntime = function() {
    finalAppDir.remove('Contents/Resources/default_app');
    finalAppDir.remove('Contents/Resources/atom.icns');
    return Q();
}

var packageBuiltApp = function () {
    var deferred = Q.defer();

    asar.createPackage(projectDir.path('build'), finalAppDir.path('Contents/Resources/app.asar'), function() {
        deferred.resolve();
    });

    return deferred.promise;
};

var finalize = function () {
    // Prepare main Info.plist
    var info = projectDir.read('resources/osx/Info.plist');
    info = utils.replace(info, {
        productName: manifest.productName,
        identifier: manifest.identifier,
        version: manifest.version
    });
    finalAppDir.write('Contents/Info.plist', info);

    // Prepare Info.plist of Helper apps
    [' EH', ' NP', ''].forEach(function (helper_suffix) {
        info = projectDir.read('resources/osx/helper_apps/Info' + helper_suffix + '.plist');
        info = utils.replace(info, {
            productName: manifest.productName,
            identifier: manifest.identifier
        });
        finalAppDir.write('Contents/Frameworks/Electron Helper' + helper_suffix + '.app/Contents/Info.plist', info);
    });

    // Copy icon
    projectDir.copy('resources/osx/icon.icns', finalAppDir.path('Contents/Resources/icon.icns'));

    return Q();
};

var renameApp = function() {
    // Rename helpers
    [' Helper EH', ' Helper NP', ' Helper'].forEach(function (helper_suffix) {
        finalAppDir.rename('Contents/Frameworks/Electron' + helper_suffix + '.app/Contents/MacOS/Electron' + helper_suffix, manifest.productName + helper_suffix );
        finalAppDir.rename('Contents/Frameworks/Electron' + helper_suffix + '.app', manifest.productName + helper_suffix + '.app');
    });
    // Rename application
    finalAppDir.rename('Contents/MacOS/Electron', manifest.productName);
    return Q();
}

var signApp = function() {
    var deferred = Q.defer();

    gulpUtil.log('Signing file...');
    childProcess.exec('codesign --deep --force --verbose --sign "Developer ID Application: Konecty Informatica Ltda (DX85ENM22A)" ' + finalAppDir.cwd(), function (error, stdout, stderr) {
        if (error || stderr) {
            console.log("ERROR while signing file");
            console.log(error);
            console.log(stderr);
        } else {
            gulpUtil.log('Signing file DONE!');
        }
        deferred.resolve();
    });
    return Q();
}

var packToDmgFile = function () {
    var deferred = Q.defer();

    var appdmg = require('appdmg');
    var dmgName = manifest.name + '_' + manifest.version + '.dmg';

    // Prepare appdmg config
    var dmgManifest = projectDir.read('resources/osx/appdmg.json');
    dmgManifest = utils.replace(dmgManifest, {
        productName: manifest.productName,
        appPath: finalAppDir.path(),
        dmgIcon: projectDir.path("resources/osx/dmg-icon.icns"),
        dmgBackground: projectDir.path("resources/osx/dmg-background.png")
    });
    tmpDir.write('appdmg.json', dmgManifest);

    // Delete DMG file with this name if already exists
    releasesDir.remove(dmgName);

    gulpUtil.log('Packaging to DMG file...');

    var readyDmgPath = releasesDir.path(dmgName);
    appdmg({
        source: tmpDir.path('appdmg.json'),
        target: readyDmgPath
    })
    .on('error', function (err) {
        console.error(err);
    })
    .on('finish', function () {
        gulpUtil.log('DMG file ready!', readyDmgPath);
        deferred.resolve();
    });

    return deferred.promise;
};

var cleanClutter = function () {
    return tmpDir.removeAsync('.');
};

module.exports = function () {
    return init()
    .then(copyRuntime)
    .then(cleanupRuntime)
    .then(packageBuiltApp)
    .then(finalize)
    .then(renameApp)
    .then(signApp)
    .then(packToDmgFile)
    .then(cleanClutter);
};
<commit_msg>Fix async<commit_after>'use strict';

var Q = require('q');
var gulpUtil = require('gulp-util');
var childProcess = require('child_process');
var jetpack = require('fs-jetpack');
var asar = require('asar');
var utils = require('./utils');

var projectDir;
var releasesDir;
var tmpDir;
var finalAppDir;
var manifest;

var init = function () {
    projectDir = jetpack;
    tmpDir = projectDir.dir('./tmp', { empty: true });
    releasesDir = projectDir.dir('./releases');
    manifest = projectDir.read('app/package.json', 'json');
    finalAppDir = tmpDir.cwd(manifest.productName + '.app');

    return Q();
};

var copyRuntime = function () {
    return projectDir.copyAsync('node_modules/electron-prebuilt/dist/Electron.app', finalAppDir.path());
};

var cleanupRuntime = function() {
    finalAppDir.remove('Contents/Resources/default_app');
    finalAppDir.remove('Contents/Resources/atom.icns');
    return Q();
}

var packageBuiltApp = function () {
    var deferred = Q.defer();

    asar.createPackage(projectDir.path('build'), finalAppDir.path('Contents/Resources/app.asar'), function() {
        deferred.resolve();
    });

    return deferred.promise;
};

var finalize = function () {
    // Prepare main Info.plist
    var info = projectDir.read('resources/osx/Info.plist');
    info = utils.replace(info, {
        productName: manifest.productName,
        identifier: manifest.identifier,
        version: manifest.version
    });
    finalAppDir.write('Contents/Info.plist', info);

    // Prepare Info.plist of Helper apps
    [' EH', ' NP', ''].forEach(function (helper_suffix) {
        info = projectDir.read('resources/osx/helper_apps/Info' + helper_suffix + '.plist');
        info = utils.replace(info, {
            productName: manifest.productName,
            identifier: manifest.identifier
        });
        finalAppDir.write('Contents/Frameworks/Electron Helper' + helper_suffix + '.app/Contents/Info.plist', info);
    });

    // Copy icon
    projectDir.copy('resources/osx/icon.icns', finalAppDir.path('Contents/Resources/icon.icns'));

    return Q();
};

var renameApp = function() {
    // Rename helpers
    [' Helper EH', ' Helper NP', ' Helper'].forEach(function (helper_suffix) {
        finalAppDir.rename('Contents/Frameworks/Electron' + helper_suffix + '.app/Contents/MacOS/Electron' + helper_suffix, manifest.productName + helper_suffix );
        finalAppDir.rename('Contents/Frameworks/Electron' + helper_suffix + '.app', manifest.productName + helper_suffix + '.app');
    });
    // Rename application
    finalAppDir.rename('Contents/MacOS/Electron', manifest.productName);
    return Q();
}

var signApp = function() {
    var deferred = Q.defer();

    gulpUtil.log('Signing file...');
    childProcess.exec('codesign --deep --force --verbose --sign "Developer ID Application: Konecty Informatica Ltda (DX85ENM22A)" ' + finalAppDir.cwd(), function (error, stdout, stderr) {
        if (error || stderr) {
            console.log("ERROR while signing file");
            console.log(error);
            console.log(stderr);
        } else {
            gulpUtil.log('Signing file DONE!');
        }
        deferred.resolve();
    });
    return deferred.promise;
}

var packToDmgFile = function () {
    var deferred = Q.defer();

    var appdmg = require('appdmg');
    var dmgName = manifest.name + '_' + manifest.version + '.dmg';

    // Prepare appdmg config
    var dmgManifest = projectDir.read('resources/osx/appdmg.json');
    dmgManifest = utils.replace(dmgManifest, {
        productName: manifest.productName,
        appPath: finalAppDir.path(),
        dmgIcon: projectDir.path("resources/osx/dmg-icon.icns"),
        dmgBackground: projectDir.path("resources/osx/dmg-background.png")
    });
    tmpDir.write('appdmg.json', dmgManifest);

    // Delete DMG file with this name if already exists
    releasesDir.remove(dmgName);

    gulpUtil.log('Packaging to DMG file...');

    var readyDmgPath = releasesDir.path(dmgName);
    appdmg({
        source: tmpDir.path('appdmg.json'),
        target: readyDmgPath
    })
    .on('error', function (err) {
        console.error(err);
    })
    .on('finish', function () {
        gulpUtil.log('DMG file ready!', readyDmgPath);
        deferred.resolve();
    });

    return deferred.promise;
};

var cleanClutter = function () {
    return tmpDir.removeAsync('.');
};

module.exports = function () {
    return init()
    .then(copyRuntime)
    .then(cleanupRuntime)
    .then(packageBuiltApp)
    .then(finalize)
    .then(renameApp)
    .then(signApp)
    .then(packToDmgFile)
    .then(cleanClutter);
};
<|endoftext|>


<commit_before>'use strict';

var Q = require('q');
var gulpUtil = require('gulp-util');
var childProcess = require('child_process');
var jetpack = require('fs-jetpack');
var asar = require('asar');
var utils = require('./utils');

var projectDir;
var releasesDir;
var tmpDir;
var finalAppDir;
var manifest;

var init = function () {
    projectDir = jetpack;
    tmpDir = projectDir.dir('./tmp', { empty: true });
    releasesDir = projectDir.dir('./releases');
    manifest = projectDir.read('app/package.json', 'json');
    finalAppDir = tmpDir.cwd(manifest.productName + '.app');

    return Q();
};

var copyRuntime = function () {
    return projectDir.copyAsync('node_modules/electron-prebuilt/dist/Electron.app', finalAppDir.path());
};

var cleanupRuntime = function() {
    finalAppDir.remove('Contents/Resources/default_app');
    finalAppDir.remove('Contents/Resources/atom.icns');
    return Q();
}

var packageBuiltApp = function () {
    var deferred = Q.defer();

    asar.createPackage(projectDir.path('build'), finalAppDir.path('Contents/Resources/app.asar'), function() {
        deferred.resolve();
    });

    return deferred.promise;
};

var finalize = function () {
    // Prepare main Info.plist
    var info = projectDir.read('resources/osx/Info.plist');
    info = utils.replace(info, {
        productName: manifest.productName,
        identifier: manifest.identifier,
        version: manifest.version
    });
    finalAppDir.write('Contents/Info.plist', info);

    // Prepare Info.plist of Helper apps
    [' EH', ' NP', ''].forEach(function (helper_suffix) {
        info = projectDir.read('resources/osx/helper_apps/Info' + helper_suffix + '.plist');
        info = utils.replace(info, {
            productName: manifest.productName,
            identifier: manifest.identifier
        });
        finalAppDir.write('Contents/Frameworks/Electron Helper' + helper_suffix + '.app/Contents/Info.plist', info);
    });

    // Copy icon
    projectDir.copy('resources/osx/icon.icns', finalAppDir.path('Contents/Resources/icon.icns'));

    return Q();
};

var renameApp = function() {
    // Rename helpers
    [' Helper EH', ' Helper NP', ' Helper'].forEach(function (helper_suffix) {
        finalAppDir.rename('Contents/Frameworks/Electron' + helper_suffix + '.app/Contents/MacOS/Electron' + helper_suffix, manifest.productName + helper_suffix );
        finalAppDir.rename('Contents/Frameworks/Electron' + helper_suffix + '.app', manifest.productName + helper_suffix + '.app');
    });
    // Rename application
    finalAppDir.rename('Contents/MacOS/Electron', manifest.productName);
    return Q();
}

var signApp = function() {
    var deferred = Q.defer();

    gulpUtil.log('Signing file...');
    childProcess.exec('codesign --deep --force --verbose --sign "Developer ID Application: Konecty Informatica Ltda (DX85ENM22A)" ' + finalAppDir.cwd(), function (error, stdout, stderr) {
        if (error || stderr) {
            console.log("ERROR while signing file");
            console.log(error);
            console.log(stderr);
        } else {
            gulpUtil.log('Signing file DONE!');
        }
        deferred.resolve();
    });
    return deferred.promise;
}

var packToDmgFile = function () {
    var deferred = Q.defer();

    var appdmg = require('appdmg');
    var dmgName = manifest.name + '_' + manifest.version + '.dmg';

    // Prepare appdmg config
    var dmgManifest = projectDir.read('resources/osx/appdmg.json');
    dmgManifest = utils.replace(dmgManifest, {
        productName: manifest.productName,
        appPath: finalAppDir.path(),
        dmgIcon: projectDir.path("resources/osx/dmg-icon.icns"),
        dmgBackground: projectDir.path("resources/osx/dmg-background.png")
    });
    tmpDir.write('appdmg.json', dmgManifest);

    // Delete DMG file with this name if already exists
    releasesDir.remove(dmgName);

    gulpUtil.log('Packaging to DMG file...');

    var readyDmgPath = releasesDir.path(dmgName);
    appdmg({
        source: tmpDir.path('appdmg.json'),
        target: readyDmgPath
    })
    .on('error', function (err) {
        console.error(err);
    })
    .on('finish', function () {
        gulpUtil.log('DMG file ready!', readyDmgPath);
        deferred.resolve();
    });

    return deferred.promise;
};

var cleanClutter = function () {
    return tmpDir.removeAsync('.');
};

module.exports = function () {
    return init()
    .then(copyRuntime)
    .then(cleanupRuntime)
    .then(packageBuiltApp)
    .then(finalize)
    .then(renameApp)
    .then(signApp)
    .then(packToDmgFile)
    .then(cleanClutter);
};
<commit_msg>removed verbose<commit_after>'use strict';

var Q = require('q');
var gulpUtil = require('gulp-util');
var childProcess = require('child_process');
var jetpack = require('fs-jetpack');
var asar = require('asar');
var utils = require('./utils');

var projectDir;
var releasesDir;
var tmpDir;
var finalAppDir;
var manifest;

var init = function () {
    projectDir = jetpack;
    tmpDir = projectDir.dir('./tmp', { empty: true });
    releasesDir = projectDir.dir('./releases');
    manifest = projectDir.read('app/package.json', 'json');
    finalAppDir = tmpDir.cwd(manifest.productName + '.app');

    return Q();
};

var copyRuntime = function () {
    return projectDir.copyAsync('node_modules/electron-prebuilt/dist/Electron.app', finalAppDir.path());
};

var cleanupRuntime = function() {
    finalAppDir.remove('Contents/Resources/default_app');
    finalAppDir.remove('Contents/Resources/atom.icns');
    return Q();
}

var packageBuiltApp = function () {
    var deferred = Q.defer();

    asar.createPackage(projectDir.path('build'), finalAppDir.path('Contents/Resources/app.asar'), function() {
        deferred.resolve();
    });

    return deferred.promise;
};

var finalize = function () {
    // Prepare main Info.plist
    var info = projectDir.read('resources/osx/Info.plist');
    info = utils.replace(info, {
        productName: manifest.productName,
        identifier: manifest.identifier,
        version: manifest.version
    });
    finalAppDir.write('Contents/Info.plist', info);

    // Prepare Info.plist of Helper apps
    [' EH', ' NP', ''].forEach(function (helper_suffix) {
        info = projectDir.read('resources/osx/helper_apps/Info' + helper_suffix + '.plist');
        info = utils.replace(info, {
            productName: manifest.productName,
            identifier: manifest.identifier
        });
        finalAppDir.write('Contents/Frameworks/Electron Helper' + helper_suffix + '.app/Contents/Info.plist', info);
    });

    // Copy icon
    projectDir.copy('resources/osx/icon.icns', finalAppDir.path('Contents/Resources/icon.icns'));

    return Q();
};

var renameApp = function() {
    // Rename helpers
    [' Helper EH', ' Helper NP', ' Helper'].forEach(function (helper_suffix) {
        finalAppDir.rename('Contents/Frameworks/Electron' + helper_suffix + '.app/Contents/MacOS/Electron' + helper_suffix, manifest.productName + helper_suffix );
        finalAppDir.rename('Contents/Frameworks/Electron' + helper_suffix + '.app', manifest.productName + helper_suffix + '.app');
    });
    // Rename application
    finalAppDir.rename('Contents/MacOS/Electron', manifest.productName);
    return Q();
}

var signApp = function() {
    var deferred = Q.defer();

    gulpUtil.log('Signing file...');
    childProcess.exec('codesign --deep --force --sign "Developer ID Application: Konecty Informatica Ltda (DX85ENM22A)" ' + finalAppDir.cwd(), function (error, stdout, stderr) {
        if (error || stderr) {
            console.log("ERROR while signing file");
            console.log(error);
            console.log(stderr);
        } else {
            gulpUtil.log('Signing file DONE!');
        }
        deferred.resolve();
    });
    return deferred.promise;
}

var packToDmgFile = function () {
    var deferred = Q.defer();

    var appdmg = require('appdmg');
    var dmgName = manifest.name + '_' + manifest.version + '.dmg';

    // Prepare appdmg config
    var dmgManifest = projectDir.read('resources/osx/appdmg.json');
    dmgManifest = utils.replace(dmgManifest, {
        productName: manifest.productName,
        appPath: finalAppDir.path(),
        dmgIcon: projectDir.path("resources/osx/dmg-icon.icns"),
        dmgBackground: projectDir.path("resources/osx/dmg-background.png")
    });
    tmpDir.write('appdmg.json', dmgManifest);

    // Delete DMG file with this name if already exists
    releasesDir.remove(dmgName);

    gulpUtil.log('Packaging to DMG file...');

    var readyDmgPath = releasesDir.path(dmgName);
    appdmg({
        source: tmpDir.path('appdmg.json'),
        target: readyDmgPath
    })
    .on('error', function (err) {
        console.error(err);
    })
    .on('finish', function () {
        gulpUtil.log('DMG file ready!', readyDmgPath);
        deferred.resolve();
    });

    return deferred.promise;
};

var cleanClutter = function () {
    return tmpDir.removeAsync('.');
};

module.exports = function () {
    return init()
    .then(copyRuntime)
    .then(cleanupRuntime)
    .then(packageBuiltApp)
    .then(finalize)
    .then(renameApp)
    .then(signApp)
    .then(packToDmgFile)
    .then(cleanClutter);
};
<|endoftext|>


<commit_before>'use strict';

exports.run = function(grunt, taskData) {
    var EC2_INSTANCE_LAUNCH_FAIL = '✗'.red + ' EC2 instance launched failed with %s';
    var EC2_INSTANCE_LAUNCH_SUCCESS = '↗'.yellow + ' EC2 instance(s) launched, instance ids:: %s';
    var EC2_INSTANCE_TAG_FAIL = '✗'.red + ' EC2 instance tagging failed with %s';
    var EC2_INSTANCE_TAG_SUCCESS = '↗'.blue + ' EC2 instance tagged';
    var EC2_INSTANCE_LAUNCHED_TO_DATE = '↗'.yellow + ' EC2 instance(s) launched so far during entire session, instance ids:: %s';

    var AWS = taskData.AWS;
    var _ = require("underscore");
    var util = require('util');
    var done = taskData.async();

    if (taskData.data.ec2 !== undefined) {
        var task = taskData.data.ec2;
        var options = _(grunt.config.get('aws.options') || {}).chain()
                .extend(taskData.data.options || {})
                .extend(taskData.data.ec2.options || {})
                .value();
    } else {
        var task = taskData;
    }

    var ami;

    var findAMI = function(options, task) {
        if (task.findAMI) {
            var findAMIOptions = _(_.clone(options)).extend(task.findAMI.options || {});
            if (findAMIOptions.region == 'us-standard') {
                findAMIOptions.region = 'us-east-1';
            }
            AWS.config.update(_.pick(findAMIOptions, 'accessKeyId', 'secretAccessKey', 'region'));
            var ec2 = new AWS.EC2(_.pick(findAMIOptions, 'accessKeyId', 'secretAccessKey', 'region'));

            ec2.describeImages(_.pick(task.findAMI, "Owners","ExecutableUsers","Filters"),
                function(err, data) {
                    if (err) {
                        grunt.fail.warn("Fetching AMI info failed. AWS response: "+ JSON.stringify(err));
                    }
                    else {
                        grunt.log.writeln("Fetching AMI info succeded");
                        data.Images.sort(function(a,b){
                            if (a.Name > b.Name) {
                                return -1;
                            }
                            else {
                                return 1;
                            }
                        });
                        ami = data.Images[0].ImageId;

                        grunt.log.writeln("Found latest matching AMI: " + ami + " - \"" +data.Images[0].Name +"\"" );
                        startEC2(options, task);
                    }
            });
        } else {
            startEC2(options, task);
        }
    };

    var startEC2 = function(options, task) {
        if (task.startEC2) {
            var startEC2Options = _(_.clone(options)).extend(task.startEC2.options || {});
            if (startEC2Options.region == 'us-standard') {
                startEC2Options.region = 'us-east-1';
            }
            task.startEC2['UserData'] = new Buffer(JSON.stringify(task.startEC2['UserData'])).toString('base64');
            AWS.config.update(_.pick(startEC2Options, 'accessKeyId', 'secretAccessKey', 'region'));
            var ec2 = new AWS.EC2(_.pick(startEC2Options, 'accessKeyId', 'secretAccessKey', 'region'));
            task.startEC2['ImageId'] = (task.startEC2['ImageId'] || ami);

            ec2.runInstances(_.pick(task.startEC2, "ImageId", "MinCount", "MaxCount",
                                                   "KeyName", "InstanceType", "UserData",
                                                   "Placement", "SecurityGroups"), function(err, data) {
                if (err) {
                    grunt.fail.warn(util.format(EC2_INSTANCE_LAUNCH_FAIL, JSON.stringify(err)));
                    done();
                } else {
                    var instances = new Array();

                    for (var i = 0; i<data.Instances.length; i++) {
                        instances.push(data.Instances[i].InstanceId);
                    }

                    var total_launched_ec2_instance_ids = grunt.config('launched_ec2_instance_ids') || new Array();
                    grunt.config.set('launched_ec2_instance_ids', total_launched_ec2_instance_ids.concat(instances));

                    grunt.log.writeln(util.format(EC2_INSTANCE_LAUNCH_SUCCESS, instances.join(', ')));
                    grunt.log.writeln(util.format(EC2_INSTANCE_LAUNCHED_TO_DATE, grunt.config('launched_ec2_instance_ids').join(', ')));

                    if (task.startEC2.Tags !== undefined) {
                        tagInstances(instances, startEC2Options, task.startEC2.Tags);
                    } else {
                        grunt.config.writeln("No tags defined to add to instances.");
                        done();
                    }
                }
            });
        }
    }

    var tagInstances = function(instances, options, tags, max_retries) {
        if (max_retries === undefined) {
            max_retries = 5;
        }

        if (tags) {
            var ec2 = new AWS.EC2(_.pick(options, 'accessKeyId', 'secretAccessKey', 'region'));
            ec2.createTags({Resources: instances, Tags: tags},
                function(err, data) {
                    if (err) {
                        if (max_retries > 0) {
                            tagInstances(instances, options, tags, max_retries - 1);
                        } else {
                            grunt.fail.warn(util.format(EC2_INSTANCE_TAG_FAIL, JSON.stringify(err)));
                        }
                    } else {
                        grunt.log.writeln(EC2_INSTANCE_TAG_SUCCESS);
                    }
                    done();
            });
        }
    }

    var terminateEC2 = function(options, task) {
        if (task.terminateEC2) {
            var terminateEC2Options = _(_.clone(options)).extend(task.terminateEC2.options || {});
            if (terminateEC2Options.region == 'us-standard') {
                terminateEC2Options.region = 'us-east-1';
            }
            AWS.config.update(_.pick(terminateEC2Options, 'accessKeyId', 'secretAccessKey', 'region'));
            var ec2 = new AWS.EC2(_.pick(terminateEC2Options, 'accessKeyId', 'secretAccessKey', 'region'));

            ec2.terminateInstances(_.pick(task.terminateEC2, "InstanceIds"),
                function(err, data) {
                    if (err) {
                        grunt.fail.warn("Terminating EC2 intances failed. AWS response: \n"+ JSON.stringify(err));
                    }
                    else {
                        grunt.log.writeln(JSON.stringify(data));
                    }
            });
        }
    }

    findAMI(options,task);
    //removeFromAmi(options,task);
    //addToAMI(options,task);
    //terminateEC2(options,task);
};
<commit_msg>cleanup<commit_after>'use strict';

exports.run = function (grunt, taskData) {
    var EC2_INSTANCE_LAUNCH_FAIL = '✗'.red + ' EC2 instance launched failed with %s';
    var EC2_INSTANCE_LAUNCH_SUCCESS = '↗'.yellow + ' EC2 instance(s) launched, instance ids:: %s';
    var EC2_INSTANCE_TAG_FAIL = '✗'.red + ' EC2 instance tagging failed with %s';
    var EC2_INSTANCE_TAG_SUCCESS = '↗'.blue + ' EC2 instance tagged';
    var EC2_INSTANCE_LAUNCHED_TO_DATE = '↗'.yellow + ' EC2 instance(s) launched so far during entire session, instance ids:: %s';

    var AWS = taskData.AWS;
    var _ = require("underscore");
    var util = require('util');
    var done = taskData.async();

    if (taskData.data.ec2 !== undefined) {
        var task = taskData.data.ec2;
        var options = _(grunt.config.get('aws.options') || {}).chain()
                .extend(taskData.data.options || {})
                .extend(taskData.data.ec2.options || {})
                .value();
    } else {
        var task = taskData;
    }

    var ami;

    var findAMI = function (options, task) {
        if (task.findAMI) {
            var findAMIOptions = _(_.clone(options)).extend(task.findAMI.options || {});
            if (findAMIOptions.region == 'us-standard') {
                findAMIOptions.region = 'us-east-1';
            }
            AWS.config.update(_.pick(findAMIOptions, 'accessKeyId', 'secretAccessKey', 'region'));
            var ec2 = new AWS.EC2(_.pick(findAMIOptions, 'accessKeyId', 'secretAccessKey', 'region'));

            ec2.describeImages(_.pick(task.findAMI, "Owners","ExecutableUsers","Filters"),
                function (err, data) {
                    if (err) {
                        grunt.fail.warn("Fetching AMI info failed. AWS response: "+ JSON.stringify(err));
                    }
                    else {
                        grunt.log.writeln("Fetching AMI info succeded");
                        data.Images.sort(function (a, b) {
                            if (a.Name > b.Name) {
                                return -1;
                            }
                            else {
                                return 1;
                            }
                        });
                        ami = data.Images[0].ImageId;

                        grunt.log.writeln("Found latest matching AMI: " + ami + " - \"" +data.Images[0].Name +"\"" );
                        startEC2(options, task);
                    }
            });
        } else {
            startEC2(options, task);
        }
    };

    var startEC2 = function (options, task) {
        if (task.startEC2) {
            var startEC2Options = _(_.clone(options)).extend(task.startEC2.options || {});
            if (startEC2Options.region == 'us-standard') {
                startEC2Options.region = 'us-east-1';
            }
            task.startEC2['UserData'] = new Buffer(JSON.stringify(task.startEC2['UserData'])).toString('base64');
            AWS.config.update(_.pick(startEC2Options, 'accessKeyId', 'secretAccessKey', 'region'));
            var ec2 = new AWS.EC2(_.pick(startEC2Options, 'accessKeyId', 'secretAccessKey', 'region'));
            task.startEC2['ImageId'] = (task.startEC2['ImageId'] || ami);

            ec2.runInstances(_.pick(task.startEC2, "ImageId", "MinCount", "MaxCount",
                                                   "KeyName", "InstanceType", "UserData",
                                                   "Placement", "SecurityGroups"), function (err, data) {
                if (err) {
                    grunt.fail.warn(util.format(EC2_INSTANCE_LAUNCH_FAIL, JSON.stringify(err)));
                    done();
                } else {
                    var instances = new Array();

                    for (var i = 0; i<data.Instances.length; i++) {
                        instances.push(data.Instances[i].InstanceId);
                    }

                    var total_launched_ec2_instance_ids = grunt.config('launched_ec2_instance_ids') || new Array();
                    grunt.config.set('launched_ec2_instance_ids', total_launched_ec2_instance_ids.concat(instances));

                    grunt.log.writeln(util.format(EC2_INSTANCE_LAUNCH_SUCCESS, instances.join(', ')));
                    grunt.log.writeln(util.format(EC2_INSTANCE_LAUNCHED_TO_DATE, grunt.config('launched_ec2_instance_ids').join(', ')));

                    if (task.startEC2.Tags !== undefined) {
                        tagInstances(instances, startEC2Options, task.startEC2.Tags);
                    } else {
                        grunt.config.writeln("No tags defined to add to instances.");
                        done();
                    }
                }
            });
        }
    }

    var tagInstances = function (instances, options, tags, max_retries) {
        if (max_retries === undefined) {
            max_retries = 5;
        }

        if (tags) {
            var ec2 = new AWS.EC2(_.pick(options, 'accessKeyId', 'secretAccessKey', 'region'));
            ec2.createTags({Resources: instances, Tags: tags},
                function (err, data) {
                    if (err) {
                        if (max_retries > 0) {
                            tagInstances(instances, options, tags, max_retries - 1);
                        } else {
                            grunt.fail.warn(util.format(EC2_INSTANCE_TAG_FAIL, JSON.stringify(err)));
                        }
                    } else {
                        grunt.log.writeln(EC2_INSTANCE_TAG_SUCCESS);
                    }
                    done();
            });
        }
    }

    var terminateEC2 = function (options, task) {
        if (task.terminateEC2) {
            var terminateEC2Options = _(_.clone(options)).extend(task.terminateEC2.options || {});
            if (terminateEC2Options.region == 'us-standard') {
                terminateEC2Options.region = 'us-east-1';
            }
            AWS.config.update(_.pick(terminateEC2Options, 'accessKeyId', 'secretAccessKey', 'region'));
            var ec2 = new AWS.EC2(_.pick(terminateEC2Options, 'accessKeyId', 'secretAccessKey', 'region'));

            ec2.terminateInstances(_.pick(task.terminateEC2, "InstanceIds"),
                function (err, data) {
                    if (err) {
                        grunt.fail.warn("Terminating EC2 intances failed. AWS response: \n"+ JSON.stringify(err));
                    }
                    else {
                        grunt.log.writeln(JSON.stringify(data));
                    }
            });
        }
    }

    findAMI(options, task);
    //removeFromAmi(options,task);
    //addToAMI(options,task);
    //terminateEC2(options,task);
};
<|endoftext|>


<commit_before>/* This file has been generated by ox-ui-module generator.
 * Please only apply minor changes (better no changes at all) to this file
 * if you want to be able to run the generator again without much trouble.
 *
 * If you really have to change this file for whatever reason, try to contact
 * the core team and describe your use-case. May be, your changes can be
 * integrated into the templates to be of use for everybody.
 */
'use strict';

module.exports = function (grunt) {
    var path = require('path');
    ['default'].concat(grunt.file.expand({cwd: 'apps/themes/'}, '*/definitions.less')).forEach(function (file) {
        var themeName = file.replace(/\/definitions.less$/, '');
        var theme = {};
        theme[themeName] = {
            options: {
                compress: !grunt.config('local.debug'),
                cleancss: !grunt.config('local.debug'),
                ieCompat: false,
                syncImport: true,
                strictMath: false,
                strictUnits: false,
                relativeUrls: false,
                paths: [
                    'apps/themes',
                    'lib/appsuite/apps/themes',
                    'bower_components/bootstrap/less',
                    'bower_components/font-awesome/less'
                ],
                imports: {
                    reference: [
                        'variables.less',
                        'mixins.less'
                    ],
                    less: [
                        'definitions.less',
                        themeName + '/definitions.less'
                    ]
                }
            },
            files: [
                {
                    src: ['apps/themes/style.less'],
                    expand: true,
                    rename: function (dest) { return dest; },
                    cwd: (grunt.option('coreDir') || grunt.config('local.coreDir') || ''),
                    dest: 'build/apps/themes/' + themeName + '/common.css'
                },
                {
                    src: [
                        'bower_components/bootstrap/less/bootstrap.less',
                        'bower_components/bootstrap-datepicker/less/datepicker3.less',
                        'bower_components/font-awesome/less/font-awesome.less',
                        'apps/themes/' + themeName + '/style.less'
                    ],
                    expand: true,
                    rename: function (dest) { return dest; },
                    filter: function () {
                        //only generate this file if there is a style.less for this theme
                        return grunt.file.exists('apps/themes/' + themeName + '/style.less');
                    },
                    dest: 'build/apps/themes/' + themeName + '/style.css'
                },
                {
                    src: ['**/*.less', '!themes/**/*.less', '!themes/*.less'],
                    expand: true,
                    ext: '.css',
                    cwd: 'apps/',
                    dest: 'build/apps/themes/' + themeName + '/'
                },
                {
                    src: ['**/*.less', '!themes/**/*.less', '!themes/*.less'],
                    expand: true,
                    ext: '.css',
                    cwd: path.join((grunt.option('coreDir') || grunt.config('local.coreDir') || ''), 'apps/'),
                    dest: 'build/apps/themes/' + themeName + '/'
                }
            ]
        };
        grunt.config.extend('less', theme);
    });

    grunt.loadNpmTasks('assemble-less');
};
<commit_msg>update less task to work as expected<commit_after>/* This file has been generated by ox-ui-module generator.
 * Please only apply minor changes (better no changes at all) to this file
 * if you want to be able to run the generator again without much trouble.
 *
 * If you really have to change this file for whatever reason, try to contact
 * the core team and describe your use-case. May be, your changes can be
 * integrated into the templates to be of use for everybody.
 */
'use strict';

module.exports = function (grunt) {
    var path = require('path');
    var coreDir = grunt.option('coreDir') || grunt.config('local.coreDir') || '';

    //TODO: get rid of coreDir dependency for less files
    //if no coreDir is specified, compile everything for 'default' theme, this can be used
    //with local versions of core definitions.less, mixins.less and style.less.
    //Just place those files in lib/appsuite/apps/themes/
    var coreThemes = (coreDir ?
        grunt.file.expand({cwd: path.join(coreDir, 'apps/themes/')}, '*/definitions.less') : []
    ).map(function (file) {
        return file.replace(/\/definitions.less$/, '');
    });
    var localThemes = grunt.file.expand({cwd: 'apps/themes/'}, '*/definitions.less').map(function (file) {
        return file.replace(/\/definitions.less$/, '');
    });

    function optionsFor(themeName) {
        return {
            compress: !grunt.config('local.debug'),
            cleancss: !grunt.config('local.debug'),
            ieCompat: false,
            syncImport: true,
            strictMath: false,
            strictUnits: false,
            relativeUrls: false,
            paths: [
                'bower_components/bootstrap/less',
                'bower_components/font-awesome/less',
                'lib/appsuite/apps/themes',
                path.join(coreDir, 'apps/themes'),
                'apps/themes',
            ],
            imports: {
                reference: [
                    'variables.less',
                    'mixins.less'
                ],
                less: [
                    'definitions.less',
                    themeName + '/definitions.less'
                ]
            }
        };
    }

    localThemes.forEach(function (themeName) {
        var theme = {};

        theme[themeName] = {
            options: optionsFor(themeName),
            files: [
                {
                    src: [
                        'bower_components/bootstrap/less/bootstrap.less',
                        'bower_components/bootstrap-datepicker/less/datepicker3.less',
                        'bower_components/font-awesome/less/font-awesome.less',
                        path.join(coreDir, 'apps/themes/style.less')
                    ],
                    expand: true,
                    rename: function (dest) { return dest; },
                    dest: 'build/apps/themes/' + themeName + '/common.css'
                },
                {
                    src: [
                        'apps/themes/' + themeName + '/style.less'
                    ],
                    expand: true,
                    rename: function (dest) { return dest; },
                    filter: function () {
                        //only generate this file if there is a style.less for this theme
                        return grunt.file.exists('apps/themes/' + themeName + '/style.less');
                    },
                    dest: 'build/apps/themes/' + themeName + '/style.css'
                },
                {
                    src: ['**/*.less', '!themes/**/*.less', '!themes/*.less'],
                    expand: true,
                    ext: '.css',
                    cwd: path.join(coreDir, 'apps/'),
                    dest: 'build/apps/themes/' + themeName + '/'
                },
                {
                    src: ['**/*.less', '!themes/**/*.less', '!themes/*.less'],
                    expand: true,
                    ext: '.css',
                    cwd: 'apps/',
                    dest: 'build/apps/themes/' + themeName + '/'
                }
            ]
        };
        grunt.config.extend('less', theme);
    });

    coreThemes.forEach(function (themeName) {
        var theme = {};
        theme['core_theme/' + themeName + '+local_less'] = {
            options: optionsFor(themeName),
            files: [
                {
                    src: ['**/*.less', '!themes/**/*.less', '!themes/*.less'],
                    expand: true,
                    ext: '.css',
                    cwd: 'apps/',
                    dest: 'build/apps/themes/' + themeName + '/'
                }
            ]
        };
        grunt.config.extend('less', theme);
    });

    //init empty less config, if no themes detected, this will prevent grunt-newer
    //from failing
    grunt.config.extend('less', {});

    grunt.loadNpmTasks('assemble-less');
};
<|endoftext|>


<commit_before>const webpack = require('webpack');

module.exports = {
	devtool: 'eval',
	debug: false,
	cache: true,
	resolve: {
		extensions: ['', '.ts', '.js']
	},
	module: {
		preLoaders: [
			{test: /\.ts$/, loader: 'tslint-loader', exclude: ['./node_modules']},
			{test: /\.js$/, loader: "source-map-loader", exclude: ['./node_modules/rxjs']}
		],
		loaders: [
			{
				test: /\.ts$/,
				loader: 'ts-loader',
				query: {transpileOnly: true},
				exclude: [/\.(spec|e2e)\.ts$/]
			}
		]
	},

	plugins: [
		new webpack.optimize.OccurenceOrderPlugin(),
		new webpack.optimize.DedupePlugin(),
		new webpack.NoErrorsPlugin(),
		new webpack.HotModuleReplacementPlugin()
	],

	tslint: {
		emitErrors: false,
		failOnHint: false,
		resourcePath: 'src'
	},
	node: {global: 'window', progress: false, crypto: 'empty', module: false, clearImmediate: false, setImmediate: false}
};
<commit_msg>fix webpack config hot module<commit_after>const webpack = require('webpack');

module.exports = {
	devtool: 'eval',
	debug: false,
	cache: true,
	resolve: {
		extensions: ['', '.ts', '.js']
	},
	module: {
		preLoaders: [
			{test: /\.ts$/, loader: 'tslint-loader', exclude: ['./node_modules']},
			{test: /\.js$/, loader: "source-map-loader", exclude: ['./node_modules/rxjs']}
		],
		loaders: [
			{
				test: /\.ts$/,
				loader: 'ts-loader',
				query: {transpileOnly: true},
				exclude: [/\.(spec|e2e)\.ts$/]
			}
		]
	},

	plugins: [
		new webpack.optimize.OccurenceOrderPlugin(),
		new webpack.optimize.DedupePlugin(),
		new webpack.NoErrorsPlugin()
	],

	tslint: {
		emitErrors: false,
		failOnHint: false,
		resourcePath: 'src'
	},
	node: {global: 'window', progress: false, crypto: 'empty', module: false, clearImmediate: false, setImmediate: false}
};
<|endoftext|>