<commit_before>// Copyright (c) IPython Development Team.
// Distributed under the terms of the Modified BSD License.

define(function(require){
    "use strict";

    var ActionHandler = function (env) {
        this.env = env || {};
        Object.seal(this);
    };

    /**
     *  A bunch of predefined `Simple Actions` used by IPython.
     *  `Simple Actions` have the following keys:
     *  help (optional): a short string the describe the action.
     *      will be used in various context, like as menu name, tool tips on buttons,
     *      and short description in help menu.
     *  help_index (optional): a string used to sort action in help menu.
     *  icon (optional): a short string that represent the icon that have to be used with this
     *  action. this should mainly correspond to a Font_awesome class.
     *  handler : a function which is called when the action is activated. It will receive at first parameter
     *      a dictionary containing various handle to element of the notebook.
     *
     *  action need to be registered with a **name** that can be use to refer to this action.
     *
     *
     *  if `help` is not provided it will be derived by replacing any dash by space
     *  in the **name** of the action. It is advised to provide a prefix to action name to
     *  avoid conflict the prefix should be all lowercase and end with a dot `.`
     *  in the absence of a prefix the behavior of the action is undefined.
     *
     *  All action provided by IPython are prefixed with `ipython.`.
     *
     *  One can register extra actions or replace an existing action with another one is possible
     *  but is considered undefined behavior.
     *
     **/
    var _actions = {
        'run-select-next': {
            icon: 'fa-play',
            help    : 'run cell, select below',
            help_index : 'ba',
            handler : function (env) {
                env.notebook.execute_cell_and_select_below();
            }
        },
        'execute-in-place':{
            help    : 'run cell',
            help_index : 'bb',
            handler : function (env) {
                env.notebook.execute_cell();
            }
        },
        'execute-and-insert-after':{
            help    : 'run cell, insert below',
            help_index : 'bc',
            handler : function (env) {
                env.notebook.execute_cell_and_insert_below();
            }
        },
        'go-to-command-mode': {
            help    : 'command mode',
            help_index : 'aa',
            handler : function (env) {
                env.notebook.command_mode();
            }
        },
        'split-cell-at-cursor': {
            help    : 'split cell',
            help_index : 'ea',
            handler : function (env) {
                env.notebook.split_cell();
            }
        },
        'enter-edit-mode' : {
            help_index : 'aa',
            handler : function (env) {
                env.notebook.edit_mode();
            }
        },
        'select-previous-cell' : {
            help_index : 'da',
            handler : function (env) {
                var index = env.notebook.get_selected_index();
                if (index !== 0 && index !== null) {
                    env.notebook.select_prev();
                    env.notebook.focus_cell();
                }
            }
        },
        'select-next-cell' : {
            help_index : 'db',
            handler : function (env) {
                var index = env.notebook.get_selected_index();
                if (index !== (env.notebook.ncells()-1) && index !== null) {
                    env.notebook.select_next();
                    env.notebook.focus_cell();
                }
            }
        },
        'cut-selected-cell' : {
            icon: 'fa-cut',
            help_index : 'ee',
            handler : function (env) {
                var index = env.notebook.get_selected_index();
                env.notebook.cut_cell();
                env.notebook.select(index);
                env.notebook.focus_cell();
            }
        },
        'copy-selected-cell' : {
            icon: 'fa-copy',
            help_index : 'ef',
            handler : function (env) {
                env.notebook.copy_cell();
                env.notebook.focus_cell();
            }
        },
        'paste-cell-before' : {
            help_index : 'eg',
            handler : function (env) {
                env.notebook.paste_cell_above();
            }
        },
        'paste-cell-after' : {
            icon: 'fa-paste',
            help_index : 'eh',
            handler : function (env) {
                env.notebook.paste_cell_below();
            }
        },
        'insert-cell-before' : {
            help_index : 'ec',
            handler : function (env) {
                env.notebook.insert_cell_above();
                env.notebook.select_prev();
                env.notebook.focus_cell();
            }
        },
        'insert-cell-after' : {
            icon : 'fa-plus',
            help_index : 'ed',
            handler : function (env) {
                env.notebook.insert_cell_below();
                env.notebook.select_next();
                env.notebook.focus_cell();
            }
        },
        'change-selected-cell-to-code-cell' : {
            help    : 'to code',
            help_index : 'ca',
            handler : function (env) {
                env.notebook.to_code();
            }
        },
        'change-selected-cell-to-markdown-cell' : {
            help    : 'to markdown',
            help_index : 'cb',
            handler : function (env) {
                env.notebook.to_markdown();
            }
        },
        'change-selected-cell-to-raw-cell' : {
            help    : 'to raw',
            help_index : 'cc',
            handler : function (env) {
                env.notebook.to_raw();
            }
        },
        'change-selected-cell-to-heading-1' : {
            help    : 'to heading 1',
            help_index : 'cd',
            handler : function (env) {
                env.notebook.to_heading(undefined, 1);
            }
        },
        'change-selected-cell-to-heading-2' : {
            help    : 'to heading 2',
            help_index : 'ce',
            handler : function (env) {
                env.notebook.to_heading(undefined, 2);
            }
        },
        'change-selected-cell-to-heading-3' : {
            help    : 'to heading 3',
            help_index : 'cf',
            handler : function (env) {
                env.notebook.to_heading(undefined, 3);
            }
        },
        'change-selected-cell-to-heading-4' : {
            help    : 'to heading 4',
            help_index : 'cg',
            handler : function (env) {
                env.notebook.to_heading(undefined, 4);
            }
        },
        'change-selected-cell-to-heading-5' : {
            help    : 'to heading 5',
            help_index : 'ch',
            handler : function (env) {
                env.notebook.to_heading(undefined, 5);
            }
        },
        'change-selected-cell-to-heading-6' : {
            help    : 'to heading 6',
            help_index : 'ci',
            handler : function (env) {
                env.notebook.to_heading(undefined, 6);
            }
        },
        'toggle-output-visibility-selected-cell' : {
            help    : 'toggle output',
            help_index : 'gb',
            handler : function (env) {
                env.notebook.toggle_output();
            }
        },
        'toggle-output-scrolling-selected-cell' : {
            help    : 'toggle output scrolling',
            help_index : 'gc',
            handler : function (env) {
                env.notebook.toggle_output_scroll();
            }
        },
        'move-selected-cell-down' : {
            icon: 'fa-arrow-down',
            help_index : 'eb',
            handler : function (env) {
                env.notebook.move_cell_down();
            }
        },
        'move-selected-cell-up' : {
            icon: 'fa-arrow-up',
            help_index : 'ea',
            handler : function (env) {
                env.notebook.move_cell_up();
            }
        },
        'toggle-line-number-selected-cell' : {
            help    : 'toggle line numbers',
            help_index : 'ga',
            handler : function (env) {
                env.notebook.cell_toggle_line_numbers();
            }
        },
        'show-keyboard-shortcut-help-dialog' : {
            help_index : 'ge',
            handler : function (env) {
                env.quick_help.show_keyboard_shortcuts();
            }
        },
        'delete-cell': {
            help_index : 'ej',
            handler : function (env) {
                env.notebook.delete_cell();
            }
        },
        'interrupt-kernel':{
            icon: 'fa-stop',
            help_index : 'ha',
            handler : function (env) {
                env.notebook.kernel.interrupt();
                env.notebook.focus_cell();
            }
        },
        'restart-kernel':{
            icon: 'fa-repeat',
            help_index : 'hb',
            handler : function (env) {
                env.notebook.restart_kernel();
                env.notebook.focus_cell();
            }
        },
        'undo-last-cell-deletion' : {
            help_index : 'ei',
            handler : function (env) {
                env.notebook.undelete_cell();
            }
        },
        'merge-selected-cell-with-cell-after' : {
            help    : 'merge cell below',
            help_index : 'ek',
            handler : function (env) {
                env.notebook.merge_cell_below();
            }
        },
        'close-pager' : {
            help_index : 'gd',
            handler : function (env) {
                env.pager.collapse();
            }
        }

    };

    /**
     * A bunch of `Advance actions` for IPython.
     * Cf `Simple Action` plus the following properties.
     *
     * handler: first argument of the handler is the event that triggerd the action
     *      (typically keypress). The handler is responsible for any modification of the
     *      event and event propagation.
     *      Is also responsible for returning false if the event have to be further ignored,
     *      true, to tell keyboard manager that it ignored the event.
     *
     *      the second parameter of the handler is the environemnt passed to Simple Actions
     *
     **/
    var custom_ignore = {
        'ignore':{
            handler : function () {
                return true;
            }
        },
        'move-cursor-up-or-previous-cell':{
            handler : function (env, event) {
                var index = env.notebook.get_selected_index();
                var cell = env.notebook.get_cell(index);
                var cm = env.notebook.get_selected_cell().code_mirror;
                var cur = cm.getCursor();
                if (cell && cell.at_top() && index !== 0 && cur.ch === 0) {
                    if(event){
                        event.preventDefault();
                    }
                    env.notebook.command_mode();
                    env.notebook.select_prev();
                    env.notebook.edit_mode();
                    cm = env.notebook.get_selected_cell().code_mirror;
                    cm.setCursor(cm.lastLine(), 0);
                }
                return false;
            }
        },
        'move-cursor-down-or-next-cell':{
            handler : function (env, event) {
                var index = env.notebook.get_selected_index();
                var cell = env.notebook.get_cell(index);
                if (cell.at_bottom() && index !== (env.notebook.ncells()-1)) {
                    if(event){
                        event.preventDefault();
                    }
                    env.notebook.command_mode();
                    env.notebook.select_next();
                    env.notebook.edit_mode();
                    var cm = env.notebook.get_selected_cell().code_mirror;
                    cm.setCursor(0, 0);
                }
                return false;
            }
        },
        'scroll-down': {
            handler: function(env, event) {
                if(event){
                    event.preventDefault();
                }
                return env.notebook.scroll_manager.scroll(1);
            },
        },
        'scroll-up': {
            handler: function(env, event) {
                if(event){
                    event.preventDefault();
                }
                return env.notebook.scroll_manager.scroll(-1);
            },
        },
        'save-notebook':{
            help: "Save and Checkpoint",
            help_index : 'fb',
            icon: 'fa-save',
            handler : function (env, event) {
                env.notebook.save_checkpoint();
                if(event){
                    event.preventDefault();
                }
                return false;
            }
        },
    };

    // private stuff that prepend `.ipython` to actions names
    // and uniformize/fill in missing pieces in of an action.
    var _prepare_handler = function(registry, subkey, source){
        registry['ipython.'+subkey] = {};
        registry['ipython.'+subkey].help = source[subkey].help||subkey.replace(/-/g,' ');
        registry['ipython.'+subkey].help_index = source[subkey].help_index;
        registry['ipython.'+subkey].icon = source[subkey].icon;
        return source[subkey].handler;
    };

    // Will actually generate/register all the IPython actions
    var fun = function(){
        var final_actions = {};
        var k;
        for(k in _actions){
            if(_actions.hasOwnProperty(k)){
                // Js closure are function level not block level need to wrap in a IIFE
                // and append ipython to event name these things do intercept event so are wrapped
                // in a function that return false.
                var handler = _prepare_handler(final_actions, k, _actions);
                (function(key, handler){
                    final_actions['ipython.'+key].handler = function(env, event){
                        handler(env);
                        if(event){
                            event.preventDefault();
                        }
                        return false;
                    };
                })(k, handler);
            }
        }

        for(k in custom_ignore){
            // Js closure are function level not block level need to wrap in a IIFE
            // same as above, but decide for themselves wether or not they intercept events.
            if(custom_ignore.hasOwnProperty(k)){
                var handler = _prepare_handler(final_actions, k, custom_ignore);
                (function(key, handler){
                    final_actions['ipython.'+key].handler = function(env, event){
                        return handler(env, event);
                    };
                })(k, handler);
            }
        }

        return final_actions;
    };
    ActionHandler.prototype._actions = fun();

    /**
     *  extend the environment variable that will be pass to handlers
     **/
    ActionHandler.prototype.extend_env = function(env){
        for(var k in env){
            this.env[k] = env[k];
        }
    };

    ActionHandler.prototype.register = function(action, name, prefix){
        /**
         * Register an `action` with an optional name and prefix.
         *
         * if name and prefix are not given they will be determined automatically.
         * if action if just a `function` it will be wrapped in an anonymous action.
         *
         * @return the full name to access this action .
         **/
        action = this.normalise(action);
        if( !name ){
            name = 'autogenerated-'+String(action.handler);
        }
        prefix = prefix || 'auto';
        var full_name = prefix+'.'+name;
        this._actions[full_name] = action;
        return full_name;

    };

    ActionHandler.prototype.normalise = function(data){
        /**
         * given an `action` or `function`, return a normalised `action`
         * by setting all known attributes and removing unknown attributes;
         **/
        if(typeof(data) === 'function'){
            data = {handler:data};
        }
        if(typeof(data.handler) !== 'function'){
            throw('unknown datatype, cannot register');
        }
        var _data = data;
        data = {};
        data.handler = _data.handler;
        data.help = _data.help || '';
        data.icon = _data.icon || '';
        data.help_index = _data.help_index || '';
        return data;
    };

    ActionHandler.prototype.get_name = function(name_or_data){
        /**
         * given an `action` or `name` of a action, return the name attached to this action.
         * if given the name of and corresponding actions does not exist in registry, return `null`.
         **/

        if(typeof(name_or_data) === 'string'){
            if(this.exists(name_or_data)){
                return name_or_data;
            } else {
                return null;
            }
        } else {
            return this.register(name_or_data);
        }
    };

    ActionHandler.prototype.get = function(name){
        return this._actions[name];
    };

    ActionHandler.prototype.call = function(name, event, env){
        return this._actions[name].handler(env|| this.env, event);
    };

    ActionHandler.prototype.exists = function(name){
        return (typeof(this._actions[name]) !== 'undefined');
    };

    return {init:ActionHandler};

});
<commit_msg>Update actions.js<commit_after>// Copyright (c) IPython Development Team.
// Distributed under the terms of the Modified BSD License.

