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

    var Scope = scope.window ? window : global;

    /* global rendy */

    if (typeof module === 'object' && module.exports)
        module.exports = new UtilProto();
    else if (!Scope.Util)
        Scope.Util = new UtilProto();

    function UtilProto() {
        var Util = this;

        this.check              = new checkProto();

        function checkProto() {
            /**
             * Check is all arguments with names present
             *
             * @param name
             * @param arg
             * @param type
             */
            var check = function check(args, names) {
                var msg         = '',
                    name        = '',
                    template    = '{{ name }} coud not be empty!',

                    indexOf     = Array.prototype.indexOf,

                    lenNames    = names.length,
                    lenArgs     = args.length,
                    lessArgs    = lenArgs < lenNames,
                    emptyIndex  = indexOf.call(args),
                    isEmpty     = ~emptyIndex && emptyIndex <= lenNames - 1;

                if (lessArgs || isEmpty) {
                    if (lessArgs)
                        name        = names[lenNames - 1];
                    else
                        name        = names[emptyIndex];

                    msg         = rendy(template, {
                        name: name
                    });

                    throw(Error(msg));
                }

                return check;
            };

            check.check = check;

            /**
             * Check is type of arg with name is equal to type
             *
             * @param name
             * @param arg
             * @param type
             */
            check.type  = function(name, arg, type) {
                var is = Util.type(arg) === type;

                if (!is)
                    throw(Error(name + ' should be ' + type));

                return check;
            };

            return check;
        }

        /**
         * Copy properties from from to to
         *
         * @param from
         * @param to
         */
        this.copyObj                = function(to, from) {
            if (!from) {
                from    = to;
                to      = {};
            }

            if (to)
                Object.keys(from).forEach(function(name) {
                    to[name]    = from[name];
                });

            return to;
        };

        /**
         * copy objFrom properties to target
         *
         * @target
         * @objFrom
         */
        this.extend                 = function(target, objFrom) {
            var obj,
                keys,
                proto,
                isFunc  = Util.type.function(objFrom),
                isArray = Util.type.array(objFrom),
                isObj   = Util.type.object(target),
                ret     = isObj ? target : {};

            if (isArray)
                objFrom.forEach(function(item) {
                   ret = Util.extend(target, item);
                });

            else if (objFrom) {
                obj     = isFunc ? new objFrom() : objFrom;
                keys    = Object.keys(obj);

                if (!keys.length) {
                    proto = Object.getPrototypeOf(objFrom);
                    keys  = Object.keys(proto);
                }

                keys.forEach(function(name) {
                    ret[name] = obj[name];
                });
            }

            return ret;
        };

        /**
         * extend proto
         *
         * @obj
         */
        this.extendProto           = function(obj) {
            var ret, F      = function() {};
            F.prototype     = Util.extend({}, obj);
            ret             = new F();

            return ret;
        };

        this.json               = new JsonProto();

        function JsonProto() {
            /**
             * @param str
             */
            this.parse      = function(str) {
                var obj;

                Util.exec.try(function() {
                    obj = JSON.parse(str);
                });

                return obj;
            },

            /**
             * @param obj
             */
            this.stringify  = function(obj) {
                var str;

                Util.exec.try(function() {
                    str = JSON.stringify(obj, null, 4);
                });

                return str;
            };
        }

        this.escapeRegExp = function(str) {
            var isStr   = Util.type.string(str);

            if (isStr)
                str = str.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');

            return str;
        };

        /**
         * get regexp from wild card
         */
        this.getRegExp              = function(wildcard) {
            var regExp;

            if (!wildcard)
                wildcard = '*';

            wildcard    = '^' + wildcard /* search from start of line */
                .replace('.', '\\.')
                .replace('*', '.*')
                .replace('?', '.?');

            wildcard    += '$'; /* search to end of line */

            regExp      = new RegExp(wildcard);

            return regExp;
        };

        this.type                   = new TypeProto();

        function TypeProto() {
            /**
             * get type of variable
             *
             * @param variable
             */
            function type(variable) {
                var regExp      = /\s([a-zA-Z]+)/,
                    str         = {}.toString.call(variable),
                    typeBig     = str.match(regExp)[1],
                    result      = typeBig.toLowerCase();

                return result;
            }

            /**
             * functions check is variable is type of name
             *
             * @param variable
             */
            function typeOf(name, variable) {
                return type(variable) === name;
            }

            function typeOfSimple(name, variable) {
                return typeof variable === name;
            }

            ['null', 'arrayBuffer', 'file', 'array', 'object']
                .forEach(function(name) {
                    type[name] = typeOf.bind(null, name);
                });

            ['string', 'undefined', 'boolean', 'number', 'function']
                .forEach(function(name) {
                    type[name] = typeOfSimple.bind(null, name);
                });

            return type;
        }

        this.exec                       = new ExecProto();

        function ExecProto() {
            /**
             * function do save exec of function
             * @param callback
             * @param arg1
             * ...
             * @param argN
             */
            var exec        = function(callback) {
                var ret,
                    isFunc  = Util.type.function(callback),
                    args    = [].slice.call(arguments, 1);

                if (isFunc)
                    ret     = callback.apply(null, args);

                return ret;
            };

            /*
             * return function that calls callback with arguments
             */
            exec.with           =  function(callback) {
                var args    = [].slice.call(arguments),
                    bind    = Function.prototype.bind;

                args[0]     = null;

                return  bind.apply(callback, args);
            };

             /**
             * return save exec function
             * @param callback
             */
            exec.ret        = function() {
                var result,
                    args        = [].slice.call(arguments);

                args.unshift(exec);
                result          = exec.with.apply(null, args);

                return result;
            };

            /**
             * function do conditional save exec of function
             * @param condition
             * @param callback
             * @param func
             */
            exec.if         = function(condition, callback, func) {
                var ret;

                if (condition)
                    exec(callback);
                else
                    exec(func, callback);

                return ret;
            };

            /**
             * exec function if it exist in object
             *
             * @param obj
             * @param name
             * @param arg
             */
            exec.ifExist                = function(obj, name, arg) {
                var ret,
                    func    = obj && obj[name];

                if (func)
                    func    = func.apply(obj, arg);

                return ret;
            };

            exec.parallel   = function(funcs, callback) {
                var keys        = [],
                    callbackWas = false,
                    arr         = [],
                    obj         = {},
                    count       = 0,
                    countFuncs  = 0,
                    type        = Util.type(funcs);

                Util.check(arguments, ['funcs', 'callback']);

                switch(type) {
                case 'array':
                    countFuncs  = funcs.length;

                    funcs.forEach(function(func, num) {
                        exec(func, function() {
                            checkFunc(num, arguments, arr);
                        });
                    });
                    break;

                case 'object':
                    keys        = Object.keys(funcs);
                    countFuncs  = keys.length;

                    keys.forEach(function(name) {
                        var func    = funcs[name];

                        exec(func, function() {
                            checkFunc(name, arguments, obj);
                        });
                    });
                    break;
                }

                function checkFunc(num, data, all) {
                    var args    = [].slice.call(data, 1),
                        isLast  = false,
                        error   = data[0],
                        length  = args.length;

                    ++count;

                    isLast = count === countFuncs;

                    if (!error)
                        if (length >= 2)
                            all[num] = args;
                        else
                            all[num] = args[0];

                    if (!callbackWas && (error || isLast)) {
                        callbackWas = true;

                        if (type === 'array')
                            callback.apply(null, [error].concat(all));
                        else
                            callback(error, all);
                    }
                }
            };

            /**
             * load functions thrue callbacks one-by-one
             * @param funcs {Array} - array of functions
             */
            exec.series             = function(funcs) {
                var func, callback,
                    isArray     = Util.type.array(funcs);

                if (isArray) {
                    func        = funcs.shift();

                    callback    = function() {
                        return exec.series(funcs);
                    };

                    exec(func, callback);
                }
            };

           /**
             * function execute param function in
             * try...catch block
             *
             * @param callback
             */
            exec.try                = function(callback) {
                var ret;
                try {
                    ret = callback();
                } catch(error) {
                    ret = error;
                }

                return ret;
            };

            return exec;
        }

        /**
         * function gets file extension
         *
         * @param pFileName
         * @return Ext
         */
        this.getExt                     = function(name) {
            var ret     = '',
                dot,
                isStr   = Util.type.string(name);

            if (isStr) {
                dot = name.lastIndexOf('.');

                if (~dot)
                    ret = name.substr(dot);
            }

            return ret;
        };

       /**
         * get values from Object Array name properties
         * or
         * @pObj
         */
        this.getNamesFromObjArray       = function(arr) {
            var ret     = [];

            if (!Array.isArray(arr))
                throw(Error('arr should be array!'));

            ret = arr.map(function(item) {
                return item.name;
            });

            return ret;
        };

        /**
         * find object by name in arrray
         *
         * @param array
         * @param name
         */
        this.findObjByNameInArr         = function(array, name) {
            var ret;

             if (!Array.isArray(array))
                throw(Error('array should be array!'));

            if (typeof name !== 'string')
                throw(Error('name should be string!'));

            array.some(function(item) {
                var is = item.name === name,
                    isArray = Util.type.array(item);

                if (is)
                    ret = item;
                else if (isArray)
                    item.some(function(item) {
                        is = item.name === name;

                        if (is)
                            ret = item.data;

                        return is;
                    });

                return is;
            });

            return ret;
        };

        /**
         * start timer
         * @param name
         */
        this.time                       = function(name) {
            var console     = Scope.console;

            Util.exec.ifExist(console, 'time', [name]);

            return this;
        };

        /**
         * stop timer
         * @param name
         */
        this.timeEnd                   = function(name) {
            var console    = Scope.console;

            Util.exec.ifExist(console, 'timeEnd', [name]);

            return this;
        };
    }

})(this);
<commit_msg>feature(util) exec: each, eachSeries<commit_after>(function(scope) {
    'use strict';

    var Scope = scope.window ? window : global;

    /* global rendy */

    if (typeof module === 'object' && module.exports)
        module.exports = new UtilProto();
    else if (!Scope.Util)
        Scope.Util = new UtilProto();

    function UtilProto() {
        var Util = this;

        this.check              = new checkProto();

        function checkProto() {
            /**
             * Check is all arguments with names present
             *
             * @param name
             * @param arg
             * @param type
             */
            var check = function check(args, names) {
                var msg         = '',
                    name        = '',
                    template    = '{{ name }} coud not be empty!',

                    indexOf     = Array.prototype.indexOf,

                    lenNames    = names.length,
                    lenArgs     = args.length,
                    lessArgs    = lenArgs < lenNames,
                    emptyIndex  = indexOf.call(args),
                    isEmpty     = ~emptyIndex && emptyIndex <= lenNames - 1;

                if (lessArgs || isEmpty) {
                    if (lessArgs)
                        name        = names[lenNames - 1];
                    else
                        name        = names[emptyIndex];

                    msg         = rendy(template, {
                        name: name
                    });

                    throw(Error(msg));
                }

                return check;
            };

            check.check = check;

            /**
             * Check is type of arg with name is equal to type
             *
             * @param name
             * @param arg
             * @param type
             */
            check.type  = function(name, arg, type) {
                var is = Util.type(arg) === type;

                if (!is)
                    throw(Error(name + ' should be ' + type));

                return check;
            };

            return check;
        }

        /**
         * Copy properties from from to to
         *
         * @param from
         * @param to
         */
        this.copyObj                = function(to, from) {
            if (!from) {
                from    = to;
                to      = {};
            }

            if (to)
                Object.keys(from).forEach(function(name) {
                    to[name]    = from[name];
                });

            return to;
        };

        /**
         * copy objFrom properties to target
         *
         * @target
         * @objFrom
         */
        this.extend                 = function(target, objFrom) {
            var obj,
                keys,
                proto,
                isFunc  = Util.type.function(objFrom),
                isArray = Util.type.array(objFrom),
                isObj   = Util.type.object(target),
                ret     = isObj ? target : {};

            if (isArray)
                objFrom.forEach(function(item) {
                   ret = Util.extend(target, item);
                });

            else if (objFrom) {
                obj     = isFunc ? new objFrom() : objFrom;
                keys    = Object.keys(obj);

                if (!keys.length) {
                    proto = Object.getPrototypeOf(objFrom);
                    keys  = Object.keys(proto);
                }

                keys.forEach(function(name) {
                    ret[name] = obj[name];
                });
            }

            return ret;
        };

        /**
         * extend proto
         *
         * @obj
         */
        this.extendProto           = function(obj) {
            var ret, F      = function() {};
            F.prototype     = Util.extend({}, obj);
            ret             = new F();

            return ret;
        };

        this.json               = new JsonProto();

        function JsonProto() {
            /**
             * @param str
             */
            this.parse      = function(str) {
                var obj;

                Util.exec.try(function() {
                    obj = JSON.parse(str);
                });

                return obj;
            },

            /**
             * @param obj
             */
            this.stringify  = function(obj) {
                var str;

                Util.exec.try(function() {
                    str = JSON.stringify(obj, null, 4);
                });

                return str;
            };
        }

        this.escapeRegExp = function(str) {
            var isStr   = Util.type.string(str);

            if (isStr)
                str = str.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');

            return str;
        };

        /**
         * get regexp from wild card
         */
        this.getRegExp              = function(wildcard) {
            var regExp;

            if (!wildcard)
                wildcard = '*';

            wildcard    = '^' + wildcard /* search from start of line */
                .replace('.', '\\.')
                .replace('*', '.*')
                .replace('?', '.?');

            wildcard    += '$'; /* search to end of line */

            regExp      = new RegExp(wildcard);

            return regExp;
        };

        this.type                   = new TypeProto();

        function TypeProto() {
            /**
             * get type of variable
             *
             * @param variable
             */
            function type(variable) {
                var regExp      = /\s([a-zA-Z]+)/,
                    str         = {}.toString.call(variable),
                    typeBig     = str.match(regExp)[1],
                    result      = typeBig.toLowerCase();

                return result;
            }

            /**
             * functions check is variable is type of name
             *
             * @param variable
             */
            function typeOf(name, variable) {
                return type(variable) === name;
            }

            function typeOfSimple(name, variable) {
                return typeof variable === name;
            }

            ['null', 'arrayBuffer', 'file', 'array', 'object']
                .forEach(function(name) {
                    type[name] = typeOf.bind(null, name);
                });

            ['string', 'undefined', 'boolean', 'number', 'function']
                .forEach(function(name) {
                    type[name] = typeOfSimple.bind(null, name);
                });

            return type;
        }

        this.exec                       = new ExecProto();

        function ExecProto() {
            /**
             * function do save exec of function
             * @param callback
             * @param arg1
             * ...
             * @param argN
             */
            var exec        = function(callback) {
                var ret,
                    isFunc  = Util.type.function(callback),
                    args    = [].slice.call(arguments, 1);

                if (isFunc)
                    ret     = callback.apply(null, args);

                return ret;
            };

            /*
             * return function that calls callback with arguments
             */
            exec.with           =  function(callback) {
                var args    = [].slice.call(arguments),
                    bind    = Function.prototype.bind;

                args[0]     = null;

                return  bind.apply(callback, args);
            };

             /**
             * return save exec function
             * @param callback
             */
            exec.ret        = function() {
                var result,
                    args        = [].slice.call(arguments);

                args.unshift(exec);
                result          = exec.with.apply(null, args);

                return result;
            };

            /**
             * function do conditional save exec of function
             * @param condition
             * @param callback
             * @param func
             */
            exec.if         = function(condition, callback, func) {
                var ret;

                if (condition)
                    exec(callback);
                else
                    exec(func, callback);

                return ret;
            };

            /**
             * exec function if it exist in object
             *
             * @param obj
             * @param name
             * @param arg
             */
            exec.ifExist                = function(obj, name, arg) {
                var ret,
                    func    = obj && obj[name];

                if (func)
                    func    = func.apply(obj, arg);

                return ret;
            };

            exec.parallel   = function(funcs, callback) {
                var keys        = [],
                    callbackWas = false,
                    arr         = [],
                    obj         = {},
                    count       = 0,
                    countFuncs  = 0,
                    type        = Util.type(funcs);

                Util.check(arguments, ['funcs', 'callback']);

                switch(type) {
                case 'array':
                    countFuncs  = funcs.length;

                    funcs.forEach(function(func, num) {
                        exec(func, function() {
                            checkFunc(num, arguments, arr);
                        });
                    });
                    break;

                case 'object':
                    keys        = Object.keys(funcs);
                    countFuncs  = keys.length;

                    keys.forEach(function(name) {
                        var func    = funcs[name];

                        exec(func, function() {
                            checkFunc(name, arguments, obj);
                        });
                    });
                    break;
                }

                function checkFunc(num, data, all) {
                    var args    = [].slice.call(data, 1),
                        isLast  = false,
                        error   = data[0],
                        length  = args.length;

                    ++count;

                    isLast = count === countFuncs;

                    if (!error)
                        if (length >= 2)
                            all[num] = args;
                        else
                            all[num] = args[0];

                    if (!callbackWas && (error || isLast)) {
                        callbackWas = true;

                        if (type === 'array')
                            callback.apply(null, [error].concat(all));
                        else
                            callback(error, all);
                    }
                }
            };

            /**
             * load functions thrue callbacks one-by-one
             * @param funcs {Array} - array of functions
             */
            exec.series             = function(funcs, callback) {
                var fn,
                    i           = funcs.length,
                    check       = function(error) {
                        var done;

                        --i;

                        if (!i || error) {
                            done = true;
                            exec(callback, error);
                        }

                        return done;
                    };

                if (!Array.isArray(funcs))
                    throw(Error('funcs should be array!'));

                fn = funcs.shift();

                exec(fn, function(error) {
                    if (!check(error))
                        exec.series(funcs, callback);
                });
            };

            exec.each               = function(array, iterator, callback) {
                var listeners = array.map(function(item) {
                    return iterator.bind(null, item);
                });

                if (!listeners.length)
                    callback();
                else
                    exec.parallel(listeners, callback);
            };

            exec.eachSeries         = function(array, iterator, callback) {
                var listeners = array.map(function(item) {
                    return iterator.bind(null, item);
                });

                if (typeof callback !== 'function')
                    throw Error('callback should be function');

                if (!listeners.length)
                    callback();
                else
                    exec.series(listeners, callback);
            };

           /**
             * function execute param function in
             * try...catch block
             *
             * @param callback
             */
            exec.try                = function(callback) {
                var ret;
                try {
                    ret = callback();
                } catch(error) {
                    ret = error;
                }

                return ret;
            };

            return exec;
        }

        /**
         * function gets file extension
         *
         * @param pFileName
         * @return Ext
         */
        this.getExt                     = function(name) {
            var ret     = '',
                dot,
                isStr   = Util.type.string(name);

            if (isStr) {
                dot = name.lastIndexOf('.');

                if (~dot)
                    ret = name.substr(dot);
            }

            return ret;
        };

       /**
         * get values from Object Array name properties
         * or
         * @pObj
         */
        this.getNamesFromObjArray       = function(arr) {
            var ret     = [];

            if (!Array.isArray(arr))
                throw(Error('arr should be array!'));

            ret = arr.map(function(item) {
                return item.name;
            });

            return ret;
        };

        /**
         * find object by name in arrray
         *
         * @param array
         * @param name
         */
        this.findObjByNameInArr         = function(array, name) {
            var ret;

             if (!Array.isArray(array))
                throw(Error('array should be array!'));

            if (typeof name !== 'string')
                throw(Error('name should be string!'));

            array.some(function(item) {
                var is = item.name === name,
                    isArray = Util.type.array(item);

                if (is)
                    ret = item;
                else if (isArray)
                    item.some(function(item) {
                        is = item.name === name;

                        if (is)
                            ret = item.data;

                        return is;
                    });

                return is;
            });

            return ret;
        };

        /**
         * start timer
         * @param name
         */
        this.time                       = function(name) {
            var console     = Scope.console;

            Util.exec.ifExist(console, 'time', [name]);

            return this;
        };

        /**
         * stop timer
         * @param name
         */
        this.timeEnd                   = function(name) {
            var console    = Scope.console;

            Util.exec.ifExist(console, 'timeEnd', [name]);

            return this;
        };
    }

})(this);
<|endoftext|>


