<commit_before>var su = ''; //http://ec2-54-200-40-68.us-west-2.compute.amazonaws.com:8080';

var _user_details = '/user/details';

var _user_details = 'http://web.mit.edu/ambhave/www/suitup/user_details.json';

function init_user_details() {
    console.log('init_user_details()');

    $.getJSON(_user_details, function (data) {
        $('.user_username').text(data['username']);
    }).error(function (jqXhr, textStatus, error) {
        alert("ERROR: " + textStatus + ", " + error);
    });
}

$(document).ready(function () {
  //  login();
    //  init_user_details();

});

function chat_join(s) {
    $.ajax({
        type: "GET",
        url: su + '/chatroom/join',
        success: function (data) {
            chatroomid = JSON.parse(data).crid;
            $('#firepad').html('');
            var firepadRef = new Firebase('//hackmitsuitup.firebaseIO.com/firepads/' + chatroomid);
            var codeMirror = CodeMirror(document.getElementById('firepad'), {
                lineNumbers: true,
                mode: 'python'
            });
            var firepad = Firepad.fromCodeMirror(firepadRef, codeMirror);

            setTimeout(join_room, 2000);
            setTimeout(chat_check, 1000);
        }
    });
}

function join_room() {
    // webrtc.createRoom(chatroomid);
    webrtc.joinRoom(String(chatroomid));
}

function chat_leave() {
    $.ajax({
        type: "GET",
        url: su + '/chatroom/leave',
        success: function (data) {
            $('#firepad').html('');
        }
    });
    chatroomid = null;
    webrtc.leaveRoom(webrtc.roomName);
}

function chat_send(chat, convo) {
    $.ajax({
        type: "GET",
        url: su + '/message/send',
        data: { 's': $('#' + chat).val() }
    });
    $('#' + convo).val($('#' + convo).val() + '\nMe: ' + $('#' + chat).val());
    $('#' + chat).val('');
}

function chat_check() {
    $.ajax({
        type: "GET",
        url: su + '/message/check',
        success: function (data) {
            sts = JSON.parse(data).status;
            if ( sts == "failure") {
                console.log("Rejoining to new person");
                chat_leave();
                chat_join();
            } else {
                if(JSON.parse(data).s != "") {
                    $('#convo').val($('#convo').val() + '\nOther: ' + JSON.parse(data).s);
                    setTimeout(chat_check, 1000);
                } else {
                    setTimeout(chat_check, 2000);
                }
            }
        }
    });
}

// Load the SDK asynchronously
(function (d) {
    var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
    if (d.getElementById(id)) { return; }
    js = d.createElement('script'); js.id = id; js.async = true;
    js.src = "//connect.facebook.net/en_US/all.js";
    ref.parentNode.insertBefore(js, ref);
}(document));

var access_token = null;
var user_city = null;
var fb_user = null;

function login() {
    _login_wait();

    FB.login(function (response) {
        //_check_login();
    });
}
function logout() {
    _login_wait();

    FB.logout(function (response) {
        //_login_bad();
    });
}

// Additional JS functions here
window.fbAsyncInit = function () {
    FB.init({
        appId: '615988445111525', // App ID
        channelUrl: '//localhost:8000/channel.html', // Channel File
        status: true, // check login status
        cookie: true, // enable cookies to allow the server to access the session
        xfbml: true  // parse XFBML
    });

    // Additional init code here
    //_check_login();
    _login_wait();
    FB.getLoginStatus(function (response) {
        if (response.status !== 'connected') {
            _login_bad();
        }
    });

    FB.Event.subscribe('auth.statusChange', function (response) {
        _check_login();
        console.log(response);
    });
};