define(function(require){
    "use strict";

    var ActionHandler = function (env) {
        this.env = env || {};
        Object.seal(this);
    };

    /**
     *  A bunch of predefined `Simple Actions` used by IPython.
     *  `Simple Actions` have the following keys:
     *  help (optional): a short string the describe the action.
     *      will be used in various context, like as menu name, tool tips on buttons,
     *      and short description in help menu.
     *  help_index (optional): a string used to sort action in help menu.
     *  icon (optional): a short string that represent the icon that have to be used with this
     *  action. this should mainly correspond to a Font_awesome class.
     *  handler : a function which is called when the action is activated. It will receive at first parameter
     *      a dictionary containing various handle to element of the notebook.
     *
     *  action need to be registered with a **name** that can be use to refer to this action.
     *
     *
     *  if `help` is not provided it will be derived by replacing any dash by space
     *  in the **name** of the action. It is advised to provide a prefix to action name to
     *  avoid conflict the prefix should be all lowercase and end with a dot `.`
     *  in the absence of a prefix the behavior of the action is undefined.
     *
     *  All action provided by IPython are prefixed with `ipython.`.
     *
     *  One can register extra actions or replace an existing action with another one is possible
     *  but is considered undefined behavior.
     *
     **/
    var _actions = {
        'run-select-next': {
            icon: 'fa-play',
            help    : 'run cell, select below',
            help_index : 'ba',
            handler : function (env) {
                env.notebook.execute_cell_and_select_below();
            }
        },
        'execute-in-place':{
            help    : 'run cell',
            help_index : 'bb',
            handler : function (env) {
                env.notebook.execute_cell();
            }
        },
        'execute-and-insert-after':{
            help    : 'run cell, insert below',
            help_index : 'bc',
            handler : function (env) {
                env.notebook.execute_cell_and_insert_below();
            }
        },
        'go-to-command-mode': {
            help    : 'command mode',
            help_index : 'aa',
            handler : function (env) {
                env.notebook.command_mode();
            }
        },
        'split-cell-at-cursor': {
            help    : 'split cell',
            help_index : 'ea',
            handler : function (env) {
                env.notebook.split_cell();
            }
        },
        'enter-edit-mode' : {
            help_index : 'aa',
            handler : function (env) {
                env.notebook.edit_mode();
            }
        },
        'select-previous-cell' : {
            help_index : 'da',
            handler : function (env) {
                var index = env.notebook.get_selected_index();
                if (index !== 0 && index !== null) {
                    env.notebook.select_prev();
                    env.notebook.focus_cell();
                }
            }
        },
        'select-next-cell' : {
            help_index : 'db',
            handler : function (env) {
                var index = env.notebook.get_selected_index();
                if (index !== (env.notebook.ncells()-1) && index !== null) {
                    env.notebook.select_next();
                    env.notebook.focus_cell();
                }
            }
        },
        'cut-selected-cell' : {
            icon: 'fa-cut',
            help_index : 'ee',
            handler : function (env) {
                var index = env.notebook.get_selected_index();
                env.notebook.cut_cell();
                env.notebook.select(index);
                env.notebook.focus_cell();
            }
        },
        'copy-selected-cell' : {
            icon: 'fa-copy',
            help_index : 'ef',
            handler : function (env) {
                env.notebook.copy_cell();
                env.notebook.focus_cell();
            }
        },
        'paste-cell-before' : {
            help: 'paste cell above',
            help_index : 'eg',
            handler : function (env) {
                env.notebook.paste_cell_above();
            }
        },
        'paste-cell-after' : {
            help: 'paste cell below',
            icon: 'fa-paste',
            help_index : 'eh',
            handler : function (env) {
                env.notebook.paste_cell_below();
            }
        },
        'insert-cell-before' : {
            help: 'insert cell above',
            help_index : 'ec',
            handler : function (env) {
                env.notebook.insert_cell_above();
                env.notebook.select_prev();
                env.notebook.focus_cell();
            }
        },
        'insert-cell-after' : {
            help: 'insert cell below',
            icon : 'fa-plus',
            help_index : 'ed',
            handler : function (env) {
                env.notebook.insert_cell_below();
                env.notebook.select_next();
                env.notebook.focus_cell();
            }
        },
        'change-selected-cell-to-code-cell' : {
            help    : 'to code',
            help_index : 'ca',
            handler : function (env) {
                env.notebook.to_code();
            }
        },
        'change-selected-cell-to-markdown-cell' : {
            help    : 'to markdown',
            help_index : 'cb',
            handler : function (env) {
                env.notebook.to_markdown();
            }
        },
        'change-selected-cell-to-raw-cell' : {
            help    : 'to raw',
            help_index : 'cc',
            handler : function (env) {
                env.notebook.to_raw();
            }
        },
        'change-selected-cell-to-heading-1' : {
            help    : 'to heading 1',
            help_index : 'cd',
            handler : function (env) {
                env.notebook.to_heading(undefined, 1);
            }
        },
        'change-selected-cell-to-heading-2' : {
            help    : 'to heading 2',
            help_index : 'ce',
            handler : function (env) {
                env.notebook.to_heading(undefined, 2);
            }
        },
        'change-selected-cell-to-heading-3' : {
            help    : 'to heading 3',
            help_index : 'cf',
            handler : function (env) {
                env.notebook.to_heading(undefined, 3);
            }
        },
        'change-selected-cell-to-heading-4' : {
            help    : 'to heading 4',
            help_index : 'cg',
            handler : function (env) {
                env.notebook.to_heading(undefined, 4);
            }
        },
        'change-selected-cell-to-heading-5' : {
            help    : 'to heading 5',
            help_index : 'ch',
            handler : function (env) {
                env.notebook.to_heading(undefined, 5);
            }
        },
        'change-selected-cell-to-heading-6' : {
            help    : 'to heading 6',
            help_index : 'ci',
            handler : function (env) {
                env.notebook.to_heading(undefined, 6);
            }
        },
        'toggle-output-visibility-selected-cell' : {
            help    : 'toggle output',
            help_index : 'gb',
            handler : function (env) {
                env.notebook.toggle_output();
            }
        },
        'toggle-output-scrolling-selected-cell' : {
            help    : 'toggle output scrolling',
            help_index : 'gc',
            handler : function (env) {
                env.notebook.toggle_output_scroll();
            }
        },
        'move-selected-cell-down' : {
            icon: 'fa-arrow-down',
            help_index : 'eb',
            handler : function (env) {
                env.notebook.move_cell_down();
            }
        },
        'move-selected-cell-up' : {
            icon: 'fa-arrow-up',
            help_index : 'ea',
            handler : function (env) {
                env.notebook.move_cell_up();
            }
        },
        'toggle-line-number-selected-cell' : {
            help    : 'toggle line numbers',
            help_index : 'ga',
            handler : function (env) {
                env.notebook.cell_toggle_line_numbers();
            }
        },
        'show-keyboard-shortcut-help-dialog' : {
            help_index : 'ge',
            handler : function (env) {
                env.quick_help.show_keyboard_shortcuts();
            }
        },
        'delete-cell': {
            help_index : 'ej',
            handler : function (env) {
                env.notebook.delete_cell();
            }
        },
        'interrupt-kernel':{
            icon: 'fa-stop',
            help_index : 'ha',
            handler : function (env) {
                env.notebook.kernel.interrupt();
                env.notebook.focus_cell();
            }
        },
        'restart-kernel':{
            icon: 'fa-repeat',
            help_index : 'hb',
            handler : function (env) {
                env.notebook.restart_kernel();
                env.notebook.focus_cell();
            }
        },
        'undo-last-cell-deletion' : {
            help_index : 'ei',
            handler : function (env) {
                env.notebook.undelete_cell();
            }
        },
        'merge-selected-cell-with-cell-after' : {
            help    : 'merge cell below',
            help_index : 'ek',
            handler : function (env) {
                env.notebook.merge_cell_below();
            }
        },
        'close-pager' : {
            help_index : 'gd',
            handler : function (env) {
                env.pager.collapse();
            }
        }

    };

    /**
     * A bunch of `Advance actions` for IPython.
     * Cf `Simple Action` plus the following properties.
     *
     * handler: first argument of the handler is the event that triggerd the action
     *      (typically keypress). The handler is responsible for any modification of the
     *      event and event propagation.
     *      Is also responsible for returning false if the event have to be further ignored,
     *      true, to tell keyboard manager that it ignored the event.
     *
     *      the second parameter of the handler is the environemnt passed to Simple Actions
     *
     **/
    var custom_ignore = {
        'ignore':{
            handler : function () {
                return true;
            }
        },
        'move-cursor-up-or-previous-cell':{
            handler : function (env, event) {
                var index = env.notebook.get_selected_index();
                var cell = env.notebook.get_cell(index);
                var cm = env.notebook.get_selected_cell().code_mirror;
                var cur = cm.getCursor();
                if (cell && cell.at_top() && index !== 0 && cur.ch === 0) {
                    if(event){
                        event.preventDefault();
                    }
                    env.notebook.command_mode();
                    env.notebook.select_prev();
                    env.notebook.edit_mode();
                    cm = env.notebook.get_selected_cell().code_mirror;
                    cm.setCursor(cm.lastLine(), 0);
                }
                return false;
            }
        },
        'move-cursor-down-or-next-cell':{
            handler : function (env, event) {
                var index = env.notebook.get_selected_index();
                var cell = env.notebook.get_cell(index);
                if (cell.at_bottom() && index !== (env.notebook.ncells()-1)) {
                    if(event){
                        event.preventDefault();
                    }
                    env.notebook.command_mode();
                    env.notebook.select_next();
                    env.notebook.edit_mode();
                    var cm = env.notebook.get_selected_cell().code_mirror;
                    cm.setCursor(0, 0);
                }
                return false;
            }
        },
        'scroll-down': {
            handler: function(env, event) {
                if(event){
                    event.preventDefault();
                }
                return env.notebook.scroll_manager.scroll(1);
            },
        },
        'scroll-up': {
            handler: function(env, event) {
                if(event){
                    event.preventDefault();
                }
                return env.notebook.scroll_manager.scroll(-1);
            },
        },
        'save-notebook':{
            help: "Save and Checkpoint",
            help_index : 'fb',
            icon: 'fa-save',
            handler : function (env, event) {
                env.notebook.save_checkpoint();
                if(event){
                    event.preventDefault();
                }
                return false;
            }
        },
    };

    // private stuff that prepend `.ipython` to actions names
    // and uniformize/fill in missing pieces in of an action.
    var _prepare_handler = function(registry, subkey, source){
        registry['ipython.'+subkey] = {};
        registry['ipython.'+subkey].help = source[subkey].help||subkey.replace(/-/g,' ');
        registry['ipython.'+subkey].help_index = source[subkey].help_index;
        registry['ipython.'+subkey].icon = source[subkey].icon;
        return source[subkey].handler;
    };

    // Will actually generate/register all the IPython actions
    var fun = function(){
        var final_actions = {};
        var k;
        for(k in _actions){
            if(_actions.hasOwnProperty(k)){
                // Js closure are function level not block level need to wrap in a IIFE
                // and append ipython to event name these things do intercept event so are wrapped
                // in a function that return false.
                var handler = _prepare_handler(final_actions, k, _actions);
                (function(key, handler){
                    final_actions['ipython.'+key].handler = function(env, event){
                        handler(env);
                        if(event){
                            event.preventDefault();
                        }
                        return false;
                    };
                })(k, handler);
            }
        }

        for(k in custom_ignore){
            // Js closure are function level not block level need to wrap in a IIFE
            // same as above, but decide for themselves wether or not they intercept events.
            if(custom_ignore.hasOwnProperty(k)){
                var handler = _prepare_handler(final_actions, k, custom_ignore);
                (function(key, handler){
                    final_actions['ipython.'+key].handler = function(env, event){
                        return handler(env, event);
                    };
                })(k, handler);
            }
        }

        return final_actions;
    };
    ActionHandler.prototype._actions = fun();

    /**
     *  extend the environment variable that will be pass to handlers
     **/
    ActionHandler.prototype.extend_env = function(env){
        for(var k in env){
            this.env[k] = env[k];
        }
    };

    ActionHandler.prototype.register = function(action, name, prefix){
        /**
         * Register an `action` with an optional name and prefix.
         *
         * if name and prefix are not given they will be determined automatically.
         * if action if just a `function` it will be wrapped in an anonymous action.
         *
         * @return the full name to access this action .
         **/
        action = this.normalise(action);
        if( !name ){
            name = 'autogenerated-'+String(action.handler);
        }
        prefix = prefix || 'auto';
        var full_name = prefix+'.'+name;
        this._actions[full_name] = action;
        return full_name;

    };

    ActionHandler.prototype.normalise = function(data){
        /**
         * given an `action` or `function`, return a normalised `action`
         * by setting all known attributes and removing unknown attributes;
         **/
        if(typeof(data) === 'function'){
            data = {handler:data};
        }
        if(typeof(data.handler) !== 'function'){
            throw('unknown datatype, cannot register');
        }
        var _data = data;
        data = {};
        data.handler = _data.handler;
        data.help = _data.help || '';
        data.icon = _data.icon || '';
        data.help_index = _data.help_index || '';
        return data;
    };

    ActionHandler.prototype.get_name = function(name_or_data){
        /**
         * given an `action` or `name` of a action, return the name attached to this action.
         * if given the name of and corresponding actions does not exist in registry, return `null`.
         **/

        if(typeof(name_or_data) === 'string'){
            if(this.exists(name_or_data)){
                return name_or_data;
            } else {
                return null;
            }
        } else {
            return this.register(name_or_data);
        }
    };

    ActionHandler.prototype.get = function(name){
        return this._actions[name];
    };

    ActionHandler.prototype.call = function(name, event, env){
        return this._actions[name].handler(env|| this.env, event);
    };

    ActionHandler.prototype.exists = function(name){
        return (typeof(this._actions[name]) !== 'undefined');
    };

    return {init:ActionHandler};

});
<|endoftext|>