<commit_before>var DB_URL = process.env.DB_URL,
    COMPANY_NAME = process.env.COMPANY_NAME,
    timeout,
    users = [],
    usersWithNoTitle = [],
    usersWithDefaultProfileImage = [],
    MESSAGES = [],
    WELCOME_MSGS = [
        // "We heard that our company just hired you to be a part of our growing team. Congratulations and on behalf of our members and leadership, we would like to welcome you! We are all happy and excited for the upbringing of our company.",
        // "Our company is truly happy that you have finally decided to join our team. We believe that you can be one of the best assets here. We can’t wait to know your plans for our team.",
        // "Our office welcomes you today as you start working with us. May we have a great time together, simply enjoy our team and work hard. I wish you the best of luck. Welcome aboard!",
        // "Welcome to our company! On behalf of our team and management, we would like you to know that we are so grateful to have you. We believe that you can contribute a lot for our company’s success and improvement. Welcome aboard.",
        // "Congratulations for getting the job, thus, we would like you to know that we are all happy and excited to work with you. We believe that your abilities will help our company to grow more and become bigger.",
        // "We are so excited to have you in our group! We believe that you can use your skills and talent in making our company reach new heights.",
        // "Hope you will have an amazing time working with us and are really glad that you’ve joined us.",
        "You are here because you are EPIC! (I’ll let the P&C team decode that for you) and we are glad you joined us."
    ];