/* Helper Functions */
function _hide_all_login() {
    $('.pLoginBad').hide();
    $('.pLoginDone').hide();
    $('.pLoginWait').hide();
}
function _check_login() {
    _login_wait();
    FB.getLoginStatus(function (response) {
        if (response.status === 'connected') {
            _login_done(response);
        }
        else {
            _login_bad();
        }
    });
}
function _login_wait() {
    _hide_all_login();
    $('.pLoginWait').show();
}
function _login_bad() {
    _hide_all_login();
    $('.pLoginBad').show();
}
function _login_done(response) {

    if (response != null)
        access_token = response.authResponse.accessToken;

    FB.api('/me?fields=picture,name', function (response) {
        fb_user = response;
        console.log(response);
        $('.user_username').text(response.name);
        $('.user_photourl').attr('src', response.picture.data.url);

        _hide_all_login();
        $('.pLoginDone').show();
    });

    // TODO: UNCOMMENT THIS!!!!!!!!!!!!!!!!!!!!!!!!!!!
    $.ajax({ url: su + '/login?access_token=' + access_token }).success(function (data) { chat_join(); });

    //$.ajax({url:"demo_test.txt",success:function(result){    $("#div1").html(result);  }});

    /*

    FB.api('/me/home', function(response) {
       console.log(response);
       $('#news_feed').empty();
       for (var i = 0; i < response['data'].length; i++) {
           var item = response['data'][i];
           var txt = '
 \
                    \
                        \
                    \

  \

' + item['from']['name'] + '
            \

 \

';
           $('#news_feed').append(txt);
       }
    });*/
}
function _fatal_error(message) {
    $('body').html('Fatal Error! Please refresh the page

Message: ' + message);
}

<commit_msg>Add questions<commit_after>var su = ''; //http://ec2-54-200-40-68.us-west-2.compute.amazonaws.com:8080';

var _user_details = '/user/details';

var _user_details = 'http://web.mit.edu/ambhave/www/suitup/user_details.json';

function init_user_details() {
    console.log('init_user_details()');

    $.getJSON(_user_details, function (data) {
        $('.user_username').text(data['username']);
    }).error(function (jqXhr, textStatus, error) {
        alert("ERROR: " + textStatus + ", " + error);
    });
}

$(document).ready(function () {
  //  login();
    //  init_user_details();

});

function chat_join(s) {
    $.ajax({
        type: "GET",
        url: su + '/chatroom/join',
        success: function (data) {
            chatroomid = JSON.parse(data).crid;
            $('#firepad').html('');
            var firepadRef = new Firebase('//hackmitsuitup.firebaseIO.com/firepads/' + chatroomid);
            var codeMirror = CodeMirror(document.getElementById('firepad'), {
                lineNumbers: true,
                mode: 'python'
            });
            var firepad = Firepad.fromCodeMirror(firepadRef, codeMirror);

            setTimeout(join_room, 2000);
            setTimeout(chat_check, 1000);
            question_new();
        }
    });
}

function join_room() {
    // webrtc.createRoom(chatroomid);
    webrtc.joinRoom(String(chatroomid));
}

function chat_leave() {
    $.ajax({
        type: "GET",
        url: su + '/chatroom/leave',
        success: function (data) {
            $('#firepad').html('');
        }
    });
    chatroomid = null;
    webrtc.leaveRoom(webrtc.roomName);
}

function chat_send(chat, convo) {
    $.ajax({
        type: "GET",
        url: su + '/message/send',
        data: { 's': $('#' + chat).val() }
    });
    $('#' + convo).val($('#' + convo).val() + '\nMe: ' + $('#' + chat).val());
    $('#' + chat).val('');
}

function chat_check() {
    $.ajax({
        type: "GET",
        url: su + '/message/check',
        success: function (data) {
            sts = JSON.parse(data).status;
            if ( sts == "failure") {
                console.log("Rejoining to new person");
                chat_leave();
                chat_join();
            } else {
                if(JSON.parse(data).s != "") {
                    $('#convo').val($('#convo').val() + '\nOther: ' + JSON.parse(data).s);
                    setTimeout(chat_check, 1000);
                } else {
                    setTimeout(chat_check, 2000);
                }
            }
        }
    });
}

function question_new() {
    $.getJSON(su + '/question/new', function (data) {
        $('.questions_title').text(data['title']);
        $('.questions_body').text(data['body']);
    }).error(function (jqXhr, textStatus, error) {
        alert("ERROR: " + textStatus + ", " + error);
    });
}

// Load the SDK asynchronously
(function (d) {
    var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
    if (d.getElementById(id)) { return; }
    js = d.createElement('script'); js.id = id; js.async = true;
    js.src = "//connect.facebook.net/en_US/all.js";
    ref.parentNode.insertBefore(js, ref);
}(document));

var access_token = null;
var user_city = null;
var fb_user = null;

function login() {
    _login_wait();

    FB.login(function (response) {
        //_check_login();
    });
}
function logout() {
    _login_wait();

    FB.logout(function (response) {
        //_login_bad();
    });
}

// Additional JS functions here
window.fbAsyncInit = function () {
    FB.init({
        appId: '615988445111525', // App ID
        channelUrl: '//localhost:8000/channel.html', // Channel File
        status: true, // check login status
        cookie: true, // enable cookies to allow the server to access the session
        xfbml: true  // parse XFBML
    });

    // Additional init code here
    //_check_login();
    _login_wait();
    FB.getLoginStatus(function (response) {
        if (response.status !== 'connected') {
            _login_bad();
        }
    });

    FB.Event.subscribe('auth.statusChange', function (response) {
        _check_login();
        console.log(response);
    });
};

/* Helper Functions */
function _hide_all_login() {
    $('.pLoginBad').hide();
    $('.pLoginDone').hide();
    $('.pLoginWait').hide();
}
function _check_login() {
    _login_wait();
    FB.getLoginStatus(function (response) {
        if (response.status === 'connected') {
            _login_done(response);
        }
        else {
            _login_bad();
        }
    });
}
function _login_wait() {
    _hide_all_login();
    $('.pLoginWait').show();
}
function _login_bad() {
    _hide_all_login();
    $('.pLoginBad').show();
}
function _login_done(response) {

    if (response != null)
        access_token = response.authResponse.accessToken;

    FB.api('/me?fields=picture,name', function (response) {
        fb_user = response;
        console.log(response);
        $('.user_username').text(response.name);
        $('.user_photourl').attr('src', response.picture.data.url);

        _hide_all_login();
        $('.pLoginDone').show();
    });

    // TODO: UNCOMMENT THIS!!!!!!!!!!!!!!!!!!!!!!!!!!!
    $.ajax({ url: su + '/login?access_token=' + access_token }).success(function (data) { chat_join(); });

    //$.ajax({url:"demo_test.txt",success:function(result){    $("#div1").html(result);  }});

    /*

    FB.api('/me/home', function(response) {
       console.log(response);
       $('#news_feed').empty();
       for (var i = 0; i < response['data'].length; i++) {
           var item = response['data'][i];
           var txt = '
 \
                    \
                        \
                    \

  \

' + item['from']['name'] + '
            \

 \

';
           $('#news_feed').append(txt);
       }
    });*/
}
function _fatal_error(message) {
    $('body').html('Fatal Error! Please refresh the page

Message: ' + message);
}

<|endoftext|>


<commit_before>/* eslint no-var:0 prefer-spread:0 */
/* global module */

var forEach = require('lodash/collection/forEach')

// Main export
function HJSPlugin(options) {
	this.config = options || {}
	this.filename = options.filename || 'index.html'
}

HJSPlugin.prototype.apply = function (compiler) {
	var self = this
	var htmlFunction = this.config.html

	// let user pass `true` to use
	// the simple default
	// Same if `isDev` and `serveCustomHtmlInDev` is falsy
	if (!htmlFunction) {
		return
	}

	self.compiler = compiler

	compiler.plugin('emit', function (compiler, callback) {
		// store stats on self
		self.stats = compiler.getStats().toJson()
		var context = self.getAssets()

		// access to package info
		context.package = self.config.package

		// access to stats
		context.stats = self.stats

		// expose `isDev` flag to html function context
		context.isDev = self.config.isDev

		// handle both sync and async versions
		if (htmlFunction.length === 2) {
			htmlFunction(context, function (err, result) {
				if (err) throw err
				self.addAssets(compiler, result)
				callback()
			})
		}
		else {
			self.addAssets(compiler, htmlFunction(context))
			callback()
		}
	})
}

// Oddly enough we have to pass in the compiler here
// it's changed from when it was stored on `this` previously
HJSPlugin.prototype.addAssets = function (compiler, data) {
	var dataType = typeof data
	var pages
	// if it's a string, we assume it's an html
	// string for the index file
	if (dataType === 'string') {
		pages = {}
		pages[this.filename] = data
	}
	else if (dataType === 'object') {
		pages = data
	}
	else {
		throw new Error('Result from `html` callback must be a string or an object')
	}

	forEach(pages, function(asset, name) {
		compiler.assets[name] = {
			source: function () {
				return asset
			},
			size: function () {
				return asset.length
			},
		}
	})
}

HJSPlugin.prototype.getAssets = function () {
	var assets = this.assets = {}

	forEach(this.stats.assetsByChunkName, function(value, chunk) {
		// Webpack outputs an array for each chunk when using sourcemaps
		if (value instanceof Array) {
			// if we've got a CSS file add it here
			if (chunk === 'main' && value.length === 2) {
				assets.css = value[1]
			}

			// Is the main bundle seems like it's always the first
			value = value[0]
		}

		assets[chunk] = value
	})

	return assets
}

module.exports = HJSPlugin
<commit_msg>add the css file to the webpack output<commit_after>/* eslint no-var:0 prefer-spread:0 */
/* global module */

var forEach = require('lodash/collection/forEach')

// Main export
function HJSPlugin(options) {
	this.config = options || {}
	this.filename = options.filename || 'index.html'
}

HJSPlugin.prototype.apply = function (compiler) {
	var self = this
	var htmlFunction = this.config.html

	// let user pass `true` to use
	// the simple default
	// Same if `isDev` and `serveCustomHtmlInDev` is falsy
	if (!htmlFunction) {
		return
	}

	self.compiler = compiler

	compiler.plugin('emit', function (compiler, callback) {
		// store stats on self
		self.stats = compiler.getStats().toJson()
		var context = self.getAssets()

		// access to package info
		context.package = self.config.package

		// access to stats
		context.stats = self.stats

		// expose `isDev` flag to html function context
		context.isDev = self.config.isDev

		// handle both sync and async versions
		if (htmlFunction.length === 2) {
			htmlFunction(context, function (err, result) {
				if (err) throw err
				self.addAssets(compiler, result)
				callback()
			})
		}
		else {
			self.addAssets(compiler, htmlFunction(context))
			callback()
		}
	})
}

// Oddly enough we have to pass in the compiler here
// it's changed from when it was stored on `this` previously
HJSPlugin.prototype.addAssets = function (compiler, data) {
	var dataType = typeof data
	var pages
	// if it's a string, we assume it's an html
	// string for the index file
	if (dataType === 'string') {
		pages = {}
		pages[this.filename] = data
	}
	else if (dataType === 'object') {
		pages = data
	}
	else {
		throw new Error('Result from `html` callback must be a string or an object')
	}

	forEach(pages, function(asset, name) {
		compiler.assets[name] = {
			source: function () {
				return asset
			},
			size: function () {
				return asset.length
			},
		}
	})
}

HJSPlugin.prototype.getAssets = function () {
	var assets = this.assets = {}

	forEach(this.stats.assetsByChunkName, function(value, chunk) {
		// Webpack outputs an array for each chunk when using sourcemaps
		if (value instanceof Array) {
			// if we've got a CSS file add it here
			if (chunk === 'main' && value.length >= 2) {
				assets.css = value[1]
			}

			// Is the main bundle seems like it's always the first
			value = value[0]
		}

		assets[chunk] = value
	})

	return assets
}

module.exports = HJSPlugin
<|endoftext|>


<commit_before>/*
 * grunt-ring-ci
 * https://github.com/dostokhan/grunt-ring-ci
 *
 * Copyright (c) 2016 Moniruzzaman Monir
 * Licensed under the MIT license.
 */

'use strict';

var Chalk = require('chalk');
var Cssmin = require('cssmin');
var Uglifyjs = require('uglify-js');

module.exports = function(grunt) {

  // Please see the Grunt documentation for more information regarding task
  // creation: http://gruntjs.com/creating-tasks

  grunt.registerMultiTask('ring_ci', 'Conginuous Integration for Angularjs 1 SPA', function() {
    var self = this,
        uglifyOptions = {
                banner: "/*! copywrite @ Ringid.com  %s */\n",
                footer: '',
                compress: {
                    warnings: false
                },
                mangle: {},
                beautify: false,
                report: 'min',
                expression: false,
                maxLineLen: 32000,
                ASCIIOnly: false,
                screwIE8: false,
                quoteStyle: 0
        },
        VENDOR_SCRIPTS = [],
        SCRIPT_FILES = [],
        STYLE_SHEETS = [],
        srcFiles = [];
    // Merge task-specific and/or target-specific options with these defaults.
    var options = this.options({
      punctuation: '.',
      separator: ', ',
        target:'dev',
        protocol:'nonssl',
        apiversion:'141',
        branch:'master'
    });

    // HELPER METHODS
    var ringHelper = require('./lib/helpers').init(grunt, options);
    // END HELPER METHODS

    // #COPY all app source files except 'bower_modules' to build path
    function copySrcToBuild() {
        grunt.log.writeln(Chalk.bold.green('$$$$$$$$$$$$$$$$$$$$ COPY SOURCE FILES from: ' + options.appSrcPath + ' TO :'+ options.appBuildPath + '. $$$$$$$$$$$$$$$$$$$$'));
        var srcPath = ringHelper.unixifyPath(options.appSrcPath),
            buildPath = ringHelper.unixifyPath(options.appBuildPath);
        // destinations exists? delete and recreate
        if (grunt.file.exists(buildPath)) {
            grunt.log.write(Chalk.black('BuildPath:' + buildPath + ' exists. Recreating'));
            grunt.file.delete(buildPath);
        }
        grunt.file.mkdir(buildPath);

        var i,k;
        for(k = 0; k < options.appModules.length; k++) {
            for(i = 0; i < options.appModules[k].files.length; i++) {
                srcPath = ringHelper.unixifyPath(options.appSrcPath + options.appModules[k].files[i]);
                buildPath = ringHelper.unixifyPath(options.appBuildPath + options.appModules[k].files[i]);
                //grunt.log.writeln('src:' + srcPath + ' dest:' + buildPath);
                if (grunt.file.exists(srcPath)) {
                    grunt.file.copy(srcPath, buildPath);
                    srcFiles.push(buildPath);
                    grunt.log.writeln(Chalk.cyan(srcPath) + ' > ' + Chalk.red(buildPath)) ;
                } else {
                    grunt.fail.warn(Chalk.bold.red('File: ' + srcPath + ' does not exist'));
                }
            }

        }
        grunt.log.writeln(Chalk.bold.green('^^^^ END COPYING SOURCE FILES TO BUILD DIRECTORY. ^^^^ '));
    }

    // #TASK update apiversion, protocol, settings(analytics,debugEnabled,secure) etc using regex
    function updateSettings() {
        grunt.log.writeln(Chalk.bold.green('$$$$$$$$$$$$$$$$$$$$ UPDATE APIVERSION, PROTOCOL, SETTINGS(ANALYTICS,DEBUGENABLED,SECURE) ETC $$$$$$$$$$$$$$$$$$$$'));
        var searches =  [/(['|"]apiVersion['|"]\s*:\s*[0-9]+)/g],
            replaces = ['"apiVersion":' + options.apiVersion],
            protocolSearches,
            protocolReplaces;
        // set replacement parameters
        protocolSearches =  (options.protocol === 'ssl') ? [/http:\/\//g, /ws:\/\//g] : [/https:\/\//g, /wss:\/\//g] ;
        protocolReplaces = (options.protocol === 'ssl') ? ['https://', 'wss://'] : ['http://', 'ws://'];

        searches = searches.concat(protocolSearches);
        replaces = replaces.concat(protocolReplaces);

        searches = searches.concat([/secure\s*:\s*\w+,/]);
        replaces = replaces.concat( options.protocol === 'ssl' ? ['secure:true,'] :  ['secure:false,'] );

        searches = searches.concat([/analytics\s*:\s*\w+,/, /debugEnabled\s*:\s*\w+,/]);
        replaces = replaces.concat( options.target === 'live' ?  ['analytics:true,', 'debugEnabled:false,'] : ['analytics:false,', 'debugEnabled:true,'] );

        // Modify settingsFile
        ringHelper.replace(options.settingsFile, searches, replaces);
        // Modify Template files
        ringHelper.replace(options.protocolFixTemplates, protocolSearches[0], protocolReplaces[0], true);
        // MOdify Worker Files
        ringHelper.replace(options.workerFiles, protocolSearches[1], protocolReplaces[1]);

        grunt.log.writeln(Chalk.bold.green('^^^^ END UPDATE APIVERSION, PROTOCOL, SETTINGS(ANALYTICS,DEBUGENABLED,SECURE) ETC ^^^^ '));
    }

    function buildModules() {
        grunt.log.writeln(Chalk.bold.green('$$$$$$$$$$$$$$$$$$$$ BUILD APP MODULES in: ' + options.appBuildPath + 'modules/. $$$$$$$$$$$$$$$$$$$$'));
        var i,k,d, srcPath, moduleFile,
            moduleContent = '',
            moduleContentStart = '',
            moduleContentEnd = '';

        // build APP MODULES
        for(k = 0; k < options.appModules.length; k++) {
            moduleContent = '';
            moduleContentStart = "(function() { 'use strict'; ";
            moduleContentEnd = "})();";

            grunt.log.writeln('Module ' + Chalk.red(options.appModules[k].name) );
            moduleFile = ringHelper.unixifyPath(options.appBuildPath + 'modules/' + options.appModules[k].name + '.module.js');
            for(i = 0; i < options.appModules[k].files.length; i++) {
                srcPath = ringHelper.unixifyPath(options.appBuildPath + options.appModules[k].files[i]);
                if (grunt.file.exists(srcPath)) {
                    // concat contents
                    moduleContent += String(grunt.file.read(srcPath, {encoding:'utf8'}));
                    grunt.log.writeln(Chalk.cyan(srcPath));
                } else {
                    grunt.fail.warn(Chalk.bold.red('File: ' + srcPath + ' does not exist'));
                }
            }

            if (options.appModules[k].name !== 'globals' ) {
                // insert dependency modules
                if (options.appModules[k].dependencies.length > 0) {
                    moduleContentStart += " angular.module('" + options.appModules[k].name + "', [ ";
                    for(d = 0; d < options.appModules[k].dependencies.length; d++) {
                        moduleContentStart += "'" + options.appModules[k].dependencies[d] + "', ";
                    }
                    moduleContentStart = moduleContentStart.substr(0, moduleContentStart.length -2);
                    moduleContentStart += " ]); ";
                } else {
                    moduleContentStart += " angular.module('" + options.appModules[k].name + "', []); ";
                }
                moduleContent = moduleContentStart + moduleContent + moduleContentEnd;
            }

            grunt.file.write(moduleFile, moduleContent);

            SCRIPT_FILES.push(moduleFile);
            grunt.log.writeln('BUILD MODULE: ' + Chalk.red(moduleFile));
        }

        grunt.log.writeln(Chalk.bold.green('^^^^ END APP MODULES BUILD. ^^^^ '));
    }

    function removeDebugCode() {
        grunt.log.writeln(Chalk.bold.green('$$$$$$$$$$$$$$$$$$$$ REMOVE DEBUG CODE from APP MODULES  $$$$$$$$$$$$$$$$$$$$'));
        var moduleFile, i, moduleContent,
            debugRegex = /DIGEST_DEBUG_START([\s\S]*?)(DIGEST_DEBUG_END)/gm,
            ringloggerRegex = /RingLogger([\s\S]*?;)/g;

        for(i = 0; i < options.appModules.length; i++) {
            moduleFile = ringHelper.unixifyPath(options.appBuildPath + 'modules/' +  options.appModules[i].name + '.module.js');
            ringHelper.replace(moduleFile, [debugRegex, ringloggerRegex], ['',''], true);
        }
        grunt.log.writeln(Chalk.bold.green('^^^^ END REMOVE DEBUG CODE from APP MODULES  ^^^^ '));
    }

    function prepareVendorScripts() {
        grunt.log.writeln(Chalk.bold.green('$$$$$$$$$$$$$$$$$$$$ BUILDING app.vendor.min $$$$$$$$$$$$$$$$$$$$'));
        var srcPath, scriptContent = '', minifiedScript = '', err;
        for(var i = 0; i < options.vendorFiles.length; i++) {
            srcPath = ringHelper.unixifyPath(options.vendorFiles[i]);
            if (grunt.file.exists(srcPath)) {
                // concat contents
                scriptContent = String(grunt.file.read(srcPath, {encoding:'utf8'}));
                if (srcPath.indexOf('min') === -1) {
                    // not minified code. minify it
                    grunt.log.writeln(Chalk.cyan('MINIFYING File: ' + srcPath ));
                    try {
                        minifiedScript += Uglifyjs.minify(srcPath, uglifyOptions).code;
                    } catch(e) {
                        err = new Error('Uglification failed.');
                        if (e.message) {
                            err.message += '\n' + e.message + '. \n';
                            if (e.line) {
                                err.message += 'Line ' + e.line + ' in ' + src + '\n';
                            }

                        }
                        err.origError = e;
                        grunt.log.warn(Chalk.bold.red('Uglifying source ' + src + ' failed.'));
                        grunt.fail.error(err);
                    }
                } else {
                    grunt.log.writeln(Chalk.cyan('File: ' + srcPath ));
                    // already minified  no need to minify
                    minifiedScript += scriptContent;
                }
            } else {
                grunt.fail.warn(Chalk.bold.red('File: ' + srcPath + ' does not exist'));
            }
        }
        var vendorFile = ringHelper.unixifyPath(options.appBuildPath + 'vendor.min.js');
        VENDOR_SCRIPTS = [vendorFile];
        grunt.log.writeln(Chalk.red('Vendor Script: ' + vendorFile));
        grunt.file.write(vendorFile, minifiedScript);

        grunt.log.writeln(Chalk.bold.green('^^^^ END BUILDING app.vendor.min  ^^^^ '));
    }

    function uglifyModules() {
        SCRIPT_FILES = [];
        grunt.log.writeln(Chalk.bold.green('$$$$$$$$$$$$$$$$$$$$ UGLIFY SOURCE MODULES $$$$$$$$$$$$$$$$$$$$'));
        var src,
            fileName,
            lastDotIndex,
            dest = 'js/dist/';

        for(var i = 0; i < options.appModules.length; i++) {
            dest = 'js/dist/';
            src = ringHelper.unixifyPath(options.appBuildPath + 'modules/' +  options.appModules[i].name + '.module.js');
            fileName = src.substr(src.lastIndexOf('/') + 1);
            dest += fileName.substr(0, fileName.lastIndexOf('.')) + '.min' + fileName.substr(fileName.lastIndexOf('.'));
            ringHelper.uglify(src, dest, uglifyOptions);
            SCRIPT_FILES.push(dest);
        }

        grunt.log.writeln(Chalk.bold.green('^^^^ END UGLIFY SOURCE MODULES   ^^^^ '));
    }

    function minifyStyles() {
        grunt.log.writeln(Chalk.bold.green('$$$$$$$$$$$$$$$$$$$$ MINIFY STYLESHEETS USING CSSMIN $$$$$$$$$$$$$$$$$$$$'));
        var cssfile, minifiedStyle = '';
        for(var i = 0; i < options.appStyles.length; i++) {
            cssfile = ringHelper.unixifyPath(options.appStyles[i]);
            if (!grunt.file.exists(cssfile)) {
                grunt.fail.warn(Chalk.bold.red('File: ' + cssfile+ ' does not exist'));
            } else {
                minifiedStyle += String(grunt.file.read(cssfile, {encoding:'utf8'}));
            }
        }

        grunt.file.write('css/styles.min.css', Cssmin(minifiedStyle));
        STYLE_SHEETS = ['css/styles.min.css'];
        grunt.log.writeln(Chalk.bold.green('^^^^ END MINIFY STYLESHEETS USING CSSMIN   ^^^^ '));
    }

    function linkScriptsStyles() {
        grunt.log.writeln(Chalk.bold.green('$$$$$$$$$$$$$$$$$$$$ LINK SOURCE SCRIPTS AND STYLESHEETS $$$$$$$$$$$$$$$$$$$$'));

        var styleStartTag = '<!--STYLES-->',
            styleEndTag = '<!--STYLES END-->',
            styleFileTmpl = "<link rel='stylesheet' type='text/css' href='%s' />",
            scriptStartTag = '<!--SCRIPTS-->',
            scriptEndTag = '<!--SCRIPTS END-->',
            scriptFileTmpl = '<script src="%s"></script>';

        if (options.target === 'live') {
            ringHelper.linkFiles(VENDOR_SCRIPTS.concat(SCRIPT_FILES), scriptFileTmpl, scriptStartTag, scriptEndTag,  options.linkerFiles);
        } else {
            ringHelper.linkFiles(VENDOR_SCRIPTS.concat(options.debugFiles.concat(SCRIPT_FILES)), scriptFileTmpl, scriptStartTag, scriptEndTag,  options.linkerFiles);
        }
        ringHelper.linkFiles(STYLE_SHEETS, styleFileTmpl, styleStartTag, styleEndTag,  options.linkerFiles);

        grunt.log.writeln(Chalk.bold.green('^^^^ END LINK SOURCE SCRIPTS AND STYLESHEETS  ^^^^ '));
    }

    // INITIALIZE
    VENDOR_SCRIPTS = options.vendorFiles;
    STYLE_SHEETS = options.appStyles;

    // RUN ALL TASKS
    // 1. copy src to build folder
    grunt.log.writeln();
    copySrcToBuild();
    // 2. update settings files
    grunt.log.writeln();
    updateSettings();
    // 3. build modules
    grunt.log.writeln();
    buildModules();
    // 4. remove debug codes if necessary
    grunt.log.writeln();
    if (options.target === 'live') {
         removeDebugCode();
    }
    // 5. uglify modules if necessary
    grunt.log.writeln();
    if (options.minifyScripts) {
        prepareVendorScripts();
        uglifyModules();
    }
    // 6. minify css if necessary
    grunt.log.writeln();
    if (options.minifyStyles) {
        minifyStyles();
    } else {
        STYLE_SHEETS = options.appStyles;
    }
    // 7. link javascript files
    grunt.log.writeln();
    linkScriptsStyles();

  });

};
<commit_msg>long log from copy src to build removed<commit_after>/*
 * grunt-ring-ci
 * https://github.com/dostokhan/grunt-ring-ci
 *
 * Copyright (c) 2016 Moniruzzaman Monir
 * Licensed under the MIT license.
 */

'use strict';

var Chalk = require('chalk');
var Cssmin = require('cssmin');
var Uglifyjs = require('uglify-js');

module.exports = function(grunt) {

  // Please see the Grunt documentation for more information regarding task
  // creation: http://gruntjs.com/creating-tasks

  grunt.registerMultiTask('ring_ci', 'Conginuous Integration for Angularjs 1 SPA', function() {
    var self = this,
        uglifyOptions = {
                banner: "/*! copywrite @ Ringid.com  %s */\n",
                footer: '',
                compress: {
                    warnings: false
                },
                mangle: {},
                beautify: false,
                report: 'min',
                expression: false,
                maxLineLen: 32000,
                ASCIIOnly: false,
                screwIE8: false,
                quoteStyle: 0
        },
        VENDOR_SCRIPTS = [],
        SCRIPT_FILES = [],
        STYLE_SHEETS = [],
        srcFiles = [];
    // Merge task-specific and/or target-specific options with these defaults.
    var options = this.options({
      punctuation: '.',
      separator: ', ',
        target:'dev',
        protocol:'nonssl',
        apiversion:'141',
        branch:'master'
    });

    // HELPER METHODS
    var ringHelper = require('./lib/helpers').init(grunt, options);
    // END HELPER METHODS

    // #COPY all app source files except 'bower_modules' to build path
    function copySrcToBuild() {
        grunt.log.writeln(Chalk.bold.green('$$$$$$$$$$$$$$$$$$$$ COPY SOURCE FILES from: ' + options.appSrcPath + ' TO :'+ options.appBuildPath + '. $$$$$$$$$$$$$$$$$$$$'));
        var srcPath = ringHelper.unixifyPath(options.appSrcPath),
            buildPath = ringHelper.unixifyPath(options.appBuildPath);
        // destinations exists? delete and recreate
        if (grunt.file.exists(buildPath)) {
            grunt.log.write(Chalk.black('BuildPath:' + buildPath + ' exists. Recreating'));
            grunt.file.delete(buildPath);
        }
        grunt.file.mkdir(buildPath);

        var i,k;
        for(k = 0; k < options.appModules.length; k++) {
            for(i = 0; i < options.appModules[k].files.length; i++) {
                srcPath = ringHelper.unixifyPath(options.appSrcPath + options.appModules[k].files[i]);
                buildPath = ringHelper.unixifyPath(options.appBuildPath + options.appModules[k].files[i]);
                //grunt.log.writeln('src:' + srcPath + ' dest:' + buildPath);
                if (grunt.file.exists(srcPath)) {
                    grunt.file.copy(srcPath, buildPath);
                    srcFiles.push(buildPath);
                    //grunt.log.writeln(Chalk.cyan(srcPath) + ' > ' + Chalk.red(buildPath)) ;
                } else {
                    grunt.fail.warn(Chalk.bold.red('File: ' + srcPath + ' does not exist'));
                }
            }

        }
        grunt.log.writeln(Chalk.bold.green('^^^^ END COPYING SOURCE FILES TO BUILD DIRECTORY. ^^^^ '));
    }

    // #TASK update apiversion, protocol, settings(analytics,debugEnabled,secure) etc using regex
    function updateSettings() {
        grunt.log.writeln(Chalk.bold.green('$$$$$$$$$$$$$$$$$$$$ UPDATE APIVERSION, PROTOCOL, SETTINGS(ANALYTICS,DEBUGENABLED,SECURE) ETC $$$$$$$$$$$$$$$$$$$$'));
        var searches =  [/(['|"]apiVersion['|"]\s*:\s*[0-9]+)/g],
            replaces = ['"apiVersion":' + options.apiVersion],
            protocolSearches,
            protocolReplaces;
        // set replacement parameters
        protocolSearches =  (options.protocol === 'ssl') ? [/http:\/\//g, /ws:\/\//g] : [/https:\/\//g, /wss:\/\//g] ;
        protocolReplaces = (options.protocol === 'ssl') ? ['https://', 'wss://'] : ['http://', 'ws://'];

        searches = searches.concat(protocolSearches);
        replaces = replaces.concat(protocolReplaces);

        searches = searches.concat([/secure\s*:\s*\w+,/]);
        replaces = replaces.concat( options.protocol === 'ssl' ? ['secure:true,'] :  ['secure:false,'] );

        searches = searches.concat([/analytics\s*:\s*\w+,/, /debugEnabled\s*:\s*\w+,/]);
        replaces = replaces.concat( options.target === 'live' ?  ['analytics:true,', 'debugEnabled:false,'] : ['analytics:false,', 'debugEnabled:true,'] );

        // Modify settingsFile
        ringHelper.replace(options.settingsFile, searches, replaces);
        // Modify Template files
        ringHelper.replace(options.protocolFixTemplates, protocolSearches[0], protocolReplaces[0], true);
        // MOdify Worker Files
        ringHelper.replace(options.workerFiles, protocolSearches[1], protocolReplaces[1]);

        grunt.log.writeln(Chalk.bold.green('^^^^ END UPDATE APIVERSION, PROTOCOL, SETTINGS(ANALYTICS,DEBUGENABLED,SECURE) ETC ^^^^ '));
    }

    function buildModules() {
        grunt.log.writeln(Chalk.bold.green('$$$$$$$$$$$$$$$$$$$$ BUILD APP MODULES in: ' + options.appBuildPath + 'modules/. $$$$$$$$$$$$$$$$$$$$'));
        var i,k,d, srcPath, moduleFile,
            moduleContent = '',
            moduleContentStart = '',
            moduleContentEnd = '';

        // build APP MODULES
        for(k = 0; k < options.appModules.length; k++) {
            moduleContent = '';
            moduleContentStart = "(function() { 'use strict'; ";
            moduleContentEnd = "})();";

            grunt.log.writeln('Module ' + Chalk.red(options.appModules[k].name) );
            moduleFile = ringHelper.unixifyPath(options.appBuildPath + 'modules/' + options.appModules[k].name + '.module.js');
            for(i = 0; i < options.appModules[k].files.length; i++) {
                srcPath = ringHelper.unixifyPath(options.appBuildPath + options.appModules[k].files[i]);
                if (grunt.file.exists(srcPath)) {
                    // concat contents
                    moduleContent += String(grunt.file.read(srcPath, {encoding:'utf8'}));
                    grunt.log.writeln(Chalk.cyan(srcPath));
                } else {
                    grunt.fail.warn(Chalk.bold.red('File: ' + srcPath + ' does not exist'));
                }
            }

            if (options.appModules[k].name !== 'globals' ) {
                // insert dependency modules
                if (options.appModules[k].dependencies.length > 0) {
                    moduleContentStart += " angular.module('" + options.appModules[k].name + "', [ ";
                    for(d = 0; d < options.appModules[k].dependencies.length; d++) {
                        moduleContentStart += "'" + options.appModules[k].dependencies[d] + "', ";
                    }
                    moduleContentStart = moduleContentStart.substr(0, moduleContentStart.length -2);
                    moduleContentStart += " ]); ";
                } else {
                    moduleContentStart += " angular.module('" + options.appModules[k].name + "', []); ";
                }
                moduleContent = moduleContentStart + moduleContent + moduleContentEnd;
            }

            grunt.file.write(moduleFile, moduleContent);

            SCRIPT_FILES.push(moduleFile);
            grunt.log.writeln('BUILD MODULE: ' + Chalk.red(moduleFile));
        }

        grunt.log.writeln(Chalk.bold.green('^^^^ END APP MODULES BUILD. ^^^^ '));
    }

    function removeDebugCode() {
        grunt.log.writeln(Chalk.bold.green('$$$$$$$$$$$$$$$$$$$$ REMOVE DEBUG CODE from APP MODULES  $$$$$$$$$$$$$$$$$$$$'));
        var moduleFile, i, moduleContent,
            debugRegex = /DIGEST_DEBUG_START([\s\S]*?)(DIGEST_DEBUG_END)/gm,
            ringloggerRegex = /RingLogger([\s\S]*?;)/g;

        for(i = 0; i < options.appModules.length; i++) {
            moduleFile = ringHelper.unixifyPath(options.appBuildPath + 'modules/' +  options.appModules[i].name + '.module.js');
            ringHelper.replace(moduleFile, [debugRegex, ringloggerRegex], ['',''], true);
        }
        grunt.log.writeln(Chalk.bold.green('^^^^ END REMOVE DEBUG CODE from APP MODULES  ^^^^ '));
    }

    function prepareVendorScripts() {
        grunt.log.writeln(Chalk.bold.green('$$$$$$$$$$$$$$$$$$$$ BUILDING app.vendor.min $$$$$$$$$$$$$$$$$$$$'));
        var srcPath, scriptContent = '', minifiedScript = '', err;
        for(var i = 0; i < options.vendorFiles.length; i++) {
            srcPath = ringHelper.unixifyPath(options.vendorFiles[i]);
            if (grunt.file.exists(srcPath)) {
                // concat contents
                scriptContent = String(grunt.file.read(srcPath, {encoding:'utf8'}));
                if (srcPath.indexOf('min') === -1) {
                    // not minified code. minify it
                    grunt.log.writeln(Chalk.cyan('MINIFYING File: ' + srcPath ));
                    try {
                        minifiedScript += Uglifyjs.minify(srcPath, uglifyOptions).code;
                    } catch(e) {
                        err = new Error('Uglification failed.');
                        if (e.message) {
                            err.message += '\n' + e.message + '. \n';
                            if (e.line) {
                                err.message += 'Line ' + e.line + ' in ' + src + '\n';
                            }

                        }
                        err.origError = e;
                        grunt.log.warn(Chalk.bold.red('Uglifying source ' + src + ' failed.'));
                        grunt.fail.error(err);
                    }
                } else {
                    grunt.log.writeln(Chalk.cyan('File: ' + srcPath ));
                    // already minified  no need to minify
                    minifiedScript += scriptContent;
                }
            } else {
                grunt.fail.warn(Chalk.bold.red('File: ' + srcPath + ' does not exist'));
            }
        }
        var vendorFile = ringHelper.unixifyPath(options.appBuildPath + 'vendor.min.js');
        VENDOR_SCRIPTS = [vendorFile];
        grunt.log.writeln(Chalk.red('Vendor Script: ' + vendorFile));
        grunt.file.write(vendorFile, minifiedScript);

        grunt.log.writeln(Chalk.bold.green('^^^^ END BUILDING app.vendor.min  ^^^^ '));
    }

    function uglifyModules() {
        SCRIPT_FILES = [];
        grunt.log.writeln(Chalk.bold.green('$$$$$$$$$$$$$$$$$$$$ UGLIFY SOURCE MODULES $$$$$$$$$$$$$$$$$$$$'));
        var src,
            fileName,
            lastDotIndex,
            dest = 'js/dist/';

        for(var i = 0; i < options.appModules.length; i++) {
            dest = 'js/dist/';
            src = ringHelper.unixifyPath(options.appBuildPath + 'modules/' +  options.appModules[i].name + '.module.js');
            fileName = src.substr(src.lastIndexOf('/') + 1);
            dest += fileName.substr(0, fileName.lastIndexOf('.')) + '.min' + fileName.substr(fileName.lastIndexOf('.'));
            ringHelper.uglify(src, dest, uglifyOptions);
            SCRIPT_FILES.push(dest);
        }

        grunt.log.writeln(Chalk.bold.green('^^^^ END UGLIFY SOURCE MODULES   ^^^^ '));
    }

    function minifyStyles() {
        grunt.log.writeln(Chalk.bold.green('$$$$$$$$$$$$$$$$$$$$ MINIFY STYLESHEETS USING CSSMIN $$$$$$$$$$$$$$$$$$$$'));
        var cssfile, minifiedStyle = '';
        for(var i = 0; i < options.appStyles.length; i++) {
            cssfile = ringHelper.unixifyPath(options.appStyles[i]);
            if (!grunt.file.exists(cssfile)) {
                grunt.fail.warn(Chalk.bold.red('File: ' + cssfile+ ' does not exist'));
            } else {
                minifiedStyle += String(grunt.file.read(cssfile, {encoding:'utf8'}));
            }
        }

        grunt.file.write('css/styles.min.css', Cssmin(minifiedStyle));
        STYLE_SHEETS = ['css/styles.min.css'];
        grunt.log.writeln(Chalk.bold.green('^^^^ END MINIFY STYLESHEETS USING CSSMIN   ^^^^ '));
    }

    function linkScriptsStyles() {
        grunt.log.writeln(Chalk.bold.green('$$$$$$$$$$$$$$$$$$$$ LINK SOURCE SCRIPTS AND STYLESHEETS $$$$$$$$$$$$$$$$$$$$'));

        var styleStartTag = '<!--STYLES-->',
            styleEndTag = '<!--STYLES END-->',
            styleFileTmpl = "<link rel='stylesheet' type='text/css' href='%s' />",
            scriptStartTag = '<!--SCRIPTS-->',
            scriptEndTag = '<!--SCRIPTS END-->',
            scriptFileTmpl = '<script src="%s"></script>';

        if (options.target === 'live') {
            ringHelper.linkFiles(VENDOR_SCRIPTS.concat(SCRIPT_FILES), scriptFileTmpl, scriptStartTag, scriptEndTag,  options.linkerFiles);
        } else {
            ringHelper.linkFiles(VENDOR_SCRIPTS.concat(options.debugFiles.concat(SCRIPT_FILES)), scriptFileTmpl, scriptStartTag, scriptEndTag,  options.linkerFiles);
        }
        ringHelper.linkFiles(STYLE_SHEETS, styleFileTmpl, styleStartTag, styleEndTag,  options.linkerFiles);

        grunt.log.writeln(Chalk.bold.green('^^^^ END LINK SOURCE SCRIPTS AND STYLESHEETS  ^^^^ '));
    }

    // INITIALIZE
    VENDOR_SCRIPTS = options.vendorFiles;
    STYLE_SHEETS = options.appStyles;

    // RUN ALL TASKS
    // 1. copy src to build folder
    grunt.log.writeln();
    copySrcToBuild();
    // 2. update settings files
    grunt.log.writeln();
    updateSettings();
    // 3. build modules
    grunt.log.writeln();
    buildModules();
    // 4. remove debug codes if necessary
    grunt.log.writeln();
    if (options.target === 'live') {
         removeDebugCode();
    }
    // 5. uglify modules if necessary
    grunt.log.writeln();
    if (options.minifyScripts) {
        prepareVendorScripts();
        uglifyModules();
    }
    // 6. minify css if necessary
    grunt.log.writeln();
    if (options.minifyStyles) {
        minifyStyles();
    } else {
        STYLE_SHEETS = options.appStyles;
    }
    // 7. link javascript files
    grunt.log.writeln();
    linkScriptsStyles();

  });

};
<|endoftext|>


<commit_before>var fs = require('fs')
var zlib = require('zlib')
var rollup = require('rollup')
var uglify = require('uglify-js')
var babel = require('rollup-plugin-babel')
var replace = require('rollup-plugin-replace')
var pack = require('../package.json')
var banner = require('./banner')

// update main file
var main = fs
  .readFileSync('src/index.js', 'utf-8')
  .replace(/plugin\.version = '[\d\.]+'/, "plugin.version = '" + pack.version + "'")
fs.writeFileSync('src/index.js', main)

// CommonJS build.
// this is used as the "main" field in package.json
// and used by bundlers like Webpack and Browserify.
rollup.rollup({
  entry: 'src/index.js',
  plugins: [
    babel({
      presets: ['es2015-rollup']
    })
  ]
})
.then(function (bundle) {
  return write('dist/' + pack.name + '.common.js', bundle.generate({
    format: 'cjs',
    banner: banner
  }).code)
})
// Standalone Dev Build
.then(function () {
  return rollup.rollup({
    entry: 'src/index.js',
    plugins: [
      replace({
        'process.env.NODE_ENV': "'development'"
      }),
      babel({
        presets: ['es2015-rollup']
      })
    ]
  })
  .then(function (bundle) {
    return write('dist/' + pack.name + '.js', bundle.generate({
      format: 'umd',
      banner: banner,
      moduleName: classify(pack.name)
    }).code)
  })
})
.then(function () {
  // Standalone Production Build
  return rollup.rollup({
    entry: 'src/index.js',
    plugins: [
      replace({
        'process.env.NODE_ENV': "'production'"
      }),
      babel({
        presets: ['es2015-rollup']
      })
    ]
  })
  .then(function (bundle) {
    var code = bundle.generate({
      format: 'umd',
      moduleName: classify(pack.name)
    }).code
    var minified = banner + '\n' + uglify.minify(code, {
      fromString: true
    }).code
    return write('dist/' + pack.name + '.min.js', minified)
  })
  .then(zip)
})
.catch(logError)

function toUpper (_, c) {
  return c ? c.toUpperCase() : ''
}

const classifyRE = /(?:^|[-_\/])(\w)/g
function classify (str) {
  return str.replace(classifyRE, toUpper)
}

function write (dest, code) {
  return new Promise(function (resolve, reject) {
    fs.writeFile(dest, code, function (err) {
      if (err) return reject(err)
      console.log(blue(dest) + ' ' + getSize(code))
      resolve()
    })
  })
}

function zip () {
  return new Promise(function (resolve, reject) {
    fs.readFile('dist/' + pack.name + '.min.js', function (err, buf) {
      if (err) return reject(err)
      zlib.gzip(buf, function (err, buf) {
        if (err) return reject(err)
        write('dist/' + pack.name + '.min.js.gz', buf).then(resolve)
      })
    })
  })
}

function getSize (code) {
  return (code.length / 1024).toFixed(2) + 'kb'
}

function logError (e) {
  console.log(e)
}

function blue (str) {
  return '\x1b[1m\x1b[34m' + str + '\x1b[39m\x1b[22m'
}
<commit_msg>:zap: improvement(build): automatically dist directory creating<commit_after>var fs = require('fs')
var zlib = require('zlib')
var rollup = require('rollup')
var uglify = require('uglify-js')
var babel = require('rollup-plugin-babel')
var replace = require('rollup-plugin-replace')
var pack = require('../package.json')
var banner = require('./banner')
var exist = fs.existsSync
var mkdir = fs.mkdirSync

if (!exists('dist')) {
  mkdir('dist')
}

// update main file
var main = fs
  .readFileSync('src/index.js', 'utf-8')
  .replace(/plugin\.version = '[\d\.]+'/, "plugin.version = '" + pack.version + "'")
fs.writeFileSync('src/index.js', main)

// CommonJS build.
// this is used as the "main" field in package.json
// and used by bundlers like Webpack and Browserify.
rollup.rollup({
  entry: 'src/index.js',
  plugins: [
    babel({
      presets: ['es2015-rollup']
    })
  ]
})
.then(function (bundle) {
  return write('dist/' + pack.name + '.common.js', bundle.generate({
    format: 'cjs',
    banner: banner
  }).code)
})
// Standalone Dev Build
.then(function () {
  return rollup.rollup({
    entry: 'src/index.js',
    plugins: [
      replace({
        'process.env.NODE_ENV': "'development'"
      }),
      babel({
        presets: ['es2015-rollup']
      })
    ]
  })
  .then(function (bundle) {
    return write('dist/' + pack.name + '.js', bundle.generate({
      format: 'umd',
      banner: banner,
      moduleName: classify(pack.name)
    }).code)
  })
})
.then(function () {
  // Standalone Production Build
  return rollup.rollup({
    entry: 'src/index.js',
    plugins: [
      replace({
        'process.env.NODE_ENV': "'production'"
      }),
      babel({
        presets: ['es2015-rollup']
      })
    ]
  })
  .then(function (bundle) {
    var code = bundle.generate({
      format: 'umd',
      moduleName: classify(pack.name)
    }).code
    var minified = banner + '\n' + uglify.minify(code, {
      fromString: true
    }).code
    return write('dist/' + pack.name + '.min.js', minified)
  })
  .then(zip)
})
.catch(logError)

function toUpper (_, c) {
  return c ? c.toUpperCase() : ''
}

const classifyRE = /(?:^|[-_\/])(\w)/g
function classify (str) {
  return str.replace(classifyRE, toUpper)
}

function write (dest, code) {
  return new Promise(function (resolve, reject) {
    fs.writeFile(dest, code, function (err) {
      if (err) return reject(err)
      console.log(blue(dest) + ' ' + getSize(code))
      resolve()
    })
  })
}

function zip () {
  return new Promise(function (resolve, reject) {
    fs.readFile('dist/' + pack.name + '.min.js', function (err, buf) {
      if (err) return reject(err)
      zlib.gzip(buf, function (err, buf) {
        if (err) return reject(err)
        write('dist/' + pack.name + '.min.js.gz', buf).then(resolve)
      })
    })
  })
}

function getSize (code) {
  return (code.length / 1024).toFixed(2) + 'kb'
}

function logError (e) {
  console.log(e)
}

function blue (str) {
  return '\x1b[1m\x1b[34m' + str + '\x1b[39m\x1b[22m'
}
<|endoftext|>


<commit_before>/*
 * grunt-schultz
 * https://github.com/reputation.com/grunt-schultz
 *
 * Copyright (c) 2012 Reputation.com
 * Authored by: Jeff Harnois jeff.harnois@reputation.com
 * Licensed under the MIT license.
 * "I know nuzzing!"
 * Docs:
 *   parser-lib git://github.com/nzakas/parser-lib.git
 *   jQuery https://github.com/coolaj86/node-jquery
 */

module.exports = function(grunt) {

  // Please see the grunt documentation for more information regarding task and
  // helper creation: https://github.com/cowboy/grunt/blob/master/docs/toc.md

  // ==========================================================================
  // GLOBAL VARS
  // ==========================================================================
  var file = grunt.file,
      log = grunt.log,
      config = grunt.config;

  // ==========================================================================
  // TASKS
  // ==========================================================================

  grunt.registerMultiTask('schultz', 'Take css files, convert them to JSON, and replace the markup in a file with inline styles.', function() {
    // make sure we get some data
    if (!this.data) { return false; }

    // make sure the destination we get is a file, not a path
    if (this.file.dest[this.file.dest.length - 1] === '/') {
       grunt.fatal('never use path as filename');
       return false;
     }

    // send unprocessed file.src object to schultz, it will extract css and tpl as it needs
    var files = this.file.src;
    grunt.file.write(this.file.dest, grunt.helper('schultz', files));

    // Fail task if errors were logged.
    if (this.errorCount) { return false; }
    console.log('no errors');
    //
    // // Otherwise, print a success message.
    grunt.log.writeln('File "' + this.file.dest + '" created.');
    return true;
  });

  // ==========================================================================
  // HELPERS
  // ==========================================================================

  grunt.registerHelper('joss', function(file) {
    var parserlib = require('parserlib'),
        contents = '',
        currentRule = {},
        css = {};
    var parser = new parserlib.css.Parser();

    parser.addListener("startrule", function(event){
      // save the current rule we are on for use in the property listen
      for (var i=0,len=event.selectors.length; i < len; i++){
         var selector = event.selectors[i];
         currentRule = selector.text;
      }
    });

    parser.addListener("property", function(event){
        // check to see if we have a relative url('') anywhere [ !== url('//') ] and add a mustache var to resolve the path
        if (event.value.text.indexOf('url(\'/') !== -1 && event.value.text.indexOf('url(\'//') === -1) {
          var str = event.value.text;
          var s = str.slice(0,5);
          var e = str.slice(6,str.length);
          event.value.text = s+'http://{{cdn}}/'+e;
        }
        // check to see if the rule already has a property
        var currProp = css[currentRule] || '';
        // save the property and value to the rule.
        css[currentRule] = currProp + event.property.text + ': ' + event.value.text + (event.important ? "!important" : "") + ';';
    });

    parser.parse(grunt.file.read(file));

    return css;
  });

  grunt.registerHelper('schultz', function(files) {
    var $ = require('jQuery') || require('jquery'),
        contents = '',
        css = {};
    files.css.map(function(filepath) {
      var raw = grunt.file.read(filepath);
        // send css to Joss to be converted into an object
        css[filepath] = grunt.helper('joss', filepath);
    });
    files.tpl.map(function(filepath) {
      var raw = grunt.file.read(filepath);
      // escape partial mustache calls because jQuery.html() strips them out
      raw = raw.replace(/\{\{>/g,"{{>");
      // save the file content to a jquery instance so that we can simply use jquery selectors
      $(raw).appendTo('body');
      $.each(css, function(key, value) {
        for (var i in value) {
          $.each($(i), function(index) {
            // save the current inline style if it exists
            var attr = $(this).attr('style') || '';
            // append the new style with the old style
            $(this).attr('style',attr+value[i]);
          });
        }
      });
      contents = $('body').html();
      // unescape the mustache partial calls for profit and success
      contents = contents.replace(/\&gt\;/g,">");
      // clear out the html from the body so when we save the file we aren't getting previous contents
      $('body').html('');
    });
    return contents;
  });

};<commit_msg>now support background shorthand<commit_after>/*
 * grunt-schultz
 * https://github.com/reputation.com/grunt-schultz
 *
 * Copyright (c) 2012 Reputation.com
 * Authored by: Jeff Harnois jeff.harnois@reputation.com
 * Licensed under the MIT license.
 * "I know nuzzing!"
 * Docs:
 *   parser-lib git://github.com/nzakas/parser-lib.git
 *   jQuery https://github.com/coolaj86/node-jquery
 */

module.exports = function(grunt) {

  // Please see the grunt documentation for more information regarding task and
  // helper creation: https://github.com/cowboy/grunt/blob/master/docs/toc.md

  // ==========================================================================
  // GLOBAL VARS
  // ==========================================================================
  var file = grunt.file,
      log = grunt.log,
      config = grunt.config;

  // ==========================================================================
  // TASKS
  // ==========================================================================

  grunt.registerMultiTask('schultz', 'Take css files, convert them to JSON, and replace the markup in a file with inline styles.', function() {
    // make sure we get some data
    if (!this.data) { return false; }

    // make sure the destination we get is a file, not a path
    if (this.file.dest[this.file.dest.length - 1] === '/') {
       grunt.fatal('never use path as filename');
       return false;
     }

    // send unprocessed file.src object to schultz, it will extract css and tpl as it needs
    var files = this.file.src;
    grunt.file.write(this.file.dest, grunt.helper('schultz', files));

    // Fail task if errors were logged.
    if (this.errorCount) { return false; }
    console.log('no errors');
    //
    // // Otherwise, print a success message.
    grunt.log.writeln('File "' + this.file.dest + '" created.');
    return true;
  });

  // ==========================================================================
  // HELPERS
  // ==========================================================================

  grunt.registerHelper('joss', function(file) {
    var parserlib = require('parserlib'),
        contents = '',
        currentRule = {},
        css = {};
    var parser = new parserlib.css.Parser();

    parser.addListener("startrule", function(event){
      // save the current rule we are on for use in the property listen
      for (var i=0,len=event.selectors.length; i < len; i++){
         var selector = event.selectors[i];
         currentRule = selector.text;
      }
    });

    parser.addListener("property", function(event){
        // check to see if we have a relative url('') anywhere [ !== url('//') ] and add a mustache var to resolve the path
        if (event.value.text.indexOf("url('/") !== -1 && event.value.text.indexOf("url('//") === -1) {
          var str = event.value.text,
              n;
          n = str.replace(/url\('\//g,"url('http://{{cdn}}/");
          event.value.text = n;
        }
        // check to see if the rule already has a property
        var currProp = css[currentRule] || '';
        // save the property and value to the rule.
        css[currentRule] = currProp + event.property.text + ': ' + event.value.text + (event.important ? "!important" : "") + ';';
    });

    parser.parse(grunt.file.read(file));

    return css;
  });

  grunt.registerHelper('schultz', function(files) {
    var $ = require('jQuery') || require('jquery'),
        contents = '',
        css = {};
    files.css.map(function(filepath) {
      var raw = grunt.file.read(filepath);
        // send css to Joss to be converted into an object
        css[filepath] = grunt.helper('joss', filepath);
    });
    files.tpl.map(function(filepath) {
      var raw = grunt.file.read(filepath);
      // escape partial mustache calls because jQuery.html() strips them out
      raw = raw.replace(/\{\{>/g,"{{>");
      // save the file content to a jquery instance so that we can simply use jquery selectors
      $(raw).appendTo('body');
      $.each(css, function(key, value) {
        for (var i in value) {
          $.each($(i), function(index) {
            // save the current inline style if it exists
            var attr = $(this).attr('style') || '';
            // append the new style with the old style
            $(this).attr('style',attr+value[i]);
          });
        }
      });
      contents = $('body').html();
      // unescape the mustache partial calls for profit and success
      contents = contents.replace(/\&gt\;/g,">");
      // clear out the html from the body so when we save the file we aren't getting previous contents
      $('body').html('');
    });
    return contents;
  });

};<|endoftext|>


<commit_before>import React from "react";

import AbstractGraph from "../AbstractGraph";

import * as d3 from "d3";

import "./style.css";

import {properties} from "./default.config"

export default class GaugeGraph extends AbstractGraph {

    constructor(props) {
        super(props, properties);
    }

    deg2rad(deg) {
        return deg * Math.PI / 180;
    }

    componentDidMount() {
        const {
            configuration
        } = this.props;

        const {
            gaugePtrTransition,
            gaugeCtrFormat,
            gaugeCtrSuffix
        } = this.getConfiguredProperties();

        const format = d3.format(gaugeCtrFormat);
        const currentValue = this.currentValue;
        const minValue = this.minValue;

        d3.timeout(() => {
            d3.select(`#gauge-needle-${configuration.id}`)
                .transition()
                .ease(d3.easeLinear)
    			      .duration(gaugePtrTransition)
    			      .attr('transform', 'rotate(' + this.angle +')');

            d3.select(`#gauge-counter-${configuration.id}`)
                .transition()
                    .duration(gaugePtrTransition)
                    .on("start", function repeat() {
                        d3.active(this)
                            .tween("text", function() {
                                var that = d3.select(this),
                                i = d3.interpolateNumber(minValue, currentValue);
                                return function(t) { that.text(format(i(t)) + (gaugeCtrSuffix ? ' ' + gaugeCtrSuffix : '')); };
                             });
                    });
        }, 500);
    }

    render() {
        const {
            data,
            width,
            height,
            configuration
        } = this.props;

        let cData = data;

        if (!data)
            return;

        if(data.length)
            cData = data[0];

        const {
            minValue,
            maxValue,
            minColumn,
            maxColumn,
            currentColumn,
            margin,
            gaugePtrWidth,
            gaugePtrTailLength,
            gaugePtrHeadLengthPercent,
            gaugeLabelInset,
            gaugePtrColor,
            gaugeTicks,
            gaugeRingInset,
            gaugeRingWidth,
            gaugeCtrColor,
            gaugeCtrFontSize,
            labelFormat,
            fontColor,
            colors
        } = this.getConfiguredProperties();

        console.log('Data', this.getConfiguredProperties(), data);
        const angles = {
            min: -90,
            max: 90
        };

        let availableWidth     = width - (margin.left + margin.right);
        let availableHeight    = height - (margin.top + margin.bottom);

        const minRange         = cData[minColumn] ? cData[minColumn] : (minValue ? minValue : 0);
        const maxRange         = cData[maxColumn] ? cData[maxColumn] : (maxValue ? maxValue : 100);
        const currentValue     = cData[currentColumn] ? cData[currentColumn] : 20;

        const minRadius   = Math.min(availableWidth, availableHeight) / 2;

        const innerRadius = minRadius - gaugeRingInset - gaugeRingWidth;
        const outerRadius = minRadius - gaugeRingInset;

        const pointerHeadLength = Math.round(minRadius * gaugePtrHeadLengthPercent);

        const arcColor = d3.interpolateHsl(d3.rgb(colors[0] ? colors[0] : '#e8e2ca'), d3.rgb(colors[1] ? colors[1] : '#3e6c0a'))

        const range = angles.max - angles.min;

        const arc = d3.arc()
            .innerRadius(innerRadius)
            .outerRadius(outerRadius)
            .startAngle((d, i) => {
    			      return this.deg2rad(angles.min + (d * i * range));
    			  })
            .endAngle((d, i) => {
                return this.deg2rad(angles.min + (d * (i + 1) * range));
    			  });

        let scale = d3.scaleLinear()
            .range([0,1])
            .domain([minRange, maxRange]);

        let ticks = scale.ticks(gaugeTicks);
        let tickData = d3.range(gaugeTicks).map(function() {return 1 / gaugeTicks;});

        const textLabel = ((d) => {
            const formatter = d3.format(labelFormat || ",.2s");
            return formatter(d);
        });

        const transformText = ((d, i) => {
            return `rotate(${angles.min + (scale(d) * range)}) translate(0, ${gaugeLabelInset - minRadius})`;
        });

        const lineData = [ [gaugePtrWidth / 2, 0],
            [0, -pointerHeadLength],
            [-(gaugePtrWidth / 2), 0],
            [0, gaugePtrTailLength],
            [gaugePtrWidth / 2, 0] ];

        const pointerLine = d3.line()
            .curve(d3.curveMonotoneX);

        this.angle        = angles.min + (scale(currentValue) * range);
        this.minValue     = minValue
        this.currentValue = currentValue;

        let needle = <path id={`gauge-needle-${configuration.id}`} d={ pointerLine(lineData) } fill={ gaugePtrColor } transform={ `rotate(${angles.min})` } />;

        let counterStyle = {
            fontSize: gaugeCtrFontSize
        };

        let counterText = <text id={`gauge-counter-${configuration.id}`} fill={ gaugeCtrColor } style={ counterStyle } transform={ `translate(0, ${height * (1 / 5)})` } > { minRange } </text>;

        return (

                <svg width={ width } height={ height }>
                    <g transform={ `translate(${ width / 2 }, ${ height * (3 / 5) })` } >
                        {
                            tickData.map((tick, i) => {
                                return <g key={i} >
                                    <path
                                        d={ arc(tick, i) }
                                        fill={ arcColor(tick * i) }
                                        />
                                </g>
                            })
                        }
                        {
                            ticks.map((tick, i) => {
                                return <g key={i} >
                                    <text transform={ transformText(tick, i) } fill={ fontColor }>
                                        {textLabel(tick)}
                                    </text>
                                </g>
                            })
                        }
                        {
                          needle
                        }

                        {
                          counterText
                        }
                    </g>
                </svg>

        );
    }
}

GaugeGraph.propTypes = {
    configuration: React.PropTypes.object,
    data: React.PropTypes.array
};
<commit_msg>0 value issue<commit_after>import React from "react";

import AbstractGraph from "../AbstractGraph";

import * as d3 from "d3";

import "./style.css";

import {properties} from "./default.config"

export default class GaugeGraph extends AbstractGraph {

    constructor(props) {
        super(props, properties);
    }

    deg2rad(deg) {
        return deg * Math.PI / 180;
    }

    componentDidMount() {
        const {
            configuration
        } = this.props;

        const {
            gaugePtrTransition,
            gaugeCtrFormat,
            gaugeCtrSuffix
        } = this.getConfiguredProperties();

        const format = d3.format(gaugeCtrFormat);
        const currentValue = this.currentValue;
        const minValue = this.minValue;

        d3.timeout(() => {
            d3.select(`#gauge-needle-${configuration.id}`)
                .transition()
                .ease(d3.easeLinear)
    			      .duration(gaugePtrTransition)
    			      .attr('transform', 'rotate(' + this.angle +')');

            d3.select(`#gauge-counter-${configuration.id}`)
                .transition()
                    .duration(gaugePtrTransition)
                    .on("start", function repeat() {
                        d3.active(this)
                            .tween("text", function() {
                                var that = d3.select(this),
                                i = d3.interpolateNumber(minValue, currentValue);
                                return function(t) { that.text(format(i(t)) + (gaugeCtrSuffix ? ' ' + gaugeCtrSuffix : '')); };
                             });
                    });
        }, 500);
    }

    render() {
        const {
            data,
            width,
            height,
            configuration
        } = this.props;

        let cData = data;

        if (!data)
            return;

        if(data.length)
            cData = data[0];

        const {
            minValue,
            maxValue,
            minColumn,
            maxColumn,
            currentColumn,
            margin,
            gaugePtrWidth,
            gaugePtrTailLength,
            gaugePtrHeadLengthPercent,
            gaugeLabelInset,
            gaugePtrColor,
            gaugeTicks,
            gaugeRingInset,
            gaugeRingWidth,
            gaugeCtrColor,
            gaugeCtrFontSize,
            labelFormat,
            fontColor,
            colors
        } = this.getConfiguredProperties();

        console.log('Data', this.getConfiguredProperties(), data);
        const angles = {
            min: -90,
            max: 90
        };

        let availableWidth     = width - (margin.left + margin.right);
        let availableHeight    = height - (margin.top + margin.bottom);

        const minRange         = cData[minColumn] ? cData[minColumn] : (minValue ? minValue : 0);
        const maxRange         = cData[maxColumn] ? cData[maxColumn] : (maxValue ? maxValue : 100);
        const currentValue     = cData[currentColumn] ? cData[currentColumn] : 0;

        const minRadius   = Math.min(availableWidth, availableHeight) / 2;

        const innerRadius = minRadius - gaugeRingInset - gaugeRingWidth;
        const outerRadius = minRadius - gaugeRingInset;

        const pointerHeadLength = Math.round(minRadius * gaugePtrHeadLengthPercent);

        const arcColor = d3.interpolateHsl(d3.rgb(colors[0] ? colors[0] : '#e8e2ca'), d3.rgb(colors[1] ? colors[1] : '#3e6c0a'))

        const range = angles.max - angles.min;

        const arc = d3.arc()
            .innerRadius(innerRadius)
            .outerRadius(outerRadius)
            .startAngle((d, i) => {
    			      return this.deg2rad(angles.min + (d * i * range));
    			  })
            .endAngle((d, i) => {
                return this.deg2rad(angles.min + (d * (i + 1) * range));
    			  });

        let scale = d3.scaleLinear()
            .range([0,1])
            .domain([minRange, maxRange]);

        let ticks = scale.ticks(gaugeTicks);
        let tickData = d3.range(gaugeTicks).map(function() {return 1 / gaugeTicks;});

        const textLabel = ((d) => {
            const formatter = d3.format(labelFormat || ",.2s");
            return formatter(d);
        });

        const transformText = ((d, i) => {
            return `rotate(${angles.min + (scale(d) * range)}) translate(0, ${gaugeLabelInset - minRadius})`;
        });

        const lineData = [ [gaugePtrWidth / 2, 0],
            [0, -pointerHeadLength],
            [-(gaugePtrWidth / 2), 0],
            [0, gaugePtrTailLength],
            [gaugePtrWidth / 2, 0] ];

        const pointerLine = d3.line()
            .curve(d3.curveMonotoneX);

        this.angle        = angles.min + (scale(currentValue) * range);
        this.minValue     = minValue
        this.currentValue = currentValue;

        let needle = <path id={`gauge-needle-${configuration.id}`} d={ pointerLine(lineData) } fill={ gaugePtrColor } transform={ `rotate(${angles.min})` } />;

        let counterStyle = {
            fontSize: gaugeCtrFontSize
        };

        let counterText = <text id={`gauge-counter-${configuration.id}`} fill={ gaugeCtrColor } style={ counterStyle } transform={ `translate(0, ${height * (1 / 5)})` } > { minRange } </text>;

        return (

                <svg width={ width } height={ height }>
                    <g transform={ `translate(${ width / 2 }, ${ height * (3 / 5) })` } >
                        {
                            tickData.map((tick, i) => {
                                return <g key={i} >
                                    <path
                                        d={ arc(tick, i) }
                                        fill={ arcColor(tick * i) }
                                        />
                                </g>
                            })
                        }
                        {
                            ticks.map((tick, i) => {
                                return <g key={i} >
                                    <text transform={ transformText(tick, i) } fill={ fontColor }>
                                        {textLabel(tick)}
                                    </text>
                                </g>
                            })
                        }
                        {
                          needle
                        }

                        {
                          counterText
                        }
                    </g>
                </svg>

        );
    }
}

GaugeGraph.propTypes = {
    configuration: React.PropTypes.object,
    data: React.PropTypes.array
};
<|endoftext|>


<commit_before>// syntax
'use strict';

// module
module.exports = (grunt) => {
  // dependencies
  const gm = require('gm');
  const path = require('path');
  const fs = require('fs');
  const async = require('async');
  // map grunt
  const log = grunt.log;
  const util = grunt.util;
  // defaults
  let splashs = {
    ios: require('ios-splash')(),
    android: require('android-splash')()
  };

  // run the queued image processing tasks
  function run(tasks, done) {
    //done(false);
    async.parallel(tasks, (error) => {
      if (error) {
        throw new util.error(`Error-> Processing splashs`);
      }
      // nothing else to do
      done(true);
    });
  }

  // splash task
  function splash(src, dst, size) {
    return (callback) => {
      gm(src)
        .resize(size.width, size.height, '^')
        .gravity('Center')
        .extent(size.width, size.height)
        .crop(size.width, size.height)
        .write(dst, error => {
          util.error(error);
          if (error) {
            log.fail(error);
          } else {
            callback(null, `${dst}`);
          }
        });
    };
  }

  // oh dir!
  function mkdir(dir) {
    grunt.file.mkdir(dir);
  }

  // check for the image
  function isImage(file) {
    try {
      if (fs.statSync(file).isFile()) {
        return true;
      }
    } catch (error) {
      if (error.code === 'ENOENT') {
        log.fail(`${file} does not exists or is not an image.`);
      }
      return false;
    }
  }

  // register as multi task to have multiple targets running
  grunt.registerMultiTask('splashs', 'Creates splash screens for a Cordova project', function() {
    // console.log(this);
    let done = this.async(),
      tasks = [],
      src = this.files[0].src[0],
      dest = this.files[0].dest;
    // being explicit
    tasks.length = 0;

    // merging task-specific and/or target-specific options witht the defaults
    let options = this.options({
      config: 'config.xml',
      platforms: ['ios', 'android'],
      expand: true
    });

    // so, in case just a string was passed in
    if (util.kindOf(options.platforms) !== 'array') {
      options.platforms = [options.platforms];
    }

    // filter for available platforms in task
    options.platforms = options.platforms.filter(platform => {
      return splashs.hasOwnProperty(platform) || false;
    });

    // check the image
    if (!isImage(src)) {
      throw new util.error(`${src} is either not a file or not an image`);
    }

    // proccess the platforms
    options.platforms.forEach(platform => {
      // setting the dir that the splash are written to
      let dir = options.expand ? path.join(dest, 'splashs', platform) : dest;
      // create the directory
      mkdir(dir);
      // queue the creation tasks to be executed async in parallel
      splashs[platform].forEach(s => {
        // set filename
        let file = path.join(dir, s.name);
        // push to the tasks queue
        tasks.push(splash(src, file, {width: s.width, height: s.height}));
      });
    });

    // check the task queue
    if (tasks.length > 0) {
      // run the task queue; pass along the promise
      run(tasks, done);
    } else {
      // end if there is nothing in the queue
      done();
    }
  });
};
<commit_msg>[Fix] Minor fix to the logging<commit_after>// syntax
'use strict';

// module
module.exports = (grunt) => {
  // dependencies
  const gm = require('gm');
  const path = require('path');
  const fs = require('fs');
  const async = require('async');
  // map grunt
  const log = grunt.log;
  const util = grunt.util;
  // defaults
  let splashs = {
    ios: require('ios-splash')(),
    android: require('android-splash')()
  };

  // run the queued image processing tasks
  function run(tasks, done) {
    // inform
    log.ok('Processing ...');
    // run
    async.parallel(tasks, (error) => {
      if (error) {
        throw new util.error(`Error-> Processing splashs`);
      }
      // nothing else to do
      done(true);
    });
  }

  // splash task
  function splash(src, dst, size) {
    return (callback) => {
      gm(src)
        .resize(size.width, size.height, '^')
        .gravity('Center')
        .extent(size.width, size.height)
        .crop(size.width, size.height)
        .write(dst, error => {
          util.error(error);
          if (error) {
            log.fail(error);
          } else {
            callback(null, `${dst}`);
          }
        });
    };
  }

  // oh dir!
  function mkdir(dir) {
    grunt.file.mkdir(dir);
  }

  // check for the image
  function isImage(file) {
    try {
      if (fs.statSync(file).isFile()) {
        return true;
      }
    } catch (error) {
      if (error.code === 'ENOENT') {
        log.fail(`${file} does not exists or is not an image.`);
      }
      return false;
    }
  }

  // register as multi task to have multiple targets running
  grunt.registerMultiTask('splashs', 'Creates splash screens for a Cordova project', function() {
    // console.log(this);
    let done = this.async(),
      tasks = [],
      src = this.files[0].src[0],
      dest = this.files[0].dest;
    // being explicit
    tasks.length = 0;

    // merging task-specific and/or target-specific options witht the defaults
    let options = this.options({
      config: 'config.xml',
      platforms: ['ios', 'android'],
      expand: true
    });

    // so, in case just a string was passed in
    if (util.kindOf(options.platforms) !== 'array') {
      options.platforms = [options.platforms];
    }

    // filter for available platforms in task
    options.platforms = options.platforms.filter(platform => {
      return splashs.hasOwnProperty(platform) || false;
    });

    // check the image
    if (!isImage(src)) {
      throw new util.error(`${src} is either not a file or not an image`);
    }

    // proccess the platforms
    options.platforms.forEach(platform => {
      // setting the dir that the splash are written to
      let dir = options.expand ? path.join(dest, 'splashs', platform) : dest;
      // create the directory
      mkdir(dir);
      // queue the creation tasks to be executed async in parallel
      splashs[platform].forEach(s => {
        // set filename
        let file = path.join(dir, s.name);
        // push to the tasks queue
        tasks.push(splash(src, file, {width: s.width, height: s.height}));
      });
    });

    // check the task queue
    if (tasks.length > 0) {
      // run the task queue; pass along the promise
      run(tasks, done);
    } else {
      // end if there is nothing in the queue
      done();
    }

    // inform
    log.ok('Done.');
  });
};
<|endoftext|>


<commit_before>//mongoose model

module.exports = exports = function (mongoose, config) {
  var CollegeSchema = new mongoose.Schema({
    'CREATOR': String, //User, who created this document
    'APPROVED': Boolean,//if document is approved, it can be edited only by administrators of moderators
    'INSTNM': String, //Institution (entity) name
    'ADDR': String, //Street address or post office box
    'CITY': String, //City location of institution
    'STABBR': String,//State abbreviation
    'ZIP': String, //Postal Zip Code
    'OBEREG': { //geographical region
      'index': Number,
      'name': String,
      'selected': Boolean
    },
    'CHFNM': String,//Name of chief administrator
    'CHFTITLE': String,//Title of chief administrator
    'GENTELE': String,//General information telephone number
    'EIN': String, //Cont,Employer Identification Number - "The number assigned to an institution by the Internal Revenue Service for tax purposes.
    'OPEID': String, //Cont,Office of Postsecondary Education (OPE) ID Number
    'OPEFLAG': String, //OPE Title IV eligibility indicator code
    'WEBADDR': String, //Institution's internet website address
    'ADMINURL': String, //Admissions office web address
    'FAIDURL': String, //Financial aid office web address
    'APPLURL': String, //Online application web address
    'NPRICURL': String, //Net price calculator web address
    'SECTOR': String, //Sector of institution
    'ICLEVEL': String, //Level of institution
    'CONTROL': String, //Control of institution
    'HLOFFER': {
      'index': Number,
      'value': String
    }, //Highest level of offering
    'UGOFFER': String, //Undergraduate offering
    'GROFFER': String, //Graduate offering
    'HDEGOFR1': String, //Highest degree offered
    'DEGGRANT': String, //Degree-granting status
    'HBCU': String, //Historically Black College or University
    'HOSPITAL': String, //Institution has hospital
    'MEDICAL': String, //Institution grants a medical degree
    'TRIBAL': String, //Tribal college
    'LOCALE': String, //Degree of urbanization (Urban-centric locale)
    'OPENPUBL': String, //Institution open to the general public
    'ACT': String, //Status of institution
    'NEWID': String, //Cont,UNITID for merged schools
    'DEATHYR': String, //Year institution was deleted from IPEDS
    'CLOSEDAT': String, //Date institution closed
    'CYACTIVE': String, //Institution is active in current year
    'POSTSEC': String, //Primarily postsecondary indicator
    'PSEFLAG': String, //Postsecondary institution indicator
    'PSET4FLG': String, //Postsecondary and Title IV institution indicator
    'RPTMTH': String, //"Reporting method for student charges, graduation rates, retention rates and student financial aid"
    'IALIAS': String, //Institution name alias
    'INSTCAT': String, //Institutional category
    'CCBASIC': String, //Carnegie Classification 2010: Basic
    'CCIPUG': String, //Carnegie Classification 2010: Undergraduate Instructional Program
    'CCIPGRAD': String, //Carnegie Classification 2010: Graduate Instructional Program
    'CCUGPROF': String, //Carnegie Classification 2010: Undergraduate Profile
    'CCENRPRF': String, //Carnegie Classification 2010: Enrollment Profile
    'CCSIZSET': String, //Carnegie Classification 2010: Size and Setting
    'CARNEGIE': String, //Carnegie Classification 2000
    'LANDGRNT': String, //Land Grant Institution
    'INSTSIZE': String, //Institution size category
    'CBSA': String, //Core Based Statistical Area (CBSA)
    'CBSATYPE': String, //CBSA Type Metropolitan or Micropolitan
    'CSA': String, //Combined Statistical Area (CSA)
    'NECTA': String, //New England City and Town Area (NECTA)
    'F1SYSTYP': String, //"System, Governing Board or Corporate Structure"
    'F1SYSNAM': String, //"Name of system, governing board or corporate entity."
    'FAXTELE': String //Fax number
  });

  CollegeSchema.index({
    INSTNM: 1,
    CITY: 1,
    ZIP: 1,
    WEBADDR: 1
  });

  CollegeSchema.statics.getGeographicalLocations = function () {
    return [
      {
        'index': 0,
        'name': 'US Service schools'
      },
      {
        'index': 1,
        'name': 'New England CT ME MA NH RI VT'
      },
      {
        'index': 2,
        'name': 'Mid East DE DC MD NJ NY PA'
      },
      {
        'index': 3,
        'name': 'Great Lakes IL IN MI OH WI'
      },
      {
        'index': 4,
        'name': 'Plains IA KS MN MO NE ND SD'
      },
      {
        'index': 5,
        'name': 'Southeast AL AR FL GA KY LA MS NC SC TN VA WV'
      },
      {
        'index': 6,
        'name': 'Southwest AZ NM OK TX'
      },
      {
        'index': 7,
        'name': 'Plains IA KS MN MO NE ND SD'
      },
      {
        'index': 8,
        'name': 'Rocky Mountains CO ID MT UT WY'
      },
      {
        'index': 9,
        'name': 'Far West AK CA HI NV OR WA'
      },
      {
        'index': 10,
        'name': 'Outlying areas AS FM GU MH MP PR PW VI'
      },
      {
        'index': -3,
        'name': 'N/A'
      }
    ];
  };

  return mongoose.model('colleges', CollegeSchema);
};

<commit_msg>[feature] - getHighestLevelOfferings<commit_after>//mongoose model

module.exports = exports = function (mongoose, config) {
  var CollegeSchema = new mongoose.Schema({
    'CREATOR': String, //User, who created this document
    'APPROVED': Boolean,//if document is approved, it can be edited only by administrators of moderators
    'INSTNM': String, //Institution (entity) name
    'ADDR': String, //Street address or post office box
    'CITY': String, //City location of institution
    'STABBR': String,//State abbreviation
    'ZIP': String, //Postal Zip Code
    'OBEREG': { //geographical region
      'index': Number,
      'name': String,
      'selected': Boolean
    },
    'CHFNM': String,//Name of chief administrator
    'CHFTITLE': String,//Title of chief administrator
    'GENTELE': String,//General information telephone number
    'EIN': String, //Cont,Employer Identification Number - "The number assigned to an institution by the Internal Revenue Service for tax purposes.
    'OPEID': String, //Cont,Office of Postsecondary Education (OPE) ID Number
    'OPEFLAG': String, //OPE Title IV eligibility indicator code
    'WEBADDR': String, //Institution's internet website address
    'ADMINURL': String, //Admissions office web address
    'FAIDURL': String, //Financial aid office web address
    'APPLURL': String, //Online application web address
    'NPRICURL': String, //Net price calculator web address
    'SECTOR': String, //Sector of institution
    'ICLEVEL': String, //Level of institution
    'CONTROL': String, //Control of institution
    'HLOFFER': {
      'index': String,
      'value': String
    }, //Highest level of offering
    'UGOFFER': String, //Undergraduate offering
    'GROFFER': String, //Graduate offering
    'HDEGOFR1': String, //Highest degree offered
    'DEGGRANT': String, //Degree-granting status
    'HBCU': String, //Historically Black College or University
    'HOSPITAL': String, //Institution has hospital
    'MEDICAL': String, //Institution grants a medical degree
    'TRIBAL': String, //Tribal college
    'LOCALE': String, //Degree of urbanization (Urban-centric locale)
    'OPENPUBL': String, //Institution open to the general public
    'ACT': String, //Status of institution
    'NEWID': String, //Cont,UNITID for merged schools
    'DEATHYR': String, //Year institution was deleted from IPEDS
    'CLOSEDAT': String, //Date institution closed
    'CYACTIVE': String, //Institution is active in current year
    'POSTSEC': String, //Primarily postsecondary indicator
    'PSEFLAG': String, //Postsecondary institution indicator
    'PSET4FLG': String, //Postsecondary and Title IV institution indicator
    'RPTMTH': String, //"Reporting method for student charges, graduation rates, retention rates and student financial aid"
    'IALIAS': String, //Institution name alias
    'INSTCAT': String, //Institutional category
    'CCBASIC': String, //Carnegie Classification 2010: Basic
    'CCIPUG': String, //Carnegie Classification 2010: Undergraduate Instructional Program
    'CCIPGRAD': String, //Carnegie Classification 2010: Graduate Instructional Program
    'CCUGPROF': String, //Carnegie Classification 2010: Undergraduate Profile
    'CCENRPRF': String, //Carnegie Classification 2010: Enrollment Profile
    'CCSIZSET': String, //Carnegie Classification 2010: Size and Setting
    'CARNEGIE': String, //Carnegie Classification 2000
    'LANDGRNT': String, //Land Grant Institution
    'INSTSIZE': String, //Institution size category
    'CBSA': String, //Core Based Statistical Area (CBSA)
    'CBSATYPE': String, //CBSA Type Metropolitan or Micropolitan
    'CSA': String, //Combined Statistical Area (CSA)
    'NECTA': String, //New England City and Town Area (NECTA)
    'F1SYSTYP': String, //"System, Governing Board or Corporate Structure"
    'F1SYSNAM': String, //"Name of system, governing board or corporate entity."
    'FAXTELE': String //Fax number
  });

  CollegeSchema.index({
    INSTNM: 1,
    CITY: 1,
    ZIP: 1,
    WEBADDR: 1
  });

  CollegeSchema.statics.getGeographicalLocations = function () {
    return [
      {
        'index': 0,
        'name': 'US Service schools'
      },
      {
        'index': 1,
        'name': 'New England CT ME MA NH RI VT'
      },
      {
        'index': 2,
        'name': 'Mid East DE DC MD NJ NY PA'
      },
      {
        'index': 3,
        'name': 'Great Lakes IL IN MI OH WI'
      },
      {
        'index': 4,
        'name': 'Plains IA KS MN MO NE ND SD'
      },
      {
        'index': 5,
        'name': 'Southeast AL AR FL GA KY LA MS NC SC TN VA WV'
      },
      {
        'index': 6,
        'name': 'Southwest AZ NM OK TX'
      },
      {
        'index': 7,
        'name': 'Plains IA KS MN MO NE ND SD'
      },
      {
        'index': 8,
        'name': 'Rocky Mountains CO ID MT UT WY'
      },
      {
        'index': 9,
        'name': 'Far West AK CA HI NV OR WA'
      },
      {
        'index': 10,
        'name': 'Outlying areas AS FM GU MH MP PR PW VI'
      },
      {
        'index': -3,
        'name': 'N/A'
      }
    ];
  };
  CollegeSchema.statics.getHighestLevelOfferings = function(){
    return [
      {
        'index':0,
        'value':'Other'
      },
      {
        'index':1,
        'value':'Postsecondary award, certificate or diploma of less than one academic year'
      },
      {
        'index':2,
        'value':'Postsecondary award, certificate or diploma of at least one but less than two academic years'
      },
      {
        'index':3,
        'value':'Associate\'s degree'
      },
      {
        'index':4,
        'value':'Postsecondary award, certificate or diploma of at least two but less than four academic years'
      },
      {
        'index':5,
        'value':'Bachelor\'s degree'
      },
      {
        'index':6,
        'value':'Postbaccalaureate certificate'
      },
      {
        'index':7,
        'value':'Master\'s degree'
      },
      {
        'index':8,
        'value':'Post-master\'s certificate'
      },
      {
        'index':9,
        'value':'Doctor\'s degree'
      },
      {
        'index':'b',
        'value':'None of the above or no answer'
      },
      {
        'index':-2,
        'value':'Not applicable, first-professional only'
      },
      {
        'index':-3,
        'value':'Not Available'
      },

    ];
  };

  return mongoose.model('colleges', CollegeSchema);
};

<|endoftext|>