<commit_before>/**
 * Patterns bumper - `bumper' handling for elements
 *
 * Copyright 2013 Florian Friesdorf
 * Copyright 2012 Humberto Sermeno
 * Copyright 2013 Simplon B.V. - Wichert Akkerman
 */
define([
    "jquery",
    "../core/parser",
    "../registry",
    "../utils"
], function($, Parser, registry, utils) {
    var parser = new Parser("bumper");

    parser.add_argument("margin", 0);
    parser.add_argument("selector");
    parser.add_argument("bump-add", "bumped");
    parser.add_argument("bump-remove");
    parser.add_argument("unbump-add");
    parser.add_argument("unbump-remove", "bumped");

    var _ = {
        name: "bumper",
        trigger: ".pat-bumper",

        init: function($el, opts) {
            $el.each(function() {
                var $trigger = $(this),
                    options = parser.parse($trigger, opts);
                $trigger.data("pat-bumper:config", options);
            });

            $(window).on("scroll.bumper", function() {
                _._testBump($el, _._getViewport());
            });

            _._testBump($el, _._getViewport());
            return $el;
        },

        /**
         * Calculates the bounding box for the current viewport
         */
        _getViewport: function() {
            var $win = $(window), view = {
                top: $win.scrollTop(),
                left: $win.scrollLeft()
            };

            view.right = view.left + $win.width();
            view.bottom = view.top + $win.height();
            return view;
        },

        /**
         * Calculates the bounding box for a given element, taking margins
         * into consideration
         *
         * @param $elem The element
         */
        _getElementBox: function($elem) {
            var box = $elem.offset();

            box.top -= parseFloat($elem.css("marginTop").replace(/auto/, 0));
            box.left -= parseFloat($elem.css("marginLeft").replace(/auto/, 0));
            box.right = box.left + $elem.outerWidth(true);
            box.bottom = box.top + $elem.outerHeight(true);

            return box;
        },

        /**
         * Determines whether an element should be bumped
         *
         * @param $el  The element to look for
         * @param box The bounding box in which the element will be bumped
         */
        _testBump: function($el, box) {
            // initialize the elements
            $el.each(function() {
                var $this = $(this),
                    options = $this.data("pat-bumper:config"),
                    $target = options.selector ? $(options.selector) : $this,
                    already_bumped = !!$this.data("pat-bumper:bumped"),
                    must_bump = false,
                    bumped = false,
                    element_box = $this.data("pat-bumper:elementbox");

                // get current ElementBox while not bumped, otherwise used
                // saved state before bumping
                if (!element_box) {
                    element_box = _._getElementBox($this);
                    element_box.threshold = {
                        top:    element_box.top - options.margin,
                        bottom: element_box.bottom + options.margin,
                        left:   element_box.left - options.margin,
                        right:  element_box.right + options.margin
                    };
                    element_box.margin = options.margin;
                    $this.data("pat-bumper:elementbox", element_box);
                }

                if (box.top > element_box.threshold.top) {
                    $target.addClass("bumped-top").removeClass("bumped-bottom");
                    must_bump = true;
                } else if (box.bottom < element_box.threshold.bottom) {
                    $target.addClass("bumped-bottom").removeClass("bumped-top");
                    must_bump = true;
                } else
                    $target.removeClass("bumped-top bumped-bottom");

                if (box.left > element_box.threshold.left) {
                    $target.addClass("bumped-left").removeClass("bumped-right");
                    must_bump = true;
                } else if (box.right < element_box.threshold.right) {
                    $target.addClass("bumped-right").removeClass("bumped-left");
                    must_bump = true;
                } else
                    $target.removeClass("bumped-left bumped-right");

                $this.data("pat-bumper:bumped", must_bump);
                if (!already_bumped && must_bump) {
                    $target.addClass("bumped");
                    if (options.bump.add)
                        $target.addClass(options.bump.add);
                    if (options.bump.remove)
                        utils.removeWildcardClass($target, options.bump.remove);
                } else if (already_bumped && !must_bump) {
                    $target.removeClass("bumped");
                    if (options.unbump.add)
                        $target.addClass(options.unbump.add);
                    if (options.unbump.remove)
                        utils.removeWildcardClass($target, options.unbump.remove);
                }
            });
        }
    };
    registry.register(_);
    return _;
});