function joinUsers(users) {
    var i, joinedUsers = "";

    // Loop through the array supplied as an argument
    for (i = 0; i < users.length; i += 1) {
        // Assign the username to the joinedUsers variable
        joinedUsers += ('<@' + users[i].id + '|' + users[i].name + '>');
        // Check that the current index of the user is not the last in the array
        if (i !== (users.length - 1)) {
            // Append a white space to the variable
            joinedUsers += " ";
        }
    }

    return joinedUsers;
}

function randomReply(users) {
    var msg,
        randomMsg = MESSAGES.length ? MESSAGES[Math.floor(Math.random() * MESSAGES.length)] : WELCOME_MSGS[0],
        welcome = "Yo! " + joinUsers(users) + "\n\nYou got in! WHOOP! WHOOP!!";
        welcome += "\n\nWelcome to the coolest team ever! :andela: \n\n";

    welcome += randomMsg;

    // Check if there are users in the usersWithDefaultProfileImage array
    if (usersWithDefaultProfileImage.length) {
        if (usersWithDefaultProfileImage.length === 1) {
            msg = '\n\nWe love pictures! Please update your Slack profile with an on-fleek profile photo so we can easily spot you around the office.';
        } else {
            msg = '\n\n' + joinUsers(usersWithDefaultProfileImage) + ' we love pictures! Please update your Slack profile with an on-fleek profile photo so we can easily spot you around the office.';
        }

        // Append the msg variable to the welcome message.
        welcome += msg;
    }

    if (usersWithNoTitle.length) {
        if (usersWithNoTitle.length === 1) {
            msg = "\n\nAdd your role to your profile description so we can easily tease… I mean, know what you're up to.";
        } else {
            msg = "\n\n" + joinUsers(usersWithNoTitle) + " add your role to your profile description so we can easily tease… I mean, know what you're up to.";
        }

        welcome += msg;
    }

    // Append the last message to the welcome message
    welcome += "\n\nWe'd also love an introduction spiced with funny and weird facts about you. Don't be shy. At Andela, every individual is *_special_*. We can’t wait to discover your superpowers :wink:\n\nYou are Andela!\n\nWelcome :tia:";

    return welcome;
}

function bot(robot) {
    // Get all the messages in the database with the active status
    // robot.http(DB_URL + '/messages.json')
    // .headers({'Content-Type': 'application/json'})
    // .get()(function (err, response, body) {
    //     var key;
    //     if (err) {
    //         MESSAGES = WELCOME_MSGS;
    //         return;
    //     }
    //     if (body) {
    //         body = JSON.parse(body);

    //         for (key in body) {
    //             MESSAGES.push(body[key].message);
    //         }

    //         return;
    //     }
    // });

    robot.enter(function (res) {
        // Check if the user is not a bot and has only entered the general channel
        if (res.message.room === 'general' || 'ladi-bot' && !res.message.user.slack.is_bot) {
            // Add new user to the users array
            users.push(res.message.user);

            // Check if the user still has the default image
            if (!res.message.user.slack.profile.hasOwnProperty('image_original')) {
                usersWithDefaultProfileImage.push(res.message.user);
            }

            // Check if the user has no title in the profile
            if (!res.message.user.slack.profile.title) {
                usersWithNoTitle.push(res.message.user);
            }
        }

        // Clear timeout if a new user joins the channel within 30 seconds.
        if (timeout) {
            clearTimeout(timeout);
        }
        timeout = setTimeout(function () {
            // Reply all the users within 30 seconds.
            res.send(randomReply(users));

            // Reset all users array
            users = [];
            usersWithNoTitle = [];
            usersWithDefaultProfileImage = [];

        }, 30000);
        // Set timeout with function call to print random reply
    });
}

module.exports = bot;
<commit_msg>Updated welcome file with attachments<commit_after>var COMPANY_NAME = process.env.COMPANY_NAME,
    timeout, new_users = [];

function bot(robot) {
    robot.enter(function (res) {
        var msg = "",
            slack_attachment = {
                content: {
                    color: "#A6B2F7",
                    fallback: "",
                    pretext: "",
                    title: "",
                    text: "",
                    mrkdwn_in: ['text', 'pretext']
                },
                channel: ""
            },
            general_message_attachment = slack_attachment,
            profile_image_attachment,
            profile_title_attachment,
            direct_message_attachment,
            welcome_note;

        if (res.message.room === "general" || "ladi-bot" && !res.message.user.slack.is_bot) { // check if the user has entered the general or ladi-bot and is not a bot
            // Push the user into the users array.
            new_users.push(res.message.user);

            profile_image_attachment = slack_attachment;
            profile_title_attachment = slack_attachment;
            direct_message_attachment = slack_attachment;

            direct_message_attachment.content.fallback = "Welcome to " + COMPANY_NAME + " <@" + res.message.user.id + "|" + res.message.user.name + ">";
            direct_message_attachment.content.title = "Welcome to " + COMPANY_NAME + " <@" + res.message.user.id + "|" + res.message.user.name + ">";
            direct_message_attachment.content.text = "You are here because you are EPIC! (I’ll let the P&C team decode that for you) and we are glad you joined us.";
            direct_message_attachment.channel = res.message.user.name;

            robot.emit("slack-attachment", direct_message_attachment);

            if (!res.message.user.slack.profile.hasOwnProperty("image_original")) { // check if the user does not have a profile image
                msg = "We love pictures! Please update your slack profile with an on-fleek profile photo so we can easily spot you around the office.";

                profile_image_attachment.content.fallback = msg;
                profile_image_attachment.content.title = "About Your Profile Photo";
                profile_image_attachment.content.text = msg;
                profile_image_attachment.channel = res.message.user.name;

                robot.emit("slack-attachment", profile_image_attachment);
            }

            if (!res.message.user.slack.profile.title) { // check if the user does not have a profile title
                msg = "Add your role to your profile description so we can easily tease… I mean, know what you're up to.";

                profile_title_attachment.content.fallback = msg;
                profile_title_attachment.content.title = "About Your Profile Title";
                profile_title_attachment.content.text = msg;
                profile_title_attachment.channel = res.message.user.name;

                robot.emit("slack-attachment", profile_title_attachment);
            }
        }

        // clear timeout if a new user joins the channel within 30 seconds.
        if (timeout) {
            clearTimeout(timeout);
        }

        timeout = setTimeout(function () { // set a timeout to send the greeting
            // general_message_attachment
            general_message_attachment.content.fallback = "Welcome to " + COMPANY_NAME + " " + joinUsers(new_users);
            general_message_attachment.content.title = new_users.length > 1 ? "We Have New Members!" : "We Have A New Member!";
            general_message_attachment.content.text = "Welcome to " + COMPANY_NAME + " " + joinUsers(new_users);
            general_message_attachment.channel = res.message.room;

            // msg = "Welcome to " + COMPANY_NAME + " " + joinUsers(new_users);

            new_users = []; // reset all users array

            // return res.send(msg);

            return robot.emit("slack-attachment", general_message_attachment); // send a general greeting with all the users within 30 seconds.

        }, 30000);
    });
}

function joinUsers(users) {
    var i, joinedUsers = "";

    // Loop through the array supplied as an argument
    for (i = 0; i < users.length; i += 1) {
        joinedUsers += ("<@" + users[i].id + "|" + users[i].name + ">"); // Assign the username to the joinedUsers variable

        if (i !== (users.length - 1)) { // Check that the current index of the user is not the last in the array
            joinedUsers += " "; // Append a white space to the variable
        }
    }

    return joinedUsers;
}

module.exports = bot;<|endoftext|>


<commit_before>'use strict';

var FS = require('fs');
var Path = require('path');

var _ = require('lodash');
var URI = require('urijs');
var YAML = require('js-yaml');
var Promise = require('bluebird');
var traverse = require('traverse');
var Request = Promise.promisify(require('request'), {multiArgs: true});

module.exports.joinPath = function () {
  var argArray = Array.prototype.slice.call(arguments);
  return argArray.join('/').replace(/\/\/+/g, '/')
}

module.exports.parseJSON = Promise.method(JSON.parse);
module.exports.parseYAML = Promise.method(YAML.safeLoad);

function readUrl(url, callback) {
  var options = {
    uri: url,
    headers: {
      //TODO: allow different fomrats to define different MIME types.
      'Accept': 'application/json,*/*',
    }
  };

  return Request(options)
    .spread((response, data) => {
      if (response.statusCode !== 200)
        throw Error(`Can not GET ${url}: ` + response.statusMessage);
      return data;
    });
}

function readFile(filename) {
  return Promise.fromCallback(callback => {
    FS.readFile(filename, 'utf8', callback);
  });
}

function readDummy(data) {
  return Promise.resolve(data);
}

module.exports.resourceReaders = {
  url: readUrl,
  file: readFile,
  object: readDummy,
  string: readDummy,
};

module.exports.getSourceType = function (source) {
  if (_.isObject(source))
    return 'object';
  if (!_.isString(source))
    return undefined;

  // windows resolved paths look like absolute URLs,
  // so check for file existence.
  try {
    // FIXME: existsSync fails in browser
    if (FS.existsSync(source)) return 'file';
  } catch (e) {}

  var uri = new URI(source);
  if (uri.is('absolute'))
    return 'url';
  else if (uri.is('relative'))
    return 'file';
  else
    return 'string';
};