// vim: sw=4 expandtab
<commit_msg>Fix bumper jslint error.<commit_after>/**
 * Patterns bumper - `bumper' handling for elements
 *
 * Copyright 2013 Florian Friesdorf
 * Copyright 2012 Humberto Sermeno
 * Copyright 2013 Simplon B.V. - Wichert Akkerman
 */
define([
    "jquery",
    "../core/parser",
    "../registry",
    "../utils"
], function($, Parser, registry, utils) {
    var parser = new Parser("bumper");

    parser.add_argument("margin", 0);
    parser.add_argument("selector");
    parser.add_argument("bump-add", "bumped");
    parser.add_argument("bump-remove");
    parser.add_argument("unbump-add");
    parser.add_argument("unbump-remove", "bumped");

    var _ = {
        name: "bumper",
        trigger: ".pat-bumper",

        init: function($el, opts) {
            $el.each(function() {
                var $trigger = $(this),
                    options = parser.parse($trigger, opts);
                $trigger.data("pat-bumper:config", options);
            });

            $(window).on("scroll.bumper", function() {
                _._testBump($el, _._getViewport());
            });

            _._testBump($el, _._getViewport());
            return $el;
        },

        /**
         * Calculates the bounding box for the current viewport
         */
        _getViewport: function() {
            var $win = $(window), view = {
                top: $win.scrollTop(),
                left: $win.scrollLeft()
            };

            view.right = view.left + $win.width();
            view.bottom = view.top + $win.height();
            return view;
        },

        /**
         * Calculates the bounding box for a given element, taking margins
         * into consideration
         *
         * @param $elem The element
         */
        _getElementBox: function($elem) {
            var box = $elem.offset();

            box.top -= parseFloat($elem.css("marginTop").replace(/auto/, 0));
            box.left -= parseFloat($elem.css("marginLeft").replace(/auto/, 0));
            box.right = box.left + $elem.outerWidth(true);
            box.bottom = box.top + $elem.outerHeight(true);

            return box;
        },

        /**
         * Determines whether an element should be bumped
         *
         * @param $el  The element to look for
         * @param box The bounding box in which the element will be bumped
         */
        _testBump: function($el, box) {
            // initialize the elements
            $el.each(function() {
                var $this = $(this),
                    options = $this.data("pat-bumper:config"),
                    $target = options.selector ? $(options.selector) : $this,
                    already_bumped = !!$this.data("pat-bumper:bumped"),
                    must_bump = false,
                    element_box = $this.data("pat-bumper:elementbox");

                // get current ElementBox while not bumped, otherwise used
                // saved state before bumping
                if (!element_box) {
                    element_box = _._getElementBox($this);
                    element_box.threshold = {
                        top:    element_box.top - options.margin,
                        bottom: element_box.bottom + options.margin,
                        left:   element_box.left - options.margin,
                        right:  element_box.right + options.margin
                    };
                    element_box.margin = options.margin;
                    $this.data("pat-bumper:elementbox", element_box);
                }

                if (box.top > element_box.threshold.top) {
                    $target.addClass("bumped-top").removeClass("bumped-bottom");
                    must_bump = true;
                } else if (box.bottom < element_box.threshold.bottom) {
                    $target.addClass("bumped-bottom").removeClass("bumped-top");
                    must_bump = true;
                } else
                    $target.removeClass("bumped-top bumped-bottom");

                if (box.left > element_box.threshold.left) {
                    $target.addClass("bumped-left").removeClass("bumped-right");
                    must_bump = true;
                } else if (box.right < element_box.threshold.right) {
                    $target.addClass("bumped-right").removeClass("bumped-left");
                    must_bump = true;
                } else
                    $target.removeClass("bumped-left bumped-right");

                $this.data("pat-bumper:bumped", must_bump);
                if (!already_bumped && must_bump) {
                    $target.addClass("bumped");
                    if (options.bump.add)
                        $target.addClass(options.bump.add);
                    if (options.bump.remove)
                        utils.removeWildcardClass($target, options.bump.remove);
                } else if (already_bumped && !must_bump) {
                    $target.removeClass("bumped");
                    if (options.unbump.add)
                        $target.addClass(options.unbump.add);
                    if (options.unbump.remove)
                        utils.removeWildcardClass($target, options.unbump.remove);
                }
            });
        }
    };
    registry.register(_);
    return _;
});

// vim: sw=4 expandtab
<|endoftext|>


<commit_before>/**
 * JBoss, Home of Professional Open Source Copyright 2016, Red Hat, Inc. and/or its affiliates, and individual
 * contributors by the
 *
 * @authors tag. See the copyright.txt in the distribution for a full listing of individual contributors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by
 * applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */

function invoke_ajax(url, id) {
    $.ajax({
        url : url,
        cache : false,
        success : function(data) {
            $('#' + id).text(data);
        },
        error : function(error) {
            $('#' + id).text('Error getting value from service ' + url);
        }
    });
}

function browser_query() {
    var services = [
            {
                'url' : 'http://hola-helloworld-msa.rhel-cdk.10.3.2.2.xip.io/rest/hola',
                'id' : 'hola-service'
            },
            {
                'url' : 'http://bonjour-helloworld-msa.rhel-cdk.10.3.2.2.xip.io/bonjour',
                'id' : 'bonjour-service'
            },
            {
                'url' : 'http://hello-helloworld-msa.rhel-cdk.10.3.2.2.xip.io/rest/hello',
                'id' : 'hello-service'
            },
            {
                'url' : 'http://aloha-helloworld-msa.rhel-cdk.10.3.2.2.xip.io/aloha',
                'id' : 'aloha-service'
            },
            {
                'url' : 'http://ola-helloworld-msa.rhel-cdk.10.3.2.2.xip.io/ola',
                'id' : 'ola-service'
            }, ];

    for (var x = 0; x < services.length; x++) {
        invoke_ajax(services[x].url, services[x].id)
    }
};

$(document).ready(function() {
    browser_query();
});
<commit_msg>Print (Loading...) before invoking the services<commit_after>/**
 * JBoss, Home of Professional Open Source Copyright 2016, Red Hat, Inc. and/or its affiliates, and individual
 * contributors by the
 *
 * @authors tag. See the copyright.txt in the distribution for a full listing of individual contributors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by
 * applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */
var services = [ {
    'url' : 'http://hola-helloworld-msa.rhel-cdk.10.3.2.2.xip.io/rest/hola',
    'id' : 'hola-service'
}, {
    'url' : 'http://bonjour-helloworld-msa.rhel-cdk.10.3.2.2.xip.io/bonjour',
    'id' : 'bonjour-service'
}, {
    'url' : 'http://hello-helloworld-msa.rhel-cdk.10.3.2.2.xip.io/rest/hello',
    'id' : 'hello-service'
}, {
    'url' : 'http://aloha-helloworld-msa.rhel-cdk.10.3.2.2.xip.io/aloha',
    'id' : 'aloha-service'
}, {
    'url' : 'http://ola-helloworld-msa.rhel-cdk.10.3.2.2.xip.io/ola',
    'id' : 'ola-service'
}, ];

function invoke_ajax(url, id) {
    $.ajax({
        url : url,
        cache : false,
        success : function(data) {
            $('#' + id).text(data);
        },
        error : function(error) {
            $('#' + id).text('Error getting value from service ' + url);
        }
    });
}

function browser_query() {
    //Clear all responses
    for (var x = 0; x < services.length; x++) {
        $('#' + services[x].id).text("Loading...");
    }
    //Make the invocation
    for (var x = 0; x < services.length; x++) {
        invoke_ajax(services[x].url, services[x].id)
    }
};

$(document).ready(function() {
    browser_query();
});
<|endoftext|>