module.exports.removeNonValues = function (obj) {
  traverse(obj).forEach(function (value) {
    if (value === undefined || value === null)
      this.remove();
  });
}
<commit_msg>fix: preserve nulls in conversions, fixes #210 (#211)<commit_after>'use strict';

var FS = require('fs');
var Path = require('path');

var _ = require('lodash');
var URI = require('urijs');
var YAML = require('js-yaml');
var Promise = require('bluebird');
var traverse = require('traverse');
var Request = Promise.promisify(require('request'), {multiArgs: true});

module.exports.joinPath = function () {
  var argArray = Array.prototype.slice.call(arguments);
  return argArray.join('/').replace(/\/\/+/g, '/')
}

module.exports.parseJSON = Promise.method(JSON.parse);
module.exports.parseYAML = Promise.method(YAML.safeLoad);

function readUrl(url, callback) {
  var options = {
    uri: url,
    headers: {
      //TODO: allow different fomrats to define different MIME types.
      'Accept': 'application/json,*/*',
    }
  };

  return Request(options)
    .spread((response, data) => {
      if (response.statusCode !== 200)
        throw Error(`Can not GET ${url}: ` + response.statusMessage);
      return data;
    });
}

function readFile(filename) {
  return Promise.fromCallback(callback => {
    FS.readFile(filename, 'utf8', callback);
  });
}

function readDummy(data) {
  return Promise.resolve(data);
}

module.exports.resourceReaders = {
  url: readUrl,
  file: readFile,
  object: readDummy,
  string: readDummy,
};

module.exports.getSourceType = function (source) {
  if (_.isObject(source))
    return 'object';
  if (!_.isString(source))
    return undefined;

  // windows resolved paths look like absolute URLs,
  // so check for file existence.
  try {
    // FIXME: existsSync fails in browser
    if (FS.existsSync(source)) return 'file';
  } catch (e) {}

  var uri = new URI(source);
  if (uri.is('absolute'))
    return 'url';
  else if (uri.is('relative'))
    return 'file';
  else
    return 'string';
};

module.exports.removeNonValues = function (obj) {
  traverse(obj).forEach(function (value) {
    if (value === undefined)
      this.remove();
  });
}
<|endoftext|>


<commit_before>Rye.define('Util', function(){

    var _slice = Array.prototype.slice

    var uid = {
            current: 0
          , next: function(){ return ++this.current }
        }

    function extend (destination, source) {
        for (var key in source) {
            if (Object.prototype.hasOwnProperty.call(source, key)){
                destination[key] = source[key]
            }
        }
        return destination
    }

    function inherits (child, parent) {
        extend(child, parent)
        function Ctor () {
            this.constructor = child
        }
        Ctor.prototype = parent.prototype
        child.prototype = new Ctor()
        child.__super__ = parent.prototype
        return child
    }

    function isElement (element) {
        return element && (element.nodeType === 1 || element.nodeType === 9)
    }

    function isNodeList (obj) {
        return obj && (obj instanceof window.NodeList) || (obj instanceof window.HTMLCollection)
    }

    function unique (array) {
        return array.filter(function(item, idx){
            return array.indexOf(item) == idx
        })
    }

    function pluck (array, property) {
        return array.map(function(item){
            return item[property]
        })
    }

    function put (array, property, value) {
        return array.map(function(item){
            return item[property] = value
        })
    }

    function prefix (key, obj) {
        var result
          , upcased = key[0].toUpperCase() + key.substring(1)
          , prefixes = ['moz', 'webkit', 'ms', 'o']

        obj = obj || window

        if (result = obj[key]){
            return result
        }

        // No pretty array methods here :(
        // http://jsperf.com/everywhile
        while(prefix = prefixes.shift()){
            if (result = obj[prefix + upcased]){
                break;
            }
        }
        return result
    }

    function applier (fn, context, args) {
        return function () {
            fn.apply(context, _slice.call(arguments, 0).concat(args))
        }
    }

    function applierLeft (fn, context, args) {
        return function () {
            fn.apply(context, args.concat(_slice.call(arguments, 0)))
        }
    }

    function curry (fn) {
        return applierLeft(fn, this, _slice.call(arguments, 1))
    }

    function getUid (element) {
        return element.rye_id || (element.rye_id = uid.next())
    }

    return {
        extend      : extend
      , inherits    : inherits
      , isElement   : isElement
      , isNodeList  : isNodeList
      , unique      : unique
      , pluck       : pluck
      , put         : put
      , prefix      : prefix
      , applier     : applier
      , applierLeft : applierLeft
      , curry       : curry
      , getUid      : getUid
    }

})
<commit_msg>put() should be destructive<commit_after>Rye.define('Util', function(){

    var _slice = Array.prototype.slice

    var uid = {
            current: 0
          , next: function(){ return ++this.current }
        }

    function extend (destination, source) {
        for (var key in source) {
            if (Object.prototype.hasOwnProperty.call(source, key)){
                destination[key] = source[key]
            }
        }
        return destination
    }

    function inherits (child, parent) {
        extend(child, parent)
        function Ctor () {
            this.constructor = child
        }
        Ctor.prototype = parent.prototype
        child.prototype = new Ctor()
        child.__super__ = parent.prototype
        return child
    }

    function isElement (element) {
        return element && (element.nodeType === 1 || element.nodeType === 9)
    }

    function isNodeList (obj) {
        return obj && (obj instanceof window.NodeList) || (obj instanceof window.HTMLCollection)
    }

    function unique (array) {
        return array.filter(function(item, idx){
            return array.indexOf(item) == idx
        })
    }

    function pluck (array, property) {
        return array.map(function(item){
            return item[property]
        })
    }

    function put (array, property, value) {
        return array.forEach(function(item, i){
            array[i][property] = value
        })
    }

    function prefix (key, obj) {
        var result
          , upcased = key[0].toUpperCase() + key.substring(1)
          , prefixes = ['moz', 'webkit', 'ms', 'o']

        obj = obj || window

        if (result = obj[key]){
            return result
        }

        // No pretty array methods here :(
        // http://jsperf.com/everywhile
        while(prefix = prefixes.shift()){
            if (result = obj[prefix + upcased]){
                break;
            }
        }
        return result
    }

    function applier (fn, context, args) {
        return function () {
            fn.apply(context, _slice.call(arguments, 0).concat(args))
        }
    }

    function applierLeft (fn, context, args) {
        return function () {
            fn.apply(context, args.concat(_slice.call(arguments, 0)))
        }
    }

    function curry (fn) {
        return applierLeft(fn, this, _slice.call(arguments, 1))
    }

    function getUid (element) {
        return element.rye_id || (element.rye_id = uid.next())
    }

    return {
        extend      : extend
      , inherits    : inherits
      , isElement   : isElement
      , isNodeList  : isNodeList
      , unique      : unique
      , pluck       : pluck
      , put         : put
      , prefix      : prefix
      , applier     : applier
      , applierLeft : applierLeft
      , curry       : curry
      , getUid      : getUid
    }

})
<|endoftext|>


<commit_before>var Database = require('../fleet/connection');
// Express
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var authentication = require('./middleware/authentication');

var routes = require('./routes/index');
var users = require('./routes/users');
var login = require('./routes/login');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser('Your_very_secret_cookie_code'));
app.use(require('less-middleware')(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));

app.use(authentication({login: '/login'}))

// Database middleware
app.use(function (req, res, next) {
	req.database = { models: app.models, connections: app.connections }
	next();
})

app.use('/', routes);
app.use('/users', users);
app.use('/login', login);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

// Make Database connection
// & Start the server
Database(function(connection){
	app.models = connection.collections;
	app.connections = connection.connections;

	app.listen(3000);
});<commit_msg>Fixed placement issue<commit_after>var Database = require('../fleet/connection');
// Express
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var authentication = require('./middleware/authentication');

var routes = require('./routes/index');
var users = require('./routes/users');
var login = require('./routes/login');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser('Your_very_secret_cookie_code'));
app.use(require('less-middleware')(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));

// Database middleware
app.use(function (req, res, next) {
	req.database = { models: app.models, connections: app.connections }
	next();
});

app.use(authentication({login: '/login'}));

app.use('/', routes);
app.use('/users', users);
app.use('/login', login);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

// Make Database connection
// & Start the server
Database(function(connection){
	app.models = connection.collections;
	app.connections = connection.connections;

	app.listen(3000);
});<|endoftext|>


<commit_before>var _ = require('lazy.js');
var extend = require('xtend');
var traverse = require('traverse');
var path = require('path');
var Promise = require('bluebird');

var boolStrings = {true: true, false: false};

var util = _(require('util')).merge({
  clone: extend,
  extend: extend,

  text: require('./text'),
  markup: require('./markup'),
  logger: require('./logger'),

  toArray: function (obj) { return [].slice.call(obj); },

  mod: function (n, m) { return ((n % m) + m) % m; },

  typeOf: function (val) {
    return (val.__proto__.constructor.toString().match(/\w+\s+(\w+)/) || [])[1];
  },

  getterSetter: function (name, getter, setter) {
    getter = getter || _.identity;
    setter = setter || _.identity;
    return function () {
      if (arguments.length) {
        var newVal = setter.apply(this, arguments);
        this.data[name] = newVal;
        this.emit && this.emit(name, getter.call(this, newVal));
        return this;
      } else {
        return getter.call(this, this.data[name]);
      }
    };
  },

  parseOpts: function (opts) {
    return traverse(opts).map(function (opt) {
      if (opt && typeof opt === 'string') {
        if (opt in boolStrings) return boolStrings[opt];

        var number = Number(opt);
        if (number === number) return number; // if (!isNaN(number))
      }
      return opt;
    });
  },

  resolvePath: function (givenPath) {
    if (!givenPath) givenPath = '';
    if (givenPath[0] === '~') {
      givenPath = path.join(process.platform !== 'win32'
        ? process.env.HOME
        : process.env.USERPROFILE
      , givenPath.slice(1));
    }
    return path.resolve.apply(null, [].slice.call(arguments, 1).concat([givenPath]));
  },

  getBinding: function (bindings, key) {
    for (var name in bindings) {
      if (bindings.hasOwnProperty(name)) {
        var keyBindings = bindings[name];
        if (!keyBindings) continue;
        if (typeof keyBindings === 'string') keyBindings = [keyBindings];
        if (keyBindings.some(function (binding) { return binding === key.full || binding === key.sequence; }))
          return name;
      }
    }
  }
}).toObject();