<commit_before>$("a[name*='pdf']").each(function() {
    //Do your work
})
<commit_msg>add test code<commit_after>$("a[name*='pdf']").each(function() {
  $(this).append( "
Test
" );
});
<|endoftext|>


<commit_before>const Property = require('./company_property')

class Company {
  constructor (client) {
    this.client = client
    this.properties = new Property(this.client)
  }

  getById (id, cb) {
    return this.client._request({
      method: 'GET',
      path: '/companies/v2/companies/' + id
    }, cb)
  }

  get (options, cb) {
    if (typeof options === 'function') {
      cb = options
      options = {}
    }

    return this.client._request({
      method: 'GET',
      path: '/companies/v2/companies/paged',
      qs: options,
      qsStringifyOptions: {
        arrayFormat: 'repeat'
      }
    }, cb)
  }

  getAll (options, cb) {
    return this.get(options, cb)
  }

  getRecentlyCreated (options, cb) {
    if (typeof options === 'function') {
      cb = options
      options = {}
    }

    return this.client._request({
      method: 'GET',
      path: '/companies/v2/companies/recent/created',
      qs: options
    }, cb)
  }

  getRecentlyModified (options, cb) {
    if (typeof options === 'function') {
      cb = options
      options = {}
    }

    return this.client._request({
      method: 'GET',
      path: '/companies/v2/companies/recent/modified',
      qs: options
    }, cb)
  }

  getByDomain (domain, cb) {
    return this.client._request({
      method: 'GET',
      path: '/companies/v2/companies/domain/' + domain
    }, cb)
  }

  create (data, cb) {
    return this.client._request({
      method: 'POST',
      path: '/companies/v2/companies/',
      body: data
    }, cb)
  }

  delete (id, cb) {
    return this.client._request({
      method: 'DELETE',
      path: '/companies/v2/companies/' + id
    }, cb)
  }

  update (id, data, cb) {
    return this.client._request({
      method: 'PUT',
      path: '/companies/v2/companies/' + id,
      body: data
    }, cb)
  }

  updateBatch (data, cb) {
    return this.client._request({
      method: 'POST',
      path: '/companies/v1/batch-async/update',
      body: data
    }, cb)
  }

  addContactToCompany (data, cb) {
    if (!data || !data.companyId || !data.contactVid) {
      return cb(new Error('companyId and contactVid params must be provided'))
    }

    return this.client._request({
      method: 'PUT',
      path: '/companies/v2/companies/' + data.companyId + '/contacts/' + data.contactVid
    }, cb)
  }

  getContactIds (id, options, cb) {
    if (typeof options === 'function') {
      cb = options
      options = {}
    }

    return this.client._request({
      method: 'GET',
      path: '/companies/v2/companies/' + id + '/vids',
      qs: options
    }, cb)
  }

  getContacts (id, options, cb) {
    if (typeof options === 'function') {
      cb = options
      options = {}
    }

    return this.client._request({
      method: 'GET',
      path: '/companies/v2/companies/' + id + '/contacts',
      qs: options
    }, cb)
  }
}

module.exports = Company
<commit_msg>companies.getByDomain<commit_after>const Property = require('./company_property')

class Company {
  constructor (client) {
    this.client = client
    this.properties = new Property(this.client)
  }

  getById (id, cb) {
    return this.client._request({
      method: 'GET',
      path: '/companies/v2/companies/' + id
    }, cb)
  }

  get (options, cb) {
    if (typeof options === 'function') {
      cb = options
      options = {}
    }

    return this.client._request({
      method: 'GET',
      path: '/companies/v2/companies/paged',
      qs: options,
      qsStringifyOptions: {
        arrayFormat: 'repeat'
      }
    }, cb)
  }

  getAll (options, cb) {
    return this.get(options, cb)
  }

  getRecentlyCreated (options, cb) {
    if (typeof options === 'function') {
      cb = options
      options = {}
    }

    return this.client._request({
      method: 'GET',
      path: '/companies/v2/companies/recent/created',
      qs: options
    }, cb)
  }

  getRecentlyModified (options, cb) {
    if (typeof options === 'function') {
      cb = options
      options = {}
    }

    return this.client._request({
      method: 'GET',
      path: '/companies/v2/companies/recent/modified',
      qs: options
    }, cb)
  }

  getByDomain (domain, data, cb) {
    // return this.client._request({
    //   method: 'GET',
    //   path: '/companies/v2/companies/domain/' + domain
    // }, cb)
    return this.client._request({
      method: 'POST',
      path: '/companies/v2/domains/' + domain + '/companies',
      body: data
    }, cb)
  }

  create (data, cb) {
    return this.client._request({
      method: 'POST',
      path: '/companies/v2/companies/',
      body: data
    }, cb)
  }

  delete (id, cb) {
    return this.client._request({
      method: 'DELETE',
      path: '/companies/v2/companies/' + id
    }, cb)
  }

  update (id, data, cb) {
    return this.client._request({
      method: 'PUT',
      path: '/companies/v2/companies/' + id,
      body: data
    }, cb)
  }

  updateBatch (data, cb) {
    return this.client._request({
      method: 'POST',
      path: '/companies/v1/batch-async/update',
      body: data
    }, cb)
  }

  addContactToCompany (data, cb) {
    if (!data || !data.companyId || !data.contactVid) {
      return cb(new Error('companyId and contactVid params must be provided'))
    }

    return this.client._request({
      method: 'PUT',
      path: '/companies/v2/companies/' + data.companyId + '/contacts/' + data.contactVid
    }, cb)
  }

  getContactIds (id, options, cb) {
    if (typeof options === 'function') {
      cb = options
      options = {}
    }

    return this.client._request({
      method: 'GET',
      path: '/companies/v2/companies/' + id + '/vids',
      qs: options
    }, cb)
  }

  getContacts (id, options, cb) {
    if (typeof options === 'function') {
      cb = options
      options = {}
    }

    return this.client._request({
      method: 'GET',
      path: '/companies/v2/companies/' + id + '/contacts',
      qs: options
    }, cb)
  }
}

module.exports = Company
<|endoftext|>


<commit_before>const { Script } = require('@beemo/core');
const fs = require('fs-extra');
const path = require('path');
const execa = require('execa');

module.exports = class BuildPackagesScript extends Script {
  parse() {
    return {
      defaults: {
        mainPackage: 'core',
      },
      string: ['mainPackage'],
    };
  }

  run(options, tool) {
    const { root } = tool.options;

    return fs
      .readdir(path.join(root, 'packages'))
      .then(files => {
        const promises = [];

        files.forEach(fileName => {
          const packagePath = path.join(root, 'packages', fileName);
          const srcPath = path.join(packagePath, 'src');

          if (!fs.statSync(packagePath).isDirectory() || !fs.existsSync(srcPath)) {
            return;
          }

          promises.push(this.build(packagePath), this.build(packagePath, true));
        });

        return Promise.all(promises);
      })
      .then(responses => {
        if (options.mainPackage) {
          fs.copySync(
            path.join(root, 'README.md'),
            path.join(root, 'packages', options.mainPackage, 'README.md'),
          );
        }

        tool.log(responses.map(response => response.stdout).join('\n'));

        return responses;
      });
  }

  build(packageRoot, isModule = false) {
    return execa('beemo', [
      'babel',
      path.join(packageRoot, 'src'),
      '--out-dir',
      path.join(packageRoot, isModule ? 'esm' : 'lib'),
      '--copy-files',
      isModule ? '--esm' : '--cjs',
      '--silent',
    ]);
  }
};
<commit_msg>Script fixes.<commit_after>const { Script } = require('@beemo/core');
const fs = require('fs-extra');
const path = require('path');
const execa = require('execa');

module.exports = class BuildPackagesScript extends Script {
  parse() {
    return {
      default: {
        'main-package': 'core',
      },
      string: ['main-package'],
    };
  }

  run(options, tool) {
    const { root } = tool.options;

    return fs
      .readdir(path.join(root, 'packages'))
      .then(files => {
        const promises = [];

        files.forEach(fileName => {
          const packagePath = path.join(root, 'packages', fileName);
          const srcPath = path.join(packagePath, 'src');

          if (!fs.statSync(packagePath).isDirectory() || !fs.existsSync(srcPath)) {
            return;
          }

          promises.push(this.build(packagePath), this.build(packagePath, true));
        });

        return Promise.all(promises);
      })
      .then(responses => {
        if (options.mainPackage) {
          fs.copySync(
            path.join(root, 'README.md'),
            path.join(root, 'packages', options.mainPackage, 'README.md'),
          );
        }

        tool.log(responses.map(response => response.stdout.trim()).join('\n'));

        return responses;
      });
  }

  build(packageRoot, isModule = false) {
    return execa('beemo', [
      'babel',
      path.join(packageRoot, 'src'),
      '--out-dir',
      path.join(packageRoot, isModule ? 'esm' : 'lib'),
      '--copy-files',
      isModule ? '--esm' : '--cjs',
      '--silent',
    ]);
  }
};
<|endoftext|>


<commit_before>var fs = require('fs');
var url = require('url');
var EventEmitter = require('events').EventEmitter;
var util = require('util');

var request = require('request');
var async = require('async');

var MailHandler = require('mailHandler').MailHandler;

function loadRules(rulesPath, callback) {
  console.error('rulesPath', rulesPath);
  var myRules;

  if (rulesPath.indexOf('http') !== 0) {
    // load from file
    try {
      myRules = require(rulesPath);
      console.error('myRules', myRules);
    } catch(err) {
      return callback(err);
    }
    console.log('loaded myRules fs');
    return setImmediate(callback.bind(this, null, myRules));
  }

  try {
    myRules = url.parse(rulesPath);
  } catch(err) {
    return callback(err);
  }

  console.log('loading myRules from url', rulesPath);
  request.get(rulesPath, function(err, resp, body) {
    if (err) return callback(err);
    if (resp.statusCode !== 200) return callback(resp.statusCode);
    try {
      fs.writeFileSync('/tmp/myRules.js', body);
      myRules = require('/tmp/myRules.js');
    } catch(err) {
      return callback(err);
    }
    console.log('loaded myRules from url', rulesPath);
    return setImmediate(callback.bind(this, null, myRules));
  });
}

function MailWorker(Q, rulesPath) {
  this.rulesPath = rulesPath;
  this.Q = Q;
}

util.inherits(MailWorker, EventEmitter);

MailWorker.prototype.start = function() {
  var Q = this.Q;
  var self = this;
  console.error('this.rulesPath', this.rulesPath);
  loadRules(this.rulesPath, function(err, rules) {
    if (err) return self.emit('error', err);
    console.error('rules', rules);
    var handler = new MailHandler(rules);
    async.forever(function(cb) {
      Q.dequeue(function(err, msg) {
        if (err) return cb(err);
        handler.processMessage(msg, cb);
      });
    }, function(err) {
      throw err;
    });
  });
};

module.exports = MailWorker;
<commit_msg>Write rules to local directory for modules.<commit_after>var fs = require('fs');
var url = require('url');
var EventEmitter = require('events').EventEmitter;
var util = require('util');

var request = require('request');
var async = require('async');

var MailHandler = require('mailHandler').MailHandler;

function loadRules(rulesPath, callback) {
  console.error('rulesPath', rulesPath);
  var myRules;

  if (rulesPath.indexOf('http') !== 0) {
    // load from file
    try {
      myRules = require(rulesPath);
      console.error('myRules', myRules);
    } catch(err) {
      return callback(err);
    }
    console.log('loaded myRules fs');
    return setImmediate(callback.bind(this, null, myRules));
  }

  try {
    myRules = url.parse(rulesPath);
  } catch(err) {
    return callback(err);
  }

  console.log('loading myRules from url', rulesPath);
  request.get(rulesPath, function(err, resp, body) {
    if (err) return callback(err);
    if (resp.statusCode !== 200) return callback(resp.statusCode);
    try {
      fs.writeFileSync('./myRules.js', body);
      myRules = require('./myRules.js');
    } catch(err) {
      return callback(err);
    }
    console.log('loaded myRules from url', rulesPath);
    return setImmediate(callback.bind(this, null, myRules));
  });
}

function MailWorker(Q, rulesPath) {
  this.rulesPath = rulesPath;
  this.Q = Q;
}

util.inherits(MailWorker, EventEmitter);

MailWorker.prototype.start = function() {
  var Q = this.Q;
  var self = this;
  console.error('this.rulesPath', this.rulesPath);
  loadRules(this.rulesPath, function(err, rules) {
    if (err) return self.emit('error', err);
    console.error('rules', rules);
    var handler = new MailHandler(rules);
    async.forever(function(cb) {
      Q.dequeue(function(err, msg) {
        if (err) return cb(err);
        handler.processMessage(msg, cb);
      });
    }, function(err) {
      throw err;
    });
  });
};

module.exports = MailWorker;
<|endoftext|>


<commit_before>//
// exports
//
var regions = module.exports = {};

//
// required packages
//
var fs = require('fs');
var winston = require('winston');
var request = require('request');
var forecasts = require('./forecasts.js');

// region constants
regions.DATA_REQUEST_TIMEOUT_SECONDS = 15;
regions.DATA_MULTIPOLYGON_TYPE = 'MultiPolygon';
regions.NAC_DATA_URL = 'https://api.avalanche.org/v2/public/products/map-layer';
regions.CANADIAN_METADATA_URL = 'https://api.avalanche.ca/forecasts/en/metadata';
regions.CANADIAN_DATA_URL = 'https://api.avalanche.ca/forecasts/en/areas';
regions.CANADIAN_API_KEY = process.env.CANADIAN_API_KEY;
regions.REGIONS_GEN_INTERVAL_SECONDS = 60*60*24;

// filepaths
regions.REGIONS_PATH = __dirname + '/public/v1/regions.json';
regions.REGIONS_DATA_TEMP_PATH = __dirname + '/public/v1/regions_TEMP.json';

regions.regenerateRegions = async function() {
    winston.info('regenerateRegions: initiated');
    var NACData = getNACData();
    var CanadianMetadata = await getCanadianMetadata()
    .catch(function(reject) {
        winston.warn('regenerateRegions: UNEXPECTED error with Canadian metadata: ' + reject);
        return false;
    });
    var CanadianData = getCanadianData(CanadianMetadata);
    Promise.all([NACData, CanadianData]).then(data => {
        var combinedRegions = data[0].concat(data[1]);
        writeRegionsFile(JSON.stringify(combinedRegions, null, 4));
        forecasts.aggregateForecasts(combinedRegions);
    })
    .catch(function(reject) {
        winston.warn('regenerateRegions: UNEXPECTED error with source data: ' + reject);
        return false;
    });
};

function writeRegionsFile(regionData) {
    winston.info('writeRegionsFile: intiated');
    fs.writeFile(regions.REGIONS_DATA_TEMP_PATH, regionData, 'utf8',
        function() {
            fs.rename(regions.REGIONS_DATA_TEMP_PATH, regions.REGIONS_PATH,
                function() {
                    winston.info('writeRegionsFile: regions file updated; path: ' + regions.REGIONS_PATH);
                }
            );
        }
    );
}

function getCanadianMetadata() {
    return new Promise((resolve, reject) => {
        winston.info('getCanadianMetadata: initiated');
        var dataURL = regions.CANADIAN_METADATA_URL

        var requestOptions = {
            url:dataURL,
            headers:{'x-api-key':regions.CANADIAN_API_KEY},
            jar:false,
            timeout:(regions.DATA_REQUEST_TIMEOUT_SECONDS * 1000)
        };

        request(requestOptions,
            function(error, response, body) {
                if (!error) {
                    winston.info('getCanadianMetadata: successful canadian metadata response; ' +  dataURL);
                    try {
                        var metadata = processCanadianMetadata(body);
                        resolve(metadata);
                    } catch (e) {
                        reject('getCanadianMetadata: parse failure of canadian metadata; exception: ' + e);
                    }
                } else {
                    reject('getCanadianMetadata: failed canadian metadata response; dataURL: ' + dataURL + '; response status code: ' + (response ? response.statusCode : '[no response]') + '; error: ' + error);
                }
            }
        );
    });
}

async function getCanadianData(metadata) {
    return new Promise((resolve, reject) => {
        winston.info('getCanadianData: initiated');;
        var dataURL = regions.CANADIAN_DATA_URL;

        var requestOptions = {
            url:dataURL,
            headers:{'x-api-key':regions.CANADIAN_API_KEY},
            jar:false,
            timeout:(regions.DATA_REQUEST_TIMEOUT_SECONDS * 1000)
        };

        request(requestOptions,
            function(error, response, body) {
                if (!error) {
                    winston.info('getCanadianData: successful canadian region data response: ' +  dataURL);
                    try {
                        var fullRegionsData = processCanadianRegions(metadata, body, 3);
                        resolve(fullRegionsData);
                    } catch (e) {
                        reject('getCanadianData: parse failure of canadian region data; exception: ' + e);
                    }
                } else {
                    reject('getCanadianData: failed canadian region data response; dataURL: ' + dataURL + '; response status code: ' + (response ? response.statusCode : '[no response]') + '; error: ' + error);
                }
            }
        );
    });
}

function getNACData() {
    return new Promise((resolve, reject) => {
        winston.info('getNACData: initiated');
        dataURL = regions.NAC_DATA_URL;

        var requestOptions = {
            url:dataURL,
            headers:{'User-Agent':'avalancheforecasts.com'},
            jar:false,
            timeout:(regions.DATA_REQUEST_TIMEOUT_SECONDS * 1000)
        };
        request(requestOptions,
            function(error, response, body) {
                if (!error) {
                    winston.info('getNACData: successful nac region data response: ' +  dataURL);
                    try {
                        var fullRegionsData = processNACRegions(body, 3);
                        resolve(fullRegionsData);
                    } catch (e) {
                        reject('getNACData: parse failure of nac region data; exception: ' + e);
                    }
                } else {
                    reject('getNACData: failed nac region data response; dataURL: ' + dataURL + '; response status code: ' + (response ? response.statusCode : '[no response]') + '; error: ' + error);
                }
            }
        );
    });
}

function processCanadianMetadata(input) {
    winston.info('processCanadianMetadata: initiated');
    var data = JSON.parse(input);
    var metadata = {};
    for (var i = 0; i < data.length; i++) {
        var caId = data[i].area.id;
        metadata[caId] = {};
        metadata[caId].regionId = 'ca_' + data[i].product.slug;
        metadata[caId].centerId = data[i].owner.value;
        metadata[caId].displayName = data[i].area.name;
        metadata[caId].URL = data[i].url;
    }
    return metadata;
}

function processCanadianRegions(metadata, input, digits) {
    winston.info('processCanadianRegions: initiated');
    var data = JSON.parse(input);
    var regionData = data.features;
    var formattedRegions = [];
    for (var i = 0; i < regionData.length; i++) {
        var caId = regionData[i].properties.id;
        formattedRegions[i] = {};
        formattedRegions[i].regionId = metadata[caId].regionId;
        formattedRegions[i].displayName = metadata[caId].displayName;
        formattedRegions[i].URL = metadata[caId].URL;
        formattedRegions[i].centerId = metadata[caId].centerId;
        formattedRegions[i].points = [];
        for (var j = 0; j < regionData[i].geometry.coordinates[0].length; j++) {
            var lon = regionData[i].geometry.coordinates[0][j][0] = parseFloat(regionData[i].geometry.coordinates[0][j][0]).toFixed(digits);
            var lat = regionData[i].geometry.coordinates[0][j][1] = parseFloat(regionData[i].geometry.coordinates[0][j][1]).toFixed(digits);
            formattedRegions[i].points[j] = {'lat': lat, 'lon': lon};
        }
    }
    return formattedRegions;
}

function processNACRegions(input, digits) {
    winston.info('processNACRegions: initiated');
    var data = JSON.parse(input);
    var regionData = data.features;
    var formattedRegions = [];
    var row = 0;
    var polygons = 1;
    for (var i = 0; i < regionData.length; i++) {
        polygons = regionData[i].geometry.coordinates.length;
        for (var j = 0; j < polygons; j++) {
            formattedRegions[row] = populateNewRegion(regionData[i], j);
            if (regionData[i].geometry.type === regions.DATA_MULTIPOLYGON_TYPE) {
                for (var k = 0; k < regionData[i].geometry.coordinates[j][0].length; k++) {
                    formattedRegions[row].points[k] = getLatLong(regionData[i].geometry.coordinates[j][0][k], digits);
                }
            } else {
                for (var k = 0; k < regionData[i].geometry.coordinates[j].length; k++) {
                    formattedRegions[row].points[k] = getLatLong(regionData[i].geometry.coordinates[j][k], digits);
                }
            }
            row++;
        }
    }
    return formattedRegions;
}

function populateNewRegion(regionData, regionCount) {
    var region = {};
    region.regionId = 'nac_' + regionData.id;
    if (regionData.geometry.coordinates.length > 1) {
        region.regionId += '_' + (regionCount+1);
    }
    region.displayName = regionData.properties.name;
    region.URL = regionData.properties.link;
    region.centerId = regionData.properties.center_id.toLowerCase();
    region.points = [];
    return region;
}

function getLatLong(coordinate, digits) {
    var lon = coordinate[0] = parseFloat(coordinate[0]).toFixed(digits);
    var lat = coordinate[1] = parseFloat(coordinate[1]).toFixed(digits);
    return {'lat': lat, 'lon': lon};
}<commit_msg>Refactoring processCanadianRegions<commit_after>//
// exports
//
var regions = module.exports = {};

//
// required packages
//
var fs = require('fs');
var winston = require('winston');
var request = require('request');
var forecasts = require('./forecasts.js');

// region constants
regions.DATA_REQUEST_TIMEOUT_SECONDS = 15;
regions.DATA_MULTIPOLYGON_TYPE = 'MultiPolygon';
regions.NAC_DATA_URL = 'https://api.avalanche.org/v2/public/products/map-layer';
regions.CANADIAN_METADATA_URL = 'https://api.avalanche.ca/forecasts/en/metadata';
regions.CANADIAN_DATA_URL = 'https://api.avalanche.ca/forecasts/en/areas';
regions.CANADIAN_API_KEY = process.env.CANADIAN_API_KEY;
regions.REGIONS_GEN_INTERVAL_SECONDS = 60*60*24;

// filepaths
regions.REGIONS_PATH = __dirname + '/public/v1/regions.json';
regions.REGIONS_DATA_TEMP_PATH = __dirname + '/public/v1/regions_TEMP.json';

regions.regenerateRegions = async function() {
    winston.info('regenerateRegions: initiated');
    var NACData = getNACData();
    var CanadianMetadata = await getCanadianMetadata()
    .catch(function(reject) {
        winston.warn('regenerateRegions: UNEXPECTED error with Canadian metadata: ' + reject);
        return false;
    });
    var CanadianData = getCanadianData(CanadianMetadata);
    Promise.all([NACData, CanadianData]).then(data => {
        var combinedRegions = data[0].concat(data[1]);
        writeRegionsFile(JSON.stringify(combinedRegions, null, 4));
        forecasts.aggregateForecasts(combinedRegions);
    })
    .catch(function(reject) {
        winston.warn('regenerateRegions: UNEXPECTED error with source data: ' + reject);
        return false;
    });
};

function writeRegionsFile(regionData) {
    winston.info('writeRegionsFile: intiated');
    fs.writeFile(regions.REGIONS_DATA_TEMP_PATH, regionData, 'utf8',
        function() {
            fs.rename(regions.REGIONS_DATA_TEMP_PATH, regions.REGIONS_PATH,
                function() {
                    winston.info('writeRegionsFile: regions file updated; path: ' + regions.REGIONS_PATH);
                }
            );
        }
    );
}

function getCanadianMetadata() {
    return new Promise((resolve, reject) => {
        winston.info('getCanadianMetadata: initiated');
        var dataURL = regions.CANADIAN_METADATA_URL

        var requestOptions = {
            url:dataURL,
            headers:{'x-api-key':regions.CANADIAN_API_KEY},
            jar:false,
            timeout:(regions.DATA_REQUEST_TIMEOUT_SECONDS * 1000)
        };

        request(requestOptions,
            function(error, response, body) {
                if (!error) {
                    winston.info('getCanadianMetadata: successful canadian metadata response; ' +  dataURL);
                    try {
                        var metadata = processCanadianMetadata(body);
                        resolve(metadata);
                    } catch (e) {
                        reject('getCanadianMetadata: parse failure of canadian metadata; exception: ' + e);
                    }
                } else {
                    reject('getCanadianMetadata: failed canadian metadata response; dataURL: ' + dataURL + '; response status code: ' + (response ? response.statusCode : '[no response]') + '; error: ' + error);
                }
            }
        );
    });
}

async function getCanadianData(metadata) {
    return new Promise((resolve, reject) => {
        winston.info('getCanadianData: initiated');;
        var dataURL = regions.CANADIAN_DATA_URL;

        var requestOptions = {
            url:dataURL,
            headers:{'x-api-key':regions.CANADIAN_API_KEY},
            jar:false,
            timeout:(regions.DATA_REQUEST_TIMEOUT_SECONDS * 1000)
        };

        request(requestOptions,
            function(error, response, body) {
                if (!error) {
                    winston.info('getCanadianData: successful canadian region data response: ' +  dataURL);
                    try {
                        var fullRegionsData = processCanadianRegions(metadata, body, 3);
                        resolve(fullRegionsData);
                    } catch (e) {
                        reject('getCanadianData: parse failure of canadian region data; exception: ' + e);
                    }
                } else {
                    reject('getCanadianData: failed canadian region data response; dataURL: ' + dataURL + '; response status code: ' + (response ? response.statusCode : '[no response]') + '; error: ' + error);
                }
            }
        );
    });
}

function getNACData() {
    return new Promise((resolve, reject) => {
        winston.info('getNACData: initiated');
        dataURL = regions.NAC_DATA_URL;

        var requestOptions = {
            url:dataURL,
            headers:{'User-Agent':'avalancheforecasts.com'},
            jar:false,
            timeout:(regions.DATA_REQUEST_TIMEOUT_SECONDS * 1000)
        };
        request(requestOptions,
            function(error, response, body) {
                if (!error) {
                    winston.info('getNACData: successful nac region data response: ' +  dataURL);
                    try {
                        var fullRegionsData = processNACRegions(body, 3);
                        resolve(fullRegionsData);
                    } catch (e) {
                        reject('getNACData: parse failure of nac region data; exception: ' + e);
                    }
                } else {
                    reject('getNACData: failed nac region data response; dataURL: ' + dataURL + '; response status code: ' + (response ? response.statusCode : '[no response]') + '; error: ' + error);
                }
            }
        );
    });
}

function processCanadianMetadata(input) {
    winston.info('processCanadianMetadata: initiated');
    var data = JSON.parse(input);
    var metadata = {};
    for (var i = 0; i < data.length; i++) {
        var caId = data[i].area.id;
        metadata[caId] = {};
        metadata[caId].regionId = 'ca_' + data[i].product.slug;
        metadata[caId].displayName = data[i].area.name;
        metadata[caId].URL = data[i].url;
        metadata[caId].centerId = data[i].owner.value;
    }
    return metadata;
}

function processCanadianRegions(metadata, input, digits) {
    winston.info('processCanadianRegions: initiated');
    var data = JSON.parse(input);
    var regionData = data.features;
    var formattedRegions = [];
    for (var i = 0; i < regionData.length; i++) {
        var caId = regionData[i].properties.id;
        formattedRegions[i] = populateNewRegion(metadata[caId], 1, false);
        for (var j = 0; j < regionData[i].geometry.coordinates[0].length; j++) {
          formattedRegions[i].points[j] = getLatLong(regionData[i].geometry.coordinates[0][j], digits);
        }
    }
    return formattedRegions;
}

function processNACRegions(input, digits) {
    winston.info('processNACRegions: initiated');
    var data = JSON.parse(input);
    var regionData = data.features;
    var formattedRegions = [];
    var row = 0;
    var polygons = 1;
    for (var i = 0; i < regionData.length; i++) {
        polygons = regionData[i].geometry.coordinates.length;
        for (var j = 0; j < polygons; j++) {
            formattedRegions[row] = populateNewRegion(regionData[i], j, true);
            if (regionData[i].geometry.type === regions.DATA_MULTIPOLYGON_TYPE) {
                for (var k = 0; k < regionData[i].geometry.coordinates[j][0].length; k++) {
                    formattedRegions[row].points[k] = getLatLong(regionData[i].geometry.coordinates[j][0][k], digits);
                }
            } else {
                for (var k = 0; k < regionData[i].geometry.coordinates[j].length; k++) {
                    formattedRegions[row].points[k] = getLatLong(regionData[i].geometry.coordinates[j][k], digits);
                }
            }
            row++;
        }
    }
    return formattedRegions;
}

function populateNewRegion(regionData, regionCount, isNacData) {
    var region = {};
    if (isNacData == true) {
        region.regionId = 'nac_' + regionData.id;
        if (regionData.geometry.coordinates.length > 1) {
            region.regionId += '_' + (regionCount+1);
        }
        region.displayName = regionData.properties.name;
        region.URL = regionData.properties.link;
        region.centerId = regionData.properties.center_id.toLowerCase();
    } else {
        region = regionData;
    }
    region.points = [];
    return region;
}

function getLatLong(coordinate, digits) {
    var lon = coordinate[0] = parseFloat(coordinate[0]).toFixed(digits);
    var lat = coordinate[1] = parseFloat(coordinate[1]).toFixed(digits);
    return {'lat': lat, 'lon': lon};
}<|endoftext|>


<commit_before>

var initSignaturePopup = function() {

    $('a.signature_popup').fancybox({
        autoSize: true,
        autoCenter: true,
        height: 'auto',
        width: 'auto',
    });
};

var triggerSignaturePopup = function() {
    $('a.signature_popup').click();
}

var initRechercheFiltre = function() {

$('form#filtres_historique select#campagne').change(function(){
    $('form#filtres_historique').submit();
});

$('form#filtres_historique select#etablissement').change(function(){
    $('form#filtres_historique').submit();
});

}

$(document).ready(function()
{
    initSignaturePopup();
    initRechercheFiltre();
});

<commit_msg>ajout d'une fonction pour l'affichage dans les soussignés<commit_after>

var initSignaturePopup = function() {

    $('a.signature_popup').fancybox({
        autoSize: true,
        autoCenter: true,
        height: 'auto',
        width: 'auto',
    });
};

var triggerSignaturePopup = function() {
    $('a.signature_popup').click();
}

var initRechercheFiltre = function() {

    $('form#filtres_historique select#campagne').change(function() {
        $('form#filtres_historique').submit();
    });

    $('form#filtres_historique select#etablissement').change(function() {
        $('form#filtres_historique').submit();
    });

}

var initTeledeclarationCourtierSoussigne = function() {

    $("#teledeclaration_courtier_interlocuteur_commercial_show").change(function() {
        if($(this).is(":checked")){
            $("#teledeclaration_courtier_interlocuteur_commercial").show();
        }else{
            $("#teledeclaration_courtier_interlocuteur_commercial").hide();
        }
    })

}

$(document).ready(function()
{
    initSignaturePopup();
    initRechercheFiltre();
});

<|endoftext|>