module.exports = util;
<commit_msg>refactor(getBinding): move to base-widget<commit_after>var _ = require('lazy.js');
var extend = require('xtend');
var traverse = require('traverse');
var path = require('path');
var Promise = require('bluebird');

var boolStrings = {true: true, false: false};

var util = _(require('util')).merge({
  clone: extend,
  extend: extend,

  text: require('./text'),
  markup: require('./markup'),
  logger: require('./logger'),

  toArray: function (obj) { return [].slice.call(obj); },

  mod: function (n, m) { return ((n % m) + m) % m; },

  typeOf: function (val) {
    return (val.__proto__.constructor.toString().match(/\w+\s+(\w+)/) || [])[1];
  },

  getterSetter: function (name, getter, setter) {
    getter = getter || _.identity;
    setter = setter || _.identity;
    return function () {
      if (arguments.length) {
        var newVal = setter.apply(this, arguments);
        this.data[name] = newVal;
        this.emit && this.emit(name, getter.call(this, newVal));
        return this;
      } else {
        return getter.call(this, this.data[name]);
      }
    };
  },

  parseOpts: function (opts) {
    return traverse(opts).map(function (opt) {
      if (opt && typeof opt === 'string') {
        if (opt in boolStrings) return boolStrings[opt];

        var number = Number(opt);
        if (number === number) return number; // if (!isNaN(number))
      }
      return opt;
    });
  },

  resolvePath: function (givenPath) {
    if (!givenPath) givenPath = '';
    if (givenPath[0] === '~') {
      givenPath = path.join(process.platform !== 'win32'
        ? process.env.HOME
        : process.env.USERPROFILE
      , givenPath.slice(1));
    }
    return path.resolve.apply(null, [].slice.call(arguments, 1).concat([givenPath]));
  }
}).toObject();

module.exports = util;
<|endoftext|>


<commit_before>'use babel'

import { BufferedProcess, Point, Range } from 'atom'

export default {
  initialDelay: 1000,
  startMoieServer(afterStart) {
    const self=this
    const execPath = atom.config.get('Moie.moieExec')
    const interface = atom.config.get('Moie.interface')
    const port = atom.config.get('Moie.port')
    const command = atom.config.get('Moie.javaExec')
    const args = ['-jar', execPath]
    const stdout = data => {
      if(data.indexOf(`Server running at ${interface}:${port}`) > -1) {
        //wait a vew seconds until server is loaded
        window.setTimeout(afterStart, self.initialDelay)
      }
      console.log("stdout", data)
    }
    const stderr = data => console.log("stderr", data)
    const exit = code => console.log("server exited with ", code)
    const process = new BufferedProcess({command,args, stdout, stderr, exit})
  },

  createErrorLine(errorObj) {
    const msg = errorObj.message.replace(/\n/g, "
")
    const cssClass = errorObj.type == 'Warning' ? 'warning-badge' : 'error-badge'
    return `
    ${errorObj.type} from
    ${errorObj.start.line}:${errorObj.start.column} to
    ${errorObj.end.line}:${errorObj.end.column}
    : ${msg}`
  },

  saveAllFiles() {
    const editors = atom.workspace.getTextEditors()
    editors.filter(v => this.isModelicaFile(v.getPath())).forEach(editor => {
      editor.save()
    })
  },

  currentFile() {
    return atom.workspace.getActiveTextEditor().getPath()
  },

  wordBelowCursor() {
    const editor = atom.workspace.getActiveTextEditor()
    const buffer = editor.getBuffer()
    const cursorPos = editor.getCursorBufferPosition()
    return this.wordBefore(cursorPos, buffer)
  },

  wordBelowPosition(position, buffer) {
    return this.wordBefore(position, buffer) + this.wordAfter(position, buffer)
  },

  wordBefore(pos, textBuffer) {
    let startPos = new Point(pos.row,pos.column-1)
    let word = textBuffer.getTextInRange(new Range(startPos, pos))
    while(!word.startsWith(" ") && startPos.column !=0) {
      startPos = new Point(startPos.row, startPos.column-1)
      word = textBuffer.getTextInRange(new Range(startPos, pos))
    }
    return word.trim()
  },

  wordAfter(pos, textBuffer) {
    let endPos = new Point(pos.row,pos.column+1)
    let word = textBuffer.getTextInRange(new Range(pos, endPos))
    while(!word.endsWith(" ") && !word.endsWith("\n")) {
      endPos = new Point(endPos.row, endPos.column+1)
      word = textBuffer.getTextInRange(new Range(pos, endPos))
    }
    return word.trim()
  },

  rangeBelowPosition(pos, buffer) {
    let startPos = new Point(pos.row, pos.column-1)
    let word = buffer.getTextInRange(new Range(startPos, pos))
    while(!word.startsWith(" ") && startPos.column !=0) {
      startPos = new Point(startPos.row, startPos.column-1)
      word = buffer.getTextInRange(new Range(startPos, pos))
    }

    let endPos = new Point(pos.row, pos.column+1)
    word = buffer.getTextInRange(new Range(pos, endPos))
    while(!word.endsWith(" ") && !word.endsWith("\n")) {
      endPos = new Point(endPos.row, endPos.column+1)
      word = buffer.getTextInRange(new Range(pos, endPos))
    }

    return new Range(startPos, endPos)
  },
  isModelicaFile(path) { return path.endsWith(".mo") },
  isModelicaScript(path) { return path.endsWith(".mos") },
  openFile(path) {
    atom.workspace.open(path)
  },

  FilePath(path) {
    this.path = path;
  },

  FilePosition(line, column) {
    this.line = line
    this.column = column
  }
}
<commit_msg>Fix endless loop in wordAfter()<commit_after>'use babel'

import { BufferedProcess, Point, Range } from 'atom'

export default {
  initialDelay: 1000,
  startMoieServer(afterStart) {
    const self=this
    const execPath = atom.config.get('Moie.moieExec')
    const interface = atom.config.get('Moie.interface')
    const port = atom.config.get('Moie.port')
    const command = atom.config.get('Moie.javaExec')
    const args = ['-jar', execPath]
    const stdout = data => {
      if(data.indexOf(`Server running at ${interface}:${port}`) > -1) {
        //wait a vew seconds until server is loaded
        window.setTimeout(afterStart, self.initialDelay)
      }
      console.log("stdout", data)
    }
    const stderr = data => console.log("stderr", data)
    const exit = code => console.log("server exited with ", code)
    const process = new BufferedProcess({command,args, stdout, stderr, exit})
  },

  createErrorLine(errorObj) {
    const msg = errorObj.message.replace(/\n/g, "
")
    const cssClass = errorObj.type == 'Warning' ? 'warning-badge' : 'error-badge'
    return `
    ${errorObj.type} from
    ${errorObj.start.line}:${errorObj.start.column} to
    ${errorObj.end.line}:${errorObj.end.column}
    : ${msg}`
  },

  saveAllFiles() {
    const editors = atom.workspace.getTextEditors()
    editors.filter(v => this.isModelicaFile(v.getPath())).forEach(editor => {
      editor.save()
    })
  },

  currentFile() {
    return atom.workspace.getActiveTextEditor().getPath()
  },

  wordBelowCursor() {
    const editor = atom.workspace.getActiveTextEditor()
    const buffer = editor.getBuffer()
    const cursorPos = editor.getCursorBufferPosition()
    return this.wordBefore(cursorPos, buffer)
  },

  wordBelowPosition(position, buffer) {
    return this.wordBefore(position, buffer) + this.wordAfter(position, buffer)
  },

  wordBefore(pos, textBuffer) {
    let startPos = new Point(pos.row,pos.column-1)
    let word = textBuffer.getTextInRange(new Range(startPos, pos))
    while(!word.startsWith(" ") && startPos.column !=0) {
      startPos = new Point(startPos.row, startPos.column-1)
      word = textBuffer.getTextInRange(new Range(startPos, pos))
    }
    return word.trim()
  },

  wordAfter(pos, textBuffer) {
    let endPos = new Point(pos.row,pos.column+1)
    let word = textBuffer.getTextInRange(new Range(pos, endPos))
    const lineLength = textBuffer.lineLengthForRow(pos.row)
    while(!word.endsWith(" ") && !word.endsWith("\n") && endPos.column < lineLength) {
      endPos = new Point(endPos.row, endPos.column+1)
      word = textBuffer.getTextInRange(new Range(pos, endPos))
    }
    return word.trim()
  },

  rangeBelowPosition(pos, buffer) {
    let startPos = new Point(pos.row, pos.column-1)
    let word = buffer.getTextInRange(new Range(startPos, pos))
    while(!word.startsWith(" ") && startPos.column !=0) {
      startPos = new Point(startPos.row, startPos.column-1)
      word = buffer.getTextInRange(new Range(startPos, pos))
    }

    let endPos = new Point(pos.row, pos.column+1)
    word = buffer.getTextInRange(new Range(pos, endPos))
    while(!word.endsWith(" ") && !word.endsWith("\n")) {
      endPos = new Point(endPos.row, endPos.column+1)
      word = buffer.getTextInRange(new Range(pos, endPos))
    }

    return new Range(startPos, endPos)
  },
  isModelicaFile(path) { return path.endsWith(".mo") },
  isModelicaScript(path) { return path.endsWith(".mos") },
  openFile(path) {
    atom.workspace.open(path)
  },

  FilePath(path) {
    this.path = path;
  },

  FilePosition(line, column) {
    this.line = line
    this.column = column
  }
}
<|endoftext|>


<commit_before>require('buffertools');
var crypto = require('crypto');
var bigint = require('bigint');
var Binary = require('./binary');
var logger = require('./logger');

// Native extensions
var ccmodule = require('../build-cc/default/native');

var NULL_HASH = exports.NULL_HASH = new Buffer(32).clear();

// How much of Bitcoin's internal integer coin representation makes 1 BTC
var COIN = 100000000;

var MAX_TARGET = new Buffer('00000000FFFF0000000000000000000000000000000000000000000000000000', 'hex');

var sha256 = exports.sha256 = function (data) {
	return new Buffer(crypto.createHash('sha256').update(data).digest('binary'), 'binary');
};

var ripe160 = exports.ripe160 = function (data) {
	return new Buffer(crypto.createHash('rmd160').update(data).digest('binary'), 'binary');
};

var twoSha256 = exports.twoSha256 = function (data) {
	return sha256(sha256(data));
};

var sha256ripe160 = exports.sha256ripe160 = function (data) {
	return ripe160(sha256(data));
};

var encodeBase58 = exports.encodeBase58 = ccmodule.base58_encode;

var decodeBase58 = exports.decodeBase58 = ccmodule.base58_decode;

/**
 * Format a block hash like the official client does.
 */
var formatHash = exports.formatHash = function (hash) {
	// Make a copy, because reverse() and toHex() are destructive.
	var hashEnd = new Buffer(10);
	hash.copy(hashEnd, 0, 22, 32);
	return hashEnd.reverse().toHex();
};

/**
 * Display the whole hash, as hex, in correct endian order.
 */
var formatHashFull = exports.formatHashFull = function (hash) {
	// Make a copy, because reverse() and toHex() are destructive.
	var copy = new Buffer(hash.length);
	hash.copy(copy);
	var hex = copy.reverse().toHex();
	return hex;
};

/**
 * Format a block hash like Block Explorer does.
 *
 * Formats a block hash by removing leading zeros and truncating to 10 characters.
 */
var formatHashAlt = exports.formatHashAlt = function (hash) {
	var hex = formatHashFull(hash);
	hex = hex.replace(/^0*/, '');
	return hex.substr(0, 10);
};

var formatBuffer = exports.formatBuffer = function (buffer, maxLen) {
	// Calculate amount of bytes to display
	maxLen = maxLen || 10;
	if (maxLen > buffer.length) maxLen = buffer.length;

	// Copy those bytes into a temporary buffer
	var temp = new Buffer(maxLen);
	buffer.copy(temp, 0, 0, maxLen);

	// Format as string
	var output = temp.toHex();
	if (temp.length < buffer.length) output += "...";
	return output;
};

var valueToBigInt = exports.valueToBigInt = function (valueBuffer) {
	if (valueBuffer instanceof bigint) return valueBuffer;
	return bigint.fromBuffer(valueBuffer, {endian: 'little', size: 8});
};

var formatValue = exports.formatValue = function (valueBuffer) {
	var value = valueToBigInt(valueBuffer).toString();
	var integerPart = value.length > 8 ? value.substr(0, value.length-8) : '0';
	var decimalPart = value.length > 8 ? value.substr(value.length-8) : value;
	while (decimalPart.length < 8) decimalPart = "0"+decimalPart;
	decimalPart = decimalPart.replace(/0*$/, '');
	while (decimalPart.length < 2) decimalPart += "0";
	return integerPart+"."+decimalPart;
};

var pubKeyHashToAddress = exports.pubKeyHashToAddress = function (pubKeyHash) {
	if (!pubKeyHash) return "";

	var put = Binary.put();
	// Version
	put.word8le(0);
	// Hash
	put.put(pubKeyHash);
	// Checksum (four bytes)
	put.put(twoSha256(put.buffer()).slice(0,4));
	return encodeBase58(put.buffer());
};

var addressToPubKeyHash = exports.addressToPubKeyHash = function (address) {
	// Trim
	var address = new String(address).replace(/\s/g, '');

	// Check sanity
	if (!address.match(/^[1-9A-HJ-NP-Za-km-z]{27,35}$/)) {
		logger.warn("Not a valid Bitcoin address");
		return null;
	}

	// Decode
	var buffer = decodeBase58(address);

	// Parse
	var parser = Binary.parse(buffer);
	parser.word8('version');
	parser.buffer('hash', 20);
	parser.buffer('checksum', 4);

	// Check checksum
	var checksum = twoSha256(buffer.slice(0, 21)).slice(0, 4);
	if (checksum.compare(parser.vars.checksum) != 0) {
		logger.warn("Checksum comparison failed");
		return null;
	}

	return parser.vars.hash;
};

// Utility that synchronizes function calls based on a key
var createSynchrotron = exports.createSynchrotron = function (fn) {
	var table = {};
	return function (key) {
		var args = Array.prototype.slice.call(arguments);
		var run = function () {
			// Function fn() will call when it finishes
			args[0] = function next() {
				if (table[key]) {
					if (table[key].length) {
						table[key].shift()();
					} else {
						delete table[key];
					}
				}
			};

			fn.apply(null, args);
		};

		if (!table[key]) {
			table[key] = [];
			run();
		} else {
			table[key].push(run);
		}
	};
};

/**
 * Generate a random 64-bit number.
 *
 * With ideas from node-uuid:
 * Copyright (c) 2010 Robert Kieffer
 * https://github.com/broofa/node-uuid/
 *
 * @returns Buffer random nonce
 */
var generateNonce = exports.generateNonce = function () {
	var b32 = 0x100000000, ff = 0xff;
	var b = new Buffer(8), i = 0;

	// Generate eight random bytes
	r = Math.random()*b32;
	b[i++] = r & ff;
	b[i++] = (r=r>>>8) & ff;
	b[i++] = (r=r>>>8) & ff;
	b[i++] = (r=r>>>8) & ff;
	r = Math.random()*b32;
	b[i++] = r & ff;
	b[i++] = (r=r>>>8) & ff;
	b[i++] = (r=r>>>8) & ff;
	b[i++] = (r=r>>>8) & ff;

	return b;
};

/**
 * Decode difficulty bits.
 *
 * This function calculates the difficulty target given the difficulty bits.
 */
var decodeDiffBits = exports.decodeDiffBits = function (diffBits) {
	diffBits = parseInt(diffBits);
	var target = bigint(diffBits & 0xffffff);
	// TODO: Add bitwise shift in upstream node-bigint
	target = target.mul(bigint(2).pow(8*((diffBits >>> 24) - 3)));
	var diffBuf = target.toBuffer();
	var targetBuf = new Buffer(32).clear();
	diffBuf.copy(targetBuf, 32-diffBuf.length);
	return targetBuf;
};

/**
 * Calculate "difficulty".
 *
 * This function calculates the maximum difficulty target divided by the given
 * difficulty target.
 */
var calcDifficulty = exports.calcDifficulty = function (target) {
	if (!(target instanceof Buffer)) target = decodeDiffBits(target);
	var targetBigint = bigint.fromBuffer(target, {order: 'forward'});
	var maxBigint = bigint.fromBuffer(MAX_TARGET, {order: 'forward'});
	return maxBigint.div(targetBigint).toNumber();
};
<commit_msg>Export constants.<commit_after>require('buffertools');
var crypto = require('crypto');
var bigint = require('bigint');
var Binary = require('./binary');
var logger = require('./logger');

// Native extensions
var ccmodule = require('../build-cc/default/native');

var NULL_HASH = exports.NULL_HASH = new Buffer(32).clear();

// How much of Bitcoin's internal integer coin representation makes 1 BTC
var COIN = exports.COIN = 100000000;

var MAX_TARGET = exports.MAX_TARGET = new Buffer('00000000FFFF0000000000000000000000000000000000000000000000000000', 'hex');

var sha256 = exports.sha256 = function (data) {
	return new Buffer(crypto.createHash('sha256').update(data).digest('binary'), 'binary');
};

var ripe160 = exports.ripe160 = function (data) {
	return new Buffer(crypto.createHash('rmd160').update(data).digest('binary'), 'binary');
};

var twoSha256 = exports.twoSha256 = function (data) {
	return sha256(sha256(data));
};

var sha256ripe160 = exports.sha256ripe160 = function (data) {
	return ripe160(sha256(data));
};

var encodeBase58 = exports.encodeBase58 = ccmodule.base58_encode;

var decodeBase58 = exports.decodeBase58 = ccmodule.base58_decode;

/**
 * Format a block hash like the official client does.
 */
var formatHash = exports.formatHash = function (hash) {
	// Make a copy, because reverse() and toHex() are destructive.
	var hashEnd = new Buffer(10);
	hash.copy(hashEnd, 0, 22, 32);
	return hashEnd.reverse().toHex();
};

/**
 * Display the whole hash, as hex, in correct endian order.
 */
var formatHashFull = exports.formatHashFull = function (hash) {
	// Make a copy, because reverse() and toHex() are destructive.
	var copy = new Buffer(hash.length);
	hash.copy(copy);
	var hex = copy.reverse().toHex();
	return hex;
};

/**
 * Format a block hash like Block Explorer does.
 *
 * Formats a block hash by removing leading zeros and truncating to 10 characters.
 */
var formatHashAlt = exports.formatHashAlt = function (hash) {
	var hex = formatHashFull(hash);
	hex = hex.replace(/^0*/, '');
	return hex.substr(0, 10);
};

var formatBuffer = exports.formatBuffer = function (buffer, maxLen) {
	// Calculate amount of bytes to display
	maxLen = maxLen || 10;
	if (maxLen > buffer.length) maxLen = buffer.length;

	// Copy those bytes into a temporary buffer
	var temp = new Buffer(maxLen);
	buffer.copy(temp, 0, 0, maxLen);

	// Format as string
	var output = temp.toHex();
	if (temp.length < buffer.length) output += "...";
	return output;
};

var valueToBigInt = exports.valueToBigInt = function (valueBuffer) {
	if (valueBuffer instanceof bigint) return valueBuffer;
	return bigint.fromBuffer(valueBuffer, {endian: 'little', size: 8});
};

var formatValue = exports.formatValue = function (valueBuffer) {
	var value = valueToBigInt(valueBuffer).toString();
	var integerPart = value.length > 8 ? value.substr(0, value.length-8) : '0';
	var decimalPart = value.length > 8 ? value.substr(value.length-8) : value;
	while (decimalPart.length < 8) decimalPart = "0"+decimalPart;
	decimalPart = decimalPart.replace(/0*$/, '');
	while (decimalPart.length < 2) decimalPart += "0";
	return integerPart+"."+decimalPart;
};

var pubKeyHashToAddress = exports.pubKeyHashToAddress = function (pubKeyHash) {
	if (!pubKeyHash) return "";

	var put = Binary.put();
	// Version
	put.word8le(0);
	// Hash
	put.put(pubKeyHash);
	// Checksum (four bytes)
	put.put(twoSha256(put.buffer()).slice(0,4));
	return encodeBase58(put.buffer());
};

var addressToPubKeyHash = exports.addressToPubKeyHash = function (address) {
	// Trim
	var address = new String(address).replace(/\s/g, '');

	// Check sanity
	if (!address.match(/^[1-9A-HJ-NP-Za-km-z]{27,35}$/)) {
		logger.warn("Not a valid Bitcoin address");
		return null;
	}

	// Decode
	var buffer = decodeBase58(address);

	// Parse
	var parser = Binary.parse(buffer);
	parser.word8('version');
	parser.buffer('hash', 20);
	parser.buffer('checksum', 4);

	// Check checksum
	var checksum = twoSha256(buffer.slice(0, 21)).slice(0, 4);
	if (checksum.compare(parser.vars.checksum) != 0) {
		logger.warn("Checksum comparison failed");
		return null;
	}

	return parser.vars.hash;
};

// Utility that synchronizes function calls based on a key
var createSynchrotron = exports.createSynchrotron = function (fn) {
	var table = {};
	return function (key) {
		var args = Array.prototype.slice.call(arguments);
		var run = function () {
			// Function fn() will call when it finishes
			args[0] = function next() {
				if (table[key]) {
					if (table[key].length) {
						table[key].shift()();
					} else {
						delete table[key];
					}
				}
			};

			fn.apply(null, args);
		};

		if (!table[key]) {
			table[key] = [];
			run();
		} else {
			table[key].push(run);
		}
	};
};

/**
 * Generate a random 64-bit number.
 *
 * With ideas from node-uuid:
 * Copyright (c) 2010 Robert Kieffer
 * https://github.com/broofa/node-uuid/
 *
 * @returns Buffer random nonce
 */
var generateNonce = exports.generateNonce = function () {
	var b32 = 0x100000000, ff = 0xff;
	var b = new Buffer(8), i = 0;

	// Generate eight random bytes
	r = Math.random()*b32;
	b[i++] = r & ff;
	b[i++] = (r=r>>>8) & ff;
	b[i++] = (r=r>>>8) & ff;
	b[i++] = (r=r>>>8) & ff;
	r = Math.random()*b32;
	b[i++] = r & ff;
	b[i++] = (r=r>>>8) & ff;
	b[i++] = (r=r>>>8) & ff;
	b[i++] = (r=r>>>8) & ff;

	return b;
};

/**
 * Decode difficulty bits.
 *
 * This function calculates the difficulty target given the difficulty bits.
 */
var decodeDiffBits = exports.decodeDiffBits = function (diffBits) {
	diffBits = parseInt(diffBits);
	var target = bigint(diffBits & 0xffffff);
	// TODO: Add bitwise shift in upstream node-bigint
	target = target.mul(bigint(2).pow(8*((diffBits >>> 24) - 3)));
	var diffBuf = target.toBuffer();
	var targetBuf = new Buffer(32).clear();
	diffBuf.copy(targetBuf, 32-diffBuf.length);
	return targetBuf;
};

/**
 * Calculate "difficulty".
 *
 * This function calculates the maximum difficulty target divided by the given
 * difficulty target.
 */
var calcDifficulty = exports.calcDifficulty = function (target) {
	if (!(target instanceof Buffer)) target = decodeDiffBits(target);
	var targetBigint = bigint.fromBuffer(target, {order: 'forward'});
	var maxBigint = bigint.fromBuffer(MAX_TARGET, {order: 'forward'});
	return maxBigint.div(targetBigint).toNumber();
};
<|endoftext|>


<commit_before>/**
 * Created by nuintun on 2015/4/27.
 */

'use strict';

var is = require('is');
var path = require('path');
var join = path.join;
var extname = path.extname;
var dirname = path.dirname;
var basename = path.basename;
var relative = path.relative;
var util = require('util');
var colors = require('colors/safe');
var debug = require('debug')('gulp-cmd');

// The work cwd
var cwd = process.cwd();

// Set debug color use 6
debug.color = 6;

/**
 * Parse package form vinyl
 * @param vinyl
 * @param wwwroot
 * @returns {object}
 */
function parsePackage(vinyl, wwwroot){
  var relative = vinyl.relative;

  // vinyl not in base dir, user wwwroot
  if (isRelative(relative)) {
    relative = path.relative(wwwroot, vinyl.path);
    // vinyl not in wwwroot, throw error
    if (isRelative(relative)) {
      throwError('file: %s is out of bound of wwwroot: %s.', normalize(vinyl.path), normalize(wwwroot));
    }

    // reset relative
    relative = path.join('/', relative);
  }

  var dir = normalize(dirname(relative));
  var filename = basename(relative);
  var SPLITRE = /\/((?:\d+\.){2}\d+)(?:\/|$)/;
  var match = dir.split(SPLITRE);

  return {
    name: match[0] || '',
    version: match[1] || '',
    file: match[2] ? match[2] + '/' + filename : filename
  }
}

/**
 * Simple template
 * ```
 * var tpl = '{{name}}/{{version}}';
 * util.template(tpl, {name:'base', version: '1.0.0'});
 * ```
 */

function template(format, data){
  if (!is.string(format)) return '';

  return format.replace(/{{([a-z]*)}}/gi, function (all, match){
    return data[match] || '';
  });
}

/**
 * Create a plugin
 * @param name
 * @param transport
 * @returns {Function}
 */

function plugin(name, transport){
  return function (vinyl, options){
    // debug
    debug('load plugin: %s', colors.green(name));
    // debug
    debug('read file: %s', colors.magenta(pathFromCwd(vinyl.path)));

    vinyl = transport(vinyl, options);

    return vinyl;
  };
}

var PATHS_RE = /^([^/:]+)(\/.+)$/;
var VARS_RE = /{([^{]+)}/g;

/**
 * Parse alias
 * @param id
 * @param alias
 * @returns {*}
 */

function parseAlias(id, alias){
  alias = alias || {};

  return alias && is.string(alias[id]) ? alias[id] : id;
}

/**
 * Parse paths
 * @param id
 * @param paths
 * @returns {*}
 */

function parsePaths(id, paths){
  var match;

  paths = paths || {};

  if (paths && (match = id.match(PATHS_RE)) && is.string(paths[match[1]])) {
    id = paths[match[1]] + match[2];
  }

  return id;
}

/**
 * Parse vars
 * @param id
 * @param vars
 * @returns {*}
 */

function parseVars(id, vars){
  vars = vars || {};

  if (vars && id.indexOf('{') > -1) {
    id = id.replace(VARS_RE, function (match, key){
      return is.string(vars[key]) ? vars[key] : match;
    });
  }

  return id;
}

/**
 * Normalize path
 * @param path
 * @returns {string}
 */

function normalize(path){
  path = path.replace(/\\+/g, '/');
  path = path.replace(/([^:/])\/+\//g, '$1/');
  path = path.replace(/(:)?\/{2,}/, '$1//');

  return path;
}

/**
 * Resolve a `relative` path base on `base` path
 * @param relative
 * @param vinyl
 * @param wwwroot
 * @returns {string}
 */

function resolve(relative, vinyl, wwwroot){
  var base;
  var absolute;

  // debug
  debug('resolve path: %s', colors.magenta(normalize(relative)));

  // resolve
  if (isRelative(relative)) {
    base = dirname(vinyl.path);
    absolute = join(base, relative);

    // out of base, use wwwroot
    if (isRelative(absolute)) {
      base = wwwroot;
      absolute = join(base, relative);

      // out of wwwroot
      if (isRelative(absolute)) {
        throwError('file: %s is out of bound of wwwroot: %s.', normalize(absolute), normalize(base));
      }
    }
  } else if (isAbsolute(relative)) {
    base = wwwroot;
    absolute = join(base, relative.substring(1));
  } else {
    base = join(vinyl.cwd, vinyl.base);
    absolute = join(base, relative);
  }

  // debug
  debug('of base path: %s', colors.magenta(pathFromCwd(base)));
  debug('to: %s', colors.magenta(pathFromCwd(absolute)));

  return absolute;
}

/**
 * Hide .js if exists
 * @param path
 * @returns {*}
 */

function hideExt(path){
  return extname(path) === '.js' ? path.replace(/\.js$/, '') : path;
}

/**
 * Add .js if not exists
 * @param path
 * @returns {*}
 */

function addExt(path){
  return extname(path) === '.js' ? path : (path + '.js');
}

/**
 * Test path is relative path or not
 * @param path
 * @returns {boolean}
 */

function isRelative(path){
  return /^\.{1,2}[\\/]/.test(path);
}

/**
 * Test path is absolute path or not
 * @param path
 * @returns {boolean}
 */

function isAbsolute(path){
  return /^[\\/](?:[^\\/]+|$)/.test(path);
}

/**
 * Test path is local path or not
 * @param path
 * @returns {boolean}
 */

function isLocal(path){
  return !/^https?:\/\/|^\/\//.test(path) && !/^data:/.test(path);
}

/**
 * Get relative path from cwd
 * @param path
 * @returns {string}
 */

function pathFromCwd(path){
  return normalize(relative(cwd, path));
}

/**
 * Plugin error
 */

function throwError(){
  var slice = [].slice;
  var message = util.format
    .apply(null, slice.call(arguments));

  throw new Error(message);
}

/**
 * Node extend
 * Copyright 2011, John Resig
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * @fileoverview
 * Port of jQuery.extend that actually works on node.js
 */

function extend(){
  var target = arguments[0] || {};
  var i = 1;
  var length = arguments.length;
  var deep = false;
  var options, name, src, copy, copy_is_array, clone;

  // handle a deep copy situation
  if (typeof target === 'boolean') {
    deep = target;
    target = arguments[1] || {};
    // skip the boolean and the target
    i = 2;
  }

  // handle case when target is a string or something (possible in deep copy)
  if (typeof target !== 'object' && !is.fn(target)) {
    target = {};
  }

  for (; i < length; i++) {
    // only deal with non-null/undefined values
    options = arguments[i];

    if (options !== null) {
      if (typeof options === 'string') {
        options = options.split('');
      }

      // extend the base object
      for (name in options) {
        if (options.hasOwnProperty(name)) {
          src = target[name];
          copy = options[name];

          // prevent never-ending loop
          if (target === copy) {
            continue;
          }

          // recurse if we're merging plain objects or arrays
          if (deep && copy && (is.hash(copy) || (copy_is_array = Array.isArray(copy)))) {
            if (copy_is_array) {
              copy_is_array = false;
              clone = src && Array.isArray(src) ? src : [];
            } else {
              clone = src && is.hash(src) ? src : {};
            }

            // never move original objects, clone them
            target[name] = extend(deep, clone, copy);

            // don't bring in undefined values
          } else if (typeof copy !== 'undefined') {
            target[name] = copy;
          }
        }
      }
    }
  }

  // return the modified object
  return target;
}

/**
 * Transform array to string
 * @param arr
 * @returns {string}
 */

function arr2str(arr){
  return arr.map(function (item){
    return '"' + item.replace(/"/g, '\\"') + '"';
  }).join(', ');
}

/**
 * Wrap module
 * @param id
 * @param deps
 * @param code
 * @returns {string}
 */

function wrapModule(id, deps, code){
  deps = arr2str(deps);

  // header and footer template string
  var headerTpl = 'define("{{id}}", [{{deps}}], function(require, exports, module){';
  var footerTpl = '});\n\n';

  if (Buffer.isBuffer(code)) code = code.toString();

  // debug
  debug('compile module: %s', colors.magenta(id));

  return template(headerTpl, { id: id.replace(/"/g, '\\"'), deps: deps })
    + '\n' + code + '\n' + footerTpl;
}

/**
 * Exports module.
 */

module.exports.cwd = cwd;
module.exports.template = template;
module.exports.parsePackage = parsePackage;
module.exports.plugin = plugin;
module.exports.normalize = normalize;
module.exports.parseAlias = parseAlias;
module.exports.parsePaths = parsePaths;
module.exports.parseVars = parseVars;
module.exports.hideExt = hideExt;
module.exports.addExt = addExt;
module.exports.isRelative = isRelative;
module.exports.isAbsolute = isAbsolute;
module.exports.isLocal = isLocal;
module.exports.resolve = resolve;
module.exports.pathFromCwd = pathFromCwd;
module.exports.throwError = throwError;
module.exports.extend = extend;
module.exports.colors = colors;
module.exports.debug = debug;
module.exports.wrapModule = wrapModule;
<commit_msg>add source files<commit_after>/**
 * Created by nuintun on 2015/4/27.
 */

'use strict';

var is = require('is');
var path = require('path');
var join = path.join;
var extname = path.extname;
var dirname = path.dirname;
var basename = path.basename;
var relative = path.relative;
var util = require('util');
var colors = require('colors/safe');
var debug = require('debug')('gulp-cmd');

// The work cwd
var cwd = process.cwd();

// Set debug color use 6
debug.color = 6;

/**
 * Parse package form vinyl
 * @param vinyl
 * @param wwwroot
 * @returns {object}
 */
function parsePackage(vinyl, wwwroot){
  var relative = vinyl.relative;

  // vinyl not in base dir, user wwwroot
  if (isRelative(relative)) {
    relative = path.relative(wwwroot, vinyl.path);
    // vinyl not in wwwroot, throw error
    if (isRelative(relative)) {
      throwError('file: %s is out of bound of wwwroot: %s.', normalize(vinyl.path), normalize(wwwroot));
    }

    // reset relative
    relative = path.join('/', relative);
  }

  var dir = normalize(dirname(relative));
  var filename = basename(relative);
  var SPLITRE = /\/((?:\d+\.){2}\d+)(?:\/|$)/;
  var match = dir.split(SPLITRE);

  return {
    name: match[0] || '',
    version: match[1] || '',
    file: match[2] ? match[2] + '/' + filename : filename
  }
}

/**
 * Simple template
 * ```
 * var tpl = '{{name}}/{{version}}';
 * util.template(tpl, {name:'base', version: '1.0.0'});
 * ```
 */

function template(format, data){
  if (!is.string(format)) return '';

  return format.replace(/{{([a-z]*)}}/gi, function (all, match){
    return data[match] || '';
  });
}

/**
 * Create a plugin
 * @param name
 * @param transport
 * @returns {Function}
 */

function plugin(name, transport){
  return function (vinyl, options){
    // debug
    debug('load plugin: %s', colors.green(name));
    // debug
    debug('read file: %s', colors.magenta(pathFromCwd(vinyl.path)));

    vinyl = transport(vinyl, options);

    return vinyl;
  };
}

var PATHS_RE = /^([^/:]+)(\/.+)$/;
var VARS_RE = /{([^{]+)}/g;

/**
 * Parse alias
 * @param id
 * @param alias
 * @returns {*}
 */

function parseAlias(id, alias){
  alias = alias || {};

  return alias && is.string(alias[id]) ? alias[id] : id;
}

/**
 * Parse paths
 * @param id
 * @param paths
 * @returns {*}
 */

function parsePaths(id, paths){
  var match;

  paths = paths || {};

  if (paths && (match = id.match(PATHS_RE)) && is.string(paths[match[1]])) {
    id = paths[match[1]] + match[2];
  }

  return id;
}

/**
 * Parse vars
 * @param id
 * @param vars
 * @returns {*}
 */

function parseVars(id, vars){
  vars = vars || {};

  if (vars && id.indexOf('{') > -1) {
    id = id.replace(VARS_RE, function (match, key){
      return is.string(vars[key]) ? vars[key] : match;
    });
  }

  return id;
}

/**
 * Normalize path
 * @param path
 * @returns {string}
 */

function normalize(path){
  path = path.replace(/\\+/g, '/');
  path = path.replace(/([^:/])\/+\//g, '$1/');
  path = path.replace(/(:)?\/{2,}/, '$1//');

  return path;
}

/**
 * Resolve a `relative` path base on `base` path
 * @param relative
 * @param vinyl
 * @param wwwroot
 * @returns {string}
 */

function resolve(relative, vinyl, wwwroot){
  var base;
  var absolute;

  // debug
  debug('resolve path: %s', colors.magenta(normalize(relative)));

  // resolve
  if (isRelative(relative)) {
    base = dirname(vinyl.path);
    absolute = join(base, relative);

    // out of base, use wwwroot
    if (isRelative(absolute)) {
      base = wwwroot;
      absolute = join(base, relative);

      // out of wwwroot
      if (isRelative(absolute)) {
        throwError('file: %s is out of bound of wwwroot: %s.', normalize(absolute), normalize(base));
      }
    }
  } else if (isAbsolute(relative)) {
    base = wwwroot;
    absolute = join(base, relative.substring(1));
  } else {
    base = join(vinyl.cwd, vinyl.base);
    absolute = join(base, relative);
  }

  // debug
  debug('of base path: %s', colors.magenta(pathFromCwd(base)));
  debug('to: %s', colors.magenta(pathFromCwd(absolute)));

  return absolute;
}

/**
 * Hide .js if exists
 * @param path
 * @returns {*}
 */

function hideExt(path){
  return extname(path) === '.js' ? path.replace(/\.js$/, '') : path;
}

/**
 * Add .js if not exists
 * @param path
 * @returns {*}
 */

function addExt(path){
  return extname(path) === '.js' ? path : (path + '.js');
}

/**
 * Test path is relative path or not
 * @param path
 * @returns {boolean}
 */

function isRelative(path){
  return /^\.{1,2}[\\/]/.test(path);
}

/**
 * Test path is absolute path or not
 * @param path
 * @returns {boolean}
 */

function isAbsolute(path){
  return /^[\\/](?:[^\\/]+|$)/.test(path);
}

/**
 * Test path is local path or not
 * @param path
 * @returns {boolean}
 */

function isLocal(path){
  return !/^https?:\/\/|^\/\//.test(path) && !/^data:/.test(path);
}

/**
 * Get relative path from cwd
 * @param path
 * @returns {string}
 */

function pathFromCwd(path){
  return normalize(relative(cwd, path));
}

/**
 * Plugin error
 */

function throwError(){
  var slice = [].slice;
  var message = util.format
    .apply(null, slice.call(arguments));

  throw new Error(message);
}

/**
 * Node extend
 * Copyright 2011, John Resig
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * @fileoverview
 * Port of jQuery.extend that actually works on node.js
 */

function extend(){
  var target = arguments[0] || {};
  var i = 1;
  var length = arguments.length;
  var deep = false;
  var options, name, src, copy, copy_is_array, clone;

  // handle a deep copy situation
  if (typeof target === 'boolean') {
    deep = target;
    target = arguments[1] || {};
    // skip the boolean and the target
    i = 2;
  }

  // handle case when target is a string or something (possible in deep copy)
  if (typeof target !== 'object' && !is.fn(target)) {
    target = {};
  }

  for (; i < length; i++) {
    // only deal with non-null/undefined values
    options = arguments[i];

    if (options !== null) {
      if (typeof options === 'string') {
        options = options.split('');
      }

      // extend the base object
      for (name in options) {
        if (options.hasOwnProperty(name)) {
          src = target[name];
          copy = options[name];

          // prevent never-ending loop
          if (target === copy) {
            continue;
          }

          // recurse if we're merging plain objects or arrays
          if (deep && copy && (is.hash(copy) || (copy_is_array = Array.isArray(copy)))) {
            if (copy_is_array) {
              copy_is_array = false;
              clone = src && Array.isArray(src) ? src : [];
            } else {
              clone = src && is.hash(src) ? src : {};
            }

            // never move original objects, clone them
            target[name] = extend(deep, clone, copy);

            // don't bring in undefined values
          } else if (typeof copy !== 'undefined') {
            target[name] = copy;
          }
        }
      }
    }
  }

  // return the modified object
  return target;
}

/**
 * Wrap module
 * @param id
 * @param deps
 * @param code
 * @returns {string}
 */

function wrapModule(id, deps, code){
  // header and footer template string
  var headerTpl = 'define({{id}}, {{deps}}, function(require, exports, module){';
  var footerTpl = '});\n\n';

  if (Buffer.isBuffer(code)) code = code.toString();

  // debug
  debug('compile module: %s', colors.magenta(id));

  id = JSON.stringify(id);
  deps = JSON.stringify(deps);

  return template(headerTpl, { id: id, deps: deps })
    + '\n' + code + '\n' + footerTpl;
}

/**
 * Exports module.
 */

module.exports.cwd = cwd;
module.exports.template = template;
module.exports.parsePackage = parsePackage;
module.exports.plugin = plugin;
module.exports.normalize = normalize;
module.exports.parseAlias = parseAlias;
module.exports.parsePaths = parsePaths;
module.exports.parseVars = parseVars;
module.exports.hideExt = hideExt;
module.exports.addExt = addExt;
module.exports.isRelative = isRelative;
module.exports.isAbsolute = isAbsolute;
module.exports.isLocal = isLocal;
module.exports.resolve = resolve;
module.exports.pathFromCwd = pathFromCwd;
module.exports.throwError = throwError;
module.exports.extend = extend;
module.exports.colors = colors;
module.exports.debug = debug;
module.exports.wrapModule = wrapModule;
<|endoftext|>