<commit_before>(function($){
// Ok, let's do eeet

// This is the basic Node class, which handles UI tree operations for each 'row'
var Node = function(elem) {
    var $elem = $(elem);
    var node_id = $elem.attr('node');
    var parent_id = $elem.attr('parent');
    var level = parseInt($elem.attr('level'));
    var children_num = parseInt($elem.attr('children-num'));
    return {
        elem: elem,
        $elem: $elem,
        node_id: node_id,
        parent_id: parent_id,
        level: level,
        has_children: function() {
            return children_num > 0;
        },
        node_name: function() {
            // Returns the text of the node
            return $elem.find('th a:not(.collapse)').text();
        },
        is_collapsed: function() {
            return $elem.find('a.collapse').hasClass('collapsed');
        },
        children: function() {
            return $('tr[parent=' + node_id + ']');
        },
        collapse: function() {
            // For each children, hide it's childrens and so on...
            $.each(this.children(), function(){
                var node = new Node(this);
                node.collapse();
            }).hide();
            // Swicth class to set the proprt expand/collapse icon
            $elem.find('a.collapse').removeClass('expanded').addClass('collapsed');
        },
        parent_node: function() {
            // Returns a Node object of the parent
            return new Node($('tr[node=' + parent_id + ']', $elem.parent())[0]);
        },
        expand: function() {
            // Display each kid (will display in collapsed state)
            this.children().show();
            // Swicth class to set the proprt expand/collapse icon
            $elem.find('a.collapse').removeClass('collapsed').addClass('expanded');

        },
        toggle: function() {
            if (this.is_collapsed()) {
                this.expand();
            } else {
                this.collapse();
            }
        },
        clone: function() {
            return $elem.clone();
        }
    }
}

$(document).ready(function(){

    // Don't activate drag or collapse if GET filters are set on the page
    if ($('#has-filters').val() === "1") {
        return;
    }

    $body = $('body');

    // Activate all rows for drag & drop
    // then bind mouse down event
    $('td.drag-handler span').addClass('active').bind('mousedown', function(evt) {
        $ghost = $('

');
        $drag_line = $('

');
        $ghost.appendTo($body);
        $drag_line.appendTo($body);

        // Create a clone create the illusion that we're moving the node
        var node = new Node($(this).closest('tr')[0]);
        cloned_node = node.clone();

        $targetRow = null;
        as_child = false;

        // Now make the new clone move with the mouse
        $body.disableSelection().bind('mousemove', function(evt2) {
            $ghost.html(cloned_node).css({  // from FeinCMS :P
                'opacity': .8,
                'position': 'absolute',
                'top': evt2.pageY,
                'left': evt2.pageX-30,
                'width': 600
            });
            // Iterate through all rows and see where am I moving so I can place
            // the drag line accordingly
            rowHeight = node.$elem.height();
            $('tr', node.$elem.parent()).each(function(index, element) {
                $row = $(element);
                rtop = $row.offset().top;
                // The tooltop will display whether I'm droping the element as
                // child or sibling
                $tooltip = $drag_line.find('span');
                $tooltip.css({
                    'left': node.$elem.width() - $tooltip.width(),
                    'height': rowHeight,
                });
                node_top = node.$elem.offset().top;
                // Check if you are dragging over the same node
                if (evt2.pageY >= node_top && evt2.pageY <= node_top + rowHeight) {
                    $targetRow = null;
                    $drag_line.css({
                        'top': rtop,
                        'height': 0,
                        'borderWidth': 0,
                    });
                } else
                // Check if mouse is over this row
                if (evt2.pageY >= rtop && evt2.pageY <= rtop + rowHeight/2) {
                    // The mouse is positioned on the top half of a $row
                    $targetRow = $row;
                    as_child = false;
                    $drag_line.css({
                        'left': node.$elem.offset().left,
                        'width': node.$elem.width(),
                        'top': rtop,
                        'borderWidth': '5px',
                        'height': 0,
                        'opacity': 1
                    });
                    $tooltip.text('As Sibling');
                } else if (evt2.pageY >= rtop + rowHeight/2 && evt2.pageY <= rtop + rowHeight) {
                    // The mouse is positioned on the bottom half of a row
                    $targetRow = $row;
                    as_child = true;
                    $drag_line.css({
                        'top': rtop,
                        'left': node.$elem.offset().left,
                        'height': rowHeight,
                        'opacity': 0.4,
                        'width': node.$elem.width(),
                        'borderWidth': 0,
                    });
                    $tooltip.text('As child');
                }
            });
        }).bind('mouseup', function() {
            if ($targetRow !== null) {
                target_node = new Node($targetRow[0]);
                if (target_node.node_id !== node.node_id) {
                    /*alert('Insert node ' + node.node_name() + ' as child of: '
                    + target_node.parent_node().node_name() + '\n and sibling of: '
                        + target_node.node_name());*/
                    // Call $.ajax so we can handle the error
                    // On Drop, make an XHR call to perform the node move
                    $.ajax({
                        url: window.MOVE_NODE_ENDPOINT,
                        type: 'POST',
                        data: {
                            node_id: node.node_id,
                            parent_id: target_node.parent_id,
                            sibling_id: target_node.node_id,
                            as_child: as_child?1:0
                        },
                        complete: function(req, status) {
                            window.location.reload();
                        },
                        error: function(req, status, error) {
                            // On error (!200) also reload to display
                            // the message
                            window.location.reload();
                        }
                    });
                }
            }
            $ghost.remove();
            $drag_line.remove();
            $body.enableSelection().unbind('mousemove').unbind('mouseup');
        }).bind('keyup', function(kbevt) {
            // Cancel drag on escape
            if (kbevt.keyCode === 27) {
                $ghost.remove();
                $drag_line.remove();
                $body.enableSelection().unbind('mousemove').unbind('mouseup');
            }
        });
    });

    $('a.collapse').click(function(){
        var node = new Node($(this).closest('tr')[0]); // send the DOM node, not jQ
        node.toggle();
        return false;
    });
});
})(django.jQuery);
<commit_msg>Mostrango ABORT tooltip<commit_after>(function($){
// Ok, let's do eeet

// This is the basic Node class, which handles UI tree operations for each 'row'
var Node = function(elem) {
    var $elem = $(elem);
    var node_id = $elem.attr('node');
    var parent_id = $elem.attr('parent');
    var level = parseInt($elem.attr('level'));
    var children_num = parseInt($elem.attr('children-num'));
    return {
        elem: elem,
        $elem: $elem,
        node_id: node_id,
        parent_id: parent_id,
        level: level,
        has_children: function() {
            return children_num > 0;
        },
        node_name: function() {
            // Returns the text of the node
            return $elem.find('th a:not(.collapse)').text();
        },
        is_collapsed: function() {
            return $elem.find('a.collapse').hasClass('collapsed');
        },
        children: function() {
            return $('tr[parent=' + node_id + ']');
        },
        collapse: function() {
            // For each children, hide it's childrens and so on...
            $.each(this.children(), function(){
                var node = new Node(this);
                node.collapse();
            }).hide();
            // Swicth class to set the proprt expand/collapse icon
            $elem.find('a.collapse').removeClass('expanded').addClass('collapsed');
        },
        parent_node: function() {
            // Returns a Node object of the parent
            return new Node($('tr[node=' + parent_id + ']', $elem.parent())[0]);
        },
        expand: function() {
            // Display each kid (will display in collapsed state)
            this.children().show();
            // Swicth class to set the proprt expand/collapse icon
            $elem.find('a.collapse').removeClass('collapsed').addClass('expanded');

        },
        toggle: function() {
            if (this.is_collapsed()) {
                this.expand();
            } else {
                this.collapse();
            }
        },
        clone: function() {
            return $elem.clone();
        }
    }
}

$(document).ready(function(){

    // Don't activate drag or collapse if GET filters are set on the page
    if ($('#has-filters').val() === "1") {
        return;
    }

    $body = $('body');

    // Activate all rows for drag & drop
    // then bind mouse down event
    $('td.drag-handler span').addClass('active').bind('mousedown', function(evt) {
        $ghost = $('

');
        $drag_line = $('

');
        $ghost.appendTo($body);
        $drag_line.appendTo($body);

        // Create a clone create the illusion that we're moving the node
        var node = new Node($(this).closest('tr')[0]);
        cloned_node = node.clone();

        $targetRow = null;
        as_child = false;

        // Now make the new clone move with the mouse
        $body.disableSelection().bind('mousemove', function(evt2) {
            $ghost.html(cloned_node).css({  // from FeinCMS :P
                'opacity': .8,
                'position': 'absolute',
                'top': evt2.pageY,
                'left': evt2.pageX-30,
                'width': 600
            });
            // Iterate through all rows and see where am I moving so I can place
            // the drag line accordingly
            rowHeight = node.$elem.height();
            $('tr', node.$elem.parent()).each(function(index, element) {
                $row = $(element);
                rtop = $row.offset().top;
                // The tooltop will display whether I'm droping the element as
                // child or sibling
                $tooltip = $drag_line.find('span');
                $tooltip.css({
                    'left': node.$elem.width() - $tooltip.width(),
                    'height': rowHeight,
                });
                node_top = node.$elem.offset().top;
                // Check if you are dragging over the same node
                if (evt2.pageY >= node_top && evt2.pageY <= node_top + rowHeight) {
                    $targetRow = null;
                    $tooltip.text('Abort');
                    $drag_line.css({
                        'top': node_top,
                        'height': rowHeight,
                        'borderWidth': 0,
                        'opacity': 0.8,
                        'backgroundColor': '#ECC'
                    });
                } else
                // Check if mouse is over this row
                if (evt2.pageY >= rtop && evt2.pageY <= rtop + rowHeight/2) {
                    // The mouse is positioned on the top half of a $row
                    $targetRow = $row;
                    as_child = false;
                    $drag_line.css({
                        'left': node.$elem.offset().left,
                        'width': node.$elem.width(),
                        'top': rtop,
                        'borderWidth': '5px',
                        'height': 0,
                        'opacity': 1
                    });
                    $tooltip.text('As Sibling');
                } else if (evt2.pageY >= rtop + rowHeight/2 && evt2.pageY <= rtop + rowHeight) {
                    // The mouse is positioned on the bottom half of a row
                    $targetRow = $row;
                    as_child = true;
                    $drag_line.css({
                        'top': rtop,
                        'left': node.$elem.offset().left,
                        'height': rowHeight,
                        'opacity': 0.4,
                        'width': node.$elem.width(),
                        'borderWidth': 0,
                        'backgroundColor': '#A0A'
                    });
                    $tooltip.text('As child');
                }
            });
        }).bind('mouseup', function() {
            if ($targetRow !== null) {
                target_node = new Node($targetRow[0]);
                if (target_node.node_id !== node.node_id) {
                    /*alert('Insert node ' + node.node_name() + ' as child of: '
                    + target_node.parent_node().node_name() + '\n and sibling of: '
                        + target_node.node_name());*/
                    // Call $.ajax so we can handle the error
                    // On Drop, make an XHR call to perform the node move
                    $.ajax({
                        url: window.MOVE_NODE_ENDPOINT,
                        type: 'POST',
                        data: {
                            node_id: node.node_id,
                            parent_id: target_node.parent_id,
                            sibling_id: target_node.node_id,
                            as_child: as_child?1:0
                        },
                        complete: function(req, status) {
                            window.location.reload();
                        },
                        error: function(req, status, error) {
                            // On error (!200) also reload to display
                            // the message
                            window.location.reload();
                        }
                    });
                }
            }
            $ghost.remove();
            $drag_line.remove();
            $body.enableSelection().unbind('mousemove').unbind('mouseup');
        }).bind('keyup', function(kbevt) {
            // Cancel drag on escape
            if (kbevt.keyCode === 27) {
                $ghost.remove();
                $drag_line.remove();
                $body.enableSelection().unbind('mousemove').unbind('mouseup');
            }
        });
    });

    $('a.collapse').click(function(){
        var node = new Node($(this).closest('tr')[0]); // send the DOM node, not jQ
        node.toggle();
        return false;
    });
});
})(django.jQuery);
<|endoftext|>


<commit_before>const util = require('util');
const chalk = require('chalk');
const generator = require('yeoman-generator');
const packagejs = require(__dirname + '/../../package.json');
const semver = require('semver');
const shelljs = require('shelljs');
const BaseGenerator = require('generator-jhipster/generators/generator-base');
// const jhipsterUtils = require('generator-jhipster/generators/util');

const JhipsterGenerator = generator.extend({});
util.inherits(JhipsterGenerator, BaseGenerator);

// Stores JHipster variables
const jhipsterVar = {moduleName: '<%= moduleName %>'};

// Stores JHipster functions
const jhipsterFunc = {};

module.exports = JhipsterGenerator.extend({
    _getConfig() {
        const fromPath = '.yo-rc.json';
        if (shelljs.test('-f', fromPath)) {
            const fileData = this.fs.readJSON(fromPath);
            if (fileData && fileData['generator-jhipster']) {
                return fileData['generator-jhipster'];
            }
        }
        return false;
    },

    initializing: {
        compose() {
            this.entityConfig = this.options.entityConfig;
            this.composeWith('jhipster:modules', {
                jhipsterVar: jhipsterVar,
                jhipsterFunc: jhipsterFunc
            });
        },
        displayLogo() {
            console.log(chalk.white('Running ' + chalk.bold('JHipster <%= moduleName %>') + ' Generator! ' + chalk.yellow('v' + packagejs.version + '\n')));
        },
        validate() {
            // this shouldnt be run directly
            if (!this.entityConfig) {
                this.env.error(chalk.red.bold('ERROR!') + ' This sub generator should be used only from JHipster and cannot be run directly...\n');
            }
        }
    },

    prompting() {
        // don't prompt if data are imported from a file
        if (this.entityConfig.useConfigurationFile == true && this.entityConfig.data && typeof this.entityConfig.data.yourOptionKey !== 'undefined') {
            this.yourOptionKey = this.entityConfig.data.yourOptionKey;
            return;
        }
        const done = this.async();
        const prompts = [
            {
                type: 'confirm',
                name: 'enableOption',
                message: 'Some option here?',
                default: false
            }
        ];

        this.prompt(prompts).then((props) => {
            this.props = props;
            // To access props later use this.props.someOption;

            done();
        });
    },

    writing() {
        updateFiles() {

            this.baseName = jhipsterVar.baseName;
            this.packageName = jhipsterVar.packageName;
            this.angularAppName = jhipsterVar.angularAppName;
            this.frontendBuilder = jhipsterVar.frontendBuilder;

            var webappDir = jhipsterVar.webappDir,
            javaTemplateDir = 'src/main/java/package',
            javaDir = jhipsterVar.javaDir,
            resourceDir = jhipsterVar.resourceDir,
            entityName = this.entityConfig.entityClass;

            // do your stuff here
        },

        writeFiles() {
            // function to use directly template
            this.template = function (source, destination) {
                this.fs.copyTpl(
                    this.templatePath(source),
                    this.destinationPath(destination),
                    this
                );
            };

            this.template('dummy.txt', 'dummy.txt', this, {});
        },

        updateConfig() {
            jhipsterFunc.updateEntityConfig(this.entityConfig.filename, 'yourOptionKey', this.yourOptionKey);
        }
    },

    end() {
        if (this.yourOptionKey){
            console.log('\n' + chalk.bold.green('<%= moduleName %> enabled'));
        }
    }
});
<commit_msg>Update the entity module<commit_after>const util = require('util');
const chalk = require('chalk');
const generator = require('yeoman-generator');
const packagejs = require(__dirname + '/../../package.json');
const semver = require('semver');
const shelljs = require('shelljs');
const BaseGenerator = require('generator-jhipster/generators/generator-base');
const constants = require('generator-jhipster/generators/generator-constants');
// const jhipsterUtils = require('generator-jhipster/generators/util');

const JhipsterGenerator = generator.extend({});
util.inherits(JhipsterGenerator, BaseGenerator);

module.exports = JhipsterGenerator.extend({
    _getConfig() {
        const fromPath = '.yo-rc.json';
        if (shelljs.test('-f', fromPath)) {
            const fileData = this.fs.readJSON(fromPath);
            if (fileData && fileData['generator-jhipster']) {
                return fileData['generator-jhipster'];
            }
        }
        return false;
    },

    initializing: {
        displayLogo() {
            this.log(chalk.white('Running ' + chalk.bold('JHipster <%= moduleName %>') + ' Generator! ' + chalk.yellow('v' + packagejs.version + '\n')));
        },
        validate() {
            // this shouldn't be run directly
            if (!this.entityConfig) {
                this.env.error(chalk.red.bold('ERROR!') + ' This sub generator should be used only from JHipster and cannot be run directly...\n');
            }
        }
    },

    prompting() {
        // don't prompt if data are imported from a file
        if (this.entityConfig.useConfigurationFile == true && this.entityConfig.data && typeof this.entityConfig.data.yourOptionKey !== 'undefined') {
            this.yourOptionKey = this.entityConfig.data.yourOptionKey;
            return;
        }
        const done = this.async();
        const prompts = [
            {
                type: 'confirm',
                name: 'enableOption',
                message: 'Some option here?',
                default: false
            }
        ];

        this.prompt(prompts).then((props) => {
            this.props = props;
            // To access props later use this.props.someOption;

            done();
        });
    },

    writing: {
        updateFiles() {
            // read config from .yo-rc.json
            const config = this._getConfig();

            // read config from .yo-rc.json
            this.baseName = config.baseName;
            this.packageName = config.packageName;
            this.packageFolder = config.packageFolder;
            this.clientFramework = config.clientFramework;
            this.clientPackageManager = config.clientPackageManager;
            this.buildTool = config.buildTool;

            // use function in generator-base.js from generator-jhipster
            this.angularAppName = this.getAngularAppName();

            // use constants from generator-constants.js
            const javaDir = `${constants.SERVER_MAIN_SRC_DIR + this.packageFolder}/`;
            const resourceDir = constants.SERVER_MAIN_RES_DIR;
            const webappDir = constants.CLIENT_MAIN_SRC_DIR;

            const entityName = this.entityConfig.entityClass;

            // do your stuff here
        },

        writeFiles() {
            // function to use directly template
            this.template = function (source, destination) {
                this.fs.copyTpl(
                    this.templatePath(source),
                    this.destinationPath(destination),
                    this
                );
            };

            this.template('dummy.txt', 'dummy.txt', this, {});
        },

        updateConfig() {
            this.updateEntityConfig(this.entityConfig.filename, 'yourOptionKey', this.yourOptionKey);
        }
    },

    end() {
        if (this.yourOptionKey){
            this.log('\n' + chalk.bold.green('<%= moduleName %> enabled'));
        }
    }
});
<|endoftext|>


<commit_before>var local = require('../../../../config/local');
var uploads = require('../../../services/uploads');
var dal = require('./dal');

var status = require('http-status-codes');
var urljoin = require('url-join');
var path = require('path');
var winston = require('winston');

var uploadHandler = uploads.tempUploader.single('importfile');

var buildUrls = function (locs) {
  // Modifies given locations.
  // Convert absolute file paths to URLs.
  // This is most correct to do in handler because it is a REST thing.
  // Absolute filepaths are needed internally more often.
  locs.forEach(function (loc) {
    loc.entries.forEach(function (entry) {
      var rel, url;
      if (entry.filepath !== null) {
        if (entry.filepath.startsWith('/')) {
          rel = path.relative(local.tempUploadDir, entry.filepath);
          url = urljoin(local.tempUploadUrl, rel);
          entry.filepath = url;
        }
      }
    });
  });
};

exports.import = function (req, res, next) {
  // Import locations from KML, KMZ, or GPX file.
  // importfile is required.

  uploadHandler(req, res, function (err) {
    if (err) {
      if (err.code === 'LIMIT_FILE_SIZE') {
        winston.warn('TEMP UPLOAD FILE SIZE reached');
        return res.sendStatus(status.REQUEST_TOO_LONG);
      }
      return next(err);
    }

    if (typeof req.file !== 'object') {
      // No file was given.
      res.status(status.BAD_REQUEST);
      return res.send('no file given');
    }

    var ext = path.extname(req.file.originalname);

    var ext2methodName = {
      '.xml': 'readKML',
      '.kml': 'readKML',
      '.kmz': 'readKMZ',
    };
    var methodName = null;

    if (ext2methodName.hasOwnProperty(ext)) {
      methodName = ext2methodName[ext];
      return dal[methodName](req.file.path, function (errr, result) {
        if (errr) {
          if (errr.message === 'INVALID_KMZ') {
            res.status(status.BAD_REQUEST);
            return res.send('unknown filetype');
          }
          return next(errr);
        }

        if (typeof result.batchId !== 'string') {
          throw new Error('invalid batchId');
        }

        var batchId = result.batchId;

        return res.json({
          batchId: batchId,
        });
      });
    }

    res.status(status.BAD_REQUEST);
    return res.send('unknown filetype');
  });
};

exports.getBatch = function (req, res, next) {

  var batchId = req.params.batchId;

  dal.getBatch(batchId, function (err, locs) {
    if (err) {
      if (err.code === 'ENOENT') {
        return res.sendStatus(status.NOT_FOUND);
      }
      return next(err);
    }

    buildUrls(locs);

    return res.json(locs);
  });
};

exports.getOutcome = function (req, res, next) {
  var batchId = req.params.batchId;
  dal.getOutcome(batchId, function (err, outcome) {
    if (err) {
      return next(err);
    }

    return res.json(outcome);
  });
};

exports.importBatch = function (req, res, next) {
  var batchId = req.params.batchId;
  var indices = req.body.indices;
  var username = req.user.name;

  dal.importBatch({
    batchId: batchId,
    indices: indices,
    username: username,
  }, function (err, batchResult) {
    if (err) {
      return next(err);
    }

    dal.mergeEntries({
      locations: batchResult.skipped,
      username: username,
    }, function (errm, mergeResult) {
      if (errm) {
        return next(errm);
      }

      var outcomeData = {
        batchId: batchId,
        created: batchResult.created,
        skipped: mergeResult.locationsSkipped,
        modified: mergeResult.locationsModified,
      };

      dal.writeBatchOutcome(outcomeData, function (errw) {
        if (errw) {
          return next(errw);
        }

        return res.json(outcomeData);
      });
    });
  });
};
<commit_msg>Remove last winston occurrence<commit_after>var local = require('../../../../config/local');
var uploads = require('../../../services/uploads');
var dal = require('./dal');

var status = require('http-status-codes');
var urljoin = require('url-join');
var path = require('path');

var uploadHandler = uploads.tempUploader.single('importfile');

var buildUrls = function (locs) {
  // Modifies given locations.
  // Convert absolute file paths to URLs.
  // This is most correct to do in handler because it is a REST thing.
  // Absolute filepaths are needed internally more often.
  locs.forEach(function (loc) {
    loc.entries.forEach(function (entry) {
      var rel, url;
      if (entry.filepath !== null) {
        if (entry.filepath.startsWith('/')) {
          rel = path.relative(local.tempUploadDir, entry.filepath);
          url = urljoin(local.tempUploadUrl, rel);
          entry.filepath = url;
        }
      }
    });
  });
};

exports.import = function (req, res, next) {
  // Import locations from KML, KMZ, or GPX file.
  // importfile is required.

  uploadHandler(req, res, function (err) {
    if (err) {
      if (err.code === 'LIMIT_FILE_SIZE') {
        return res.sendStatus(status.REQUEST_TOO_LONG);
      }
      return next(err);
    }

    if (typeof req.file !== 'object') {
      // No file was given.
      res.status(status.BAD_REQUEST);
      return res.send('no file given');
    }

    var ext = path.extname(req.file.originalname);

    var ext2methodName = {
      '.xml': 'readKML',
      '.kml': 'readKML',
      '.kmz': 'readKMZ',
    };
    var methodName = null;

    if (ext2methodName.hasOwnProperty(ext)) {
      methodName = ext2methodName[ext];
      return dal[methodName](req.file.path, function (errr, result) {
        if (errr) {
          if (errr.message === 'INVALID_KMZ') {
            res.status(status.BAD_REQUEST);
            return res.send('unknown filetype');
          }
          return next(errr);
        }

        if (typeof result.batchId !== 'string') {
          throw new Error('invalid batchId');
        }

        var batchId = result.batchId;

        return res.json({
          batchId: batchId,
        });
      });
    }

    res.status(status.BAD_REQUEST);
    return res.send('unknown filetype');
  });
};

exports.getBatch = function (req, res, next) {

  var batchId = req.params.batchId;

  dal.getBatch(batchId, function (err, locs) {
    if (err) {
      if (err.code === 'ENOENT') {
        return res.sendStatus(status.NOT_FOUND);
      }
      return next(err);
    }

    buildUrls(locs);

    return res.json(locs);
  });
};

exports.getOutcome = function (req, res, next) {
  var batchId = req.params.batchId;
  dal.getOutcome(batchId, function (err, outcome) {
    if (err) {
      return next(err);
    }

    return res.json(outcome);
  });
};

exports.importBatch = function (req, res, next) {
  var batchId = req.params.batchId;
  var indices = req.body.indices;
  var username = req.user.name;

  dal.importBatch({
    batchId: batchId,
    indices: indices,
    username: username,
  }, function (err, batchResult) {
    if (err) {
      return next(err);
    }

    dal.mergeEntries({
      locations: batchResult.skipped,
      username: username,
    }, function (errm, mergeResult) {
      if (errm) {
        return next(errm);
      }

      var outcomeData = {
        batchId: batchId,
        created: batchResult.created,
        skipped: mergeResult.locationsSkipped,
        modified: mergeResult.locationsModified,
      };

      dal.writeBatchOutcome(outcomeData, function (errw) {
        if (errw) {
          return next(errw);
        }

        return res.json(outcomeData);
      });
    });
  });
};
<|endoftext|>


<commit_before>import firebase from 'firebase/app';
import 'firebase/auth';
import 'firebase/firestore';
import * as firebaseui from 'firebaseui';
import User from './User';

var firebaseConfig = {
    apiKey: process.env.REACT_APP_API_KEY,
    authDomain:  process.env.REACT_APP_AUTH_DOMAIN,
    databaseURL: process.env.REACT_APP_DATABASE_URL,
    projectId: process.env.REACT_APP_PROJECT_ID,
    storageBucket: process.env.REACT_APP_STORAGE_BUCKET,
    messagingSenderId: process.env.REACT_APP_MESSAGING_SENDER_ID,
    appId: "1:390165048626:web:6e692e8fa9d6c5ea1dbb2b",
    measurementId: "G-JPC7PLV9CF",
  };

class Firebase {
  constructor() {
    firebase.initializeApp(firebaseConfig);
    this.db = firebase.firestore();
    this.auth = firebase.auth();
    this.ui = new firebaseui.auth.AuthUI(this.auth);
    this.uiConfig = {
      signInSuccessUrl: 'index.html',
      signInOptions: [
        firebase.auth.GoogleAuthProvider.PROVIDER_ID,
        firebase.auth.FacebookAuthProvider.PROVIDER_ID,
        firebase.auth.EmailAuthProvider.PROVIDER_ID,
      ],
      tosUrl: 'index.html',
      privacyPolicyUrl: function() {
        window.location.assign('index.html');
      }
    };
  }

  getTrips = (email) => {return {"1" : "tripA"}};
  createFirebaseWidget = () => {this.ui.start("#firebaseui-auth-container", this.uiConfig)};
  getUserInfo = () => {
    return new Promise((resolve, reject) => {
      this.auth.onAuthStateChanged((user) => {
        if (user) {
          // User is signed in.
          let trips = this.getTrips(user.email);
          let userObject = new User(user.email, user.displayName, trips);
          resolve({signInStatus: true, user: userObject});

        } else {
          // User is signed out.
          resolve({signInStatus: false, user: null});
        }
      })

    });
  }

}

export default Firebase;<commit_msg>Firebase methods<commit_after>import firebase from 'firebase/app';
import 'firebase/auth';
import 'firebase/firestore';
import * as firebaseui from 'firebaseui';
import User from './User';

var firebaseConfig = {
    apiKey: process.env.REACT_APP_API_KEY,
    authDomain:  process.env.REACT_APP_AUTH_DOMAIN,
    databaseURL: process.env.REACT_APP_DATABASE_URL,
    projectId: process.env.REACT_APP_PROJECT_ID,
    storageBucket: process.env.REACT_APP_STORAGE_BUCKET,
    messagingSenderId: process.env.REACT_APP_MESSAGING_SENDER_ID,
    appId: "1:390165048626:web:6e692e8fa9d6c5ea1dbb2b",
    measurementId: "G-JPC7PLV9CF",
  };

class Firebase {
  constructor() {
    firebase.initializeApp(firebaseConfig);
    this.db = firebase.firestore();
    this.auth = firebase.auth();
    this.ui = new firebaseui.auth.AuthUI(this.auth);
    this.uiConfig = {
      signInSuccessUrl: 'index.html',
      signInOptions: [
        firebase.auth.GoogleAuthProvider.PROVIDER_ID,
        firebase.auth.FacebookAuthProvider.PROVIDER_ID,
        firebase.auth.EmailAuthProvider.PROVIDER_ID,
      ],
      tosUrl: 'index.html',
      privacyPolicyUrl: function() {
        window.location.assign('index.html');
      }
    };
  }

  getTrips = (email) => {return {"1" : "tripA"}};
  createFirebaseWidget = () => {this.ui.start("#firebaseui-auth-container", this.uiConfig)};
  getUserInfo = () => {
    return new Promise((resolve, reject) => {
      this.auth.onAuthStateChanged((user) => {
        if (user) {
          // User is signed in.
          let trips = this.getTrips(user.email);
          let userObject = new User(user.email, user.displayName, trips);
          resolve({signInStatus: true, user: userObject});

        } else {
          // User is signed out.
          resolve({signInStatus: false, user: null});
        }
      })

    });
  }

  getData(reference){
    const doc = this.db.doc(reference);
    return doc.get();
  }

  getCollection(reference){
    const collec = this.db.collection(reference);
    return collec.get();
  }

  addTrip(reference, trip) {
    const tripListRef = this.db.collection(reference);
    return tripListRef.add(trip);
  }

  addTravelObject(reference, travelObject) {
    const tripRef = this.db.doc(reference);
    return tripRef.update({travelObjects: firebase.firestore.FieldValue.arrayUnion(travelObject)});
  }

  editTravelObject(reference, oldTravelObject, newTravelObject) {
    const tripRef = this.db.doc(reference);
    return new Promise((resolve) => {
      tripRef.update({travelObjects : firebase.firestore.FieldValue.arrayRemove(oldTravelObject)})
      .then(() => {
        tripRef.update({travelObjects : firebase.firestore.FieldValue.arrayUnion(newTravelObject)})
        .then(() => {resolve()});
     })
    });
  }

  editTrip(reference, data) {
    //TODO: Implement when details of trip editing and settings are implemented
  }

  deleteTravelObject(reference, travelObject) {
    const tripRef = this.db.doc(reference);
    return tripRef.update({travelObjects : firebase.firestore.FieldValue.arrayRemove(travelObject)});
  }

  deleteTrip(reference) {
    const tripRef = this.db.doc(reference);
    return tripRef.delete()
  }

}

export default Firebase;<|endoftext|>


<commit_before>import { Component, PropTypes } from "react";
import Forms from "../../../../components/@primitives/UI/forms";

const focusedInput = {
  border: "1px solid #f0f0f0",
  borderRadius: 7,
  boxShadow: "0px 2px 9px #DDD",
  backgroundColor: "#FFFFFF",
  display: "block",
  textTransform: "captialize",
  position: "relative",
  zIndex: 99,
};

const hiddenInput = {
  border: 0,
};

export default class Campus extends Component {
  state: {
    focused: boolean,
    campus: string,
    onload: boolean,
  };

  static propTypes = {
    campuses: PropTypes.array.isRequired,
    selectedCampus: PropTypes.string.isRequired,
    campusOnChange: PropTypes.func.isRequired,
    iconName: PropTypes.string.isRequired,
    iconFill: PropTypes.string,
    iconWidth: PropTypes.string,
    iconHeight: PropTypes.string,
    iconTitle: PropTypes.string,
  };

  state: {
    focused: boolean,
    campus: string,
    onload: boolean,
  };

  constructor(props: Object) {
    super(props);
    this.state = {
      focused: false,
      campus: "",
      onload: true,
    };

    this.setWrapperRef = this.setWrapperRef.bind(this);
    this.handleClickOutside = this.handleClickOutside.bind(this);
  }

  componentDidMount() {
    document.addEventListener("mousedown", this.handleClickOutside);
    document.addEventListener("touchstart", this.handleClickOutside);
  }

  componentWillReceiveProps(nextProps: Object) {
    if (nextProps.selectedCampus) {
      this.setState({
        campus: nextProps.selectedCampus,
      });
    }
  }

  componentWillUnmount() {
    document.removeEventListener("mousedown", this.handleClickOutside);
    document.removeEventListener("touchend", this.handleClickOutside);
  }

  setWrapperRef(node) {
    this.wrapperRef = node;
  }

  /**
   * Alert if clicked on outside of element
   */
  handleClickOutside(event: Event) {
    if (this.wrapperRef && !this.wrapperRef.contains(event.target)) {
      this.setState({
        focused: false,
      });
    }
  }

  setFocus = () => {
    const focused =
      this.state.onload && this.props.selectedCampus
        ? false
        : !this.state.focused;

    this.setState({
      focused,
      onload: false,
    });
  };

  buttonToggle = () => {
    this.setState({
      focused: !this.state.focused,
    });
  };

  onClick = (e: Event) => {
    const campus = e.target.name || e.target.innerHTML; // eslint-disable-line

    this.setState({
      campus,
    });

    if (!Meteor.isCordova) {
      this.setFocus();
    }

    this.props.campusOnChange(campus);
  };

  onBlur = event => {
    if (event.type === "keydown" && event.keyCode === 9) {
      if (!Meteor.isCordova) {
        this.setFocus();
      }
    }
  };

  render() {
    const { campuses } = this.props;
    const { campus } = this.state;

    return (
      <div
        style={this.state.focused ? focusedInput : hiddenInput}
        className={"soft-double-top text-left soft-half-sides"}
        ref={this.setWrapperRef}
        onKeyDown={this.onBlur}
        onFocus={this.setFocus}
        onTouchStart={this.setFocus}
      >
        <Forms.Input
          classes={this.state.focused ? "soft-bottom" : ""}
          inputClasses={
            "outlined--dotted outlined--light h6 flush-bottom text-black"
          }
          style={{ textTransform: "capitalize" }}
          type="text"
          label={"Campus"}
          labelStyles={{ pointerEvents: "none" }}
          name="campus"
          defaultValue={campus}
          readOnly="readonly"
          onFocus={this.setFocus}
          iconName={this.state.focused ? "arrowUp" : "arrowDown"}
          iconFill={this.state.focused ? "#6BAC43" : "#505050"}
          iconWidth={"24px"}
          iconHeight={"24px"}
          iconTitle={this.state.focused ? "Arrow Up Icon" : "Arrow Down Icon"}
          iconButtonToggle={this.buttonToggle}
          ignoreLastPass
        />
        <div
          className={`push-half-sides push-half-bottom ${!this.state.focused
            ? "visuallyhidden"
            : "display-inline-block"}`}
        >
          {/* weird SSR stuff here to investigate */}
          {campuses.map((c, i) =>
            <Forms.Checkbox
              classes={[
                "soft-half-bottom",
                "float-left@lap-and-up",
                "one-half@lap-and-up",
                "display-inline-block@lap-and-up",
              ]}
              defaultChecked={campus === c ? "defaultChecked" : ""}
              name={c}
              key={i}
              clicked={this.onClick}
            >
              <span
                className="soft-half-top"
                style={{ textTransform: "capitalize" }}
              >
                {c}
              </span>
            </Forms.Checkbox>,
          )}
        </div>
      </div>
    );
  }
}
<commit_msg>campus changes<commit_after>import { Component, PropTypes } from "react";
import Forms from "../../../../components/@primitives/UI/forms";

const focusedInput = {
  border: "1px solid #f0f0f0",
  borderRadius: 7,
  boxShadow: "0px 2px 9px #DDD",
  backgroundColor: "#FFFFFF",
  display: "block",
  textTransform: "captialize",
  position: "relative",
  zIndex: 99,
};

const hiddenInput = {
  border: 0,
};

export default class Campus extends Component {
  state: {
    focused: boolean,
    campus: string,
    onload: boolean,
  };

  static propTypes = {
    campuses: PropTypes.array.isRequired,
    selectedCampus: PropTypes.string.isRequired,
    campusOnChange: PropTypes.func.isRequired,
    iconName: PropTypes.string.isRequired,
    iconFill: PropTypes.string,
    iconWidth: PropTypes.string,
    iconHeight: PropTypes.string,
    iconTitle: PropTypes.string,
  };

  state: {
    focused: boolean,
    campus: string,
    onload: boolean,
  };

  constructor(props: Object) {
    super(props);
    this.state = {
      focused: false,
      campus: "",
      onload: true,
    };

    this.setWrapperRef = this.setWrapperRef.bind(this);
    this.handleClickOutside = this.handleClickOutside.bind(this);
  }

  componentDidMount() {
    document.addEventListener("mousedown", this.handleClickOutside);
    document.addEventListener("touchstart", this.handleClickOutside);
  }

  componentWillReceiveProps(nextProps: Object) {
    if (nextProps.selectedCampus) {
      this.setState({
        campus: nextProps.selectedCampus,
      });
    }
  }

  componentWillUnmount() {
    document.removeEventListener("mousedown", this.handleClickOutside);
    document.removeEventListener("touchend", this.handleClickOutside);
  }

  setWrapperRef(node) {
    this.wrapperRef = node;
  }

  /**
   * Alert if clicked on outside of element
   */
  handleClickOutside(event: Event) {
    if (this.wrapperRef && !this.wrapperRef.contains(event.target)) {
      this.setState({
        focused: false,
      });
    }
  }

  setFocus = () => {
    const focused =
      this.state.onload && this.props.selectedCampus
        ? false
        : !this.state.focused;

    this.setState({
      focused,
      onload: false,
    });
  };

  buttonToggle = () => {
    this.setState({
      focused: !this.state.focused,
    });
  };

  onClick = (e: Event) => {
    const campus = e.target.name || e.target.innerHTML; // eslint-disable-line

    this.setState({
      campus,
    });

    if (!Meteor.isCordova) {
      this.setFocus();
    }

    this.props.campusOnChange(campus);
  };

  onBlur = event => {
    if (event.type === "keydown" && event.keyCode === 9) {
      if (!Meteor.isCordova) {
        this.setFocus();
      }
    }
  };

  render() {
    const { campuses } = this.props;
    const { campus } = this.state;

    return (
      <div
        style={this.state.focused ? focusedInput : hiddenInput}
        className={"soft-double-top text-left soft-half-sides"}
        ref={this.setWrapperRef}
        onKeyDown={this.onBlur}
        onFocus={this.setFocus}
        onTouchStart={this.setFocus}
      >
        <Forms.Input
          classes={this.state.focused ? "soft-bottom" : ""}
          inputClasses={
            "outlined--dotted outlined--light h6 flush-bottom text-black"
          }
          style={{ textTransform: "capitalize" }}
          type="text"
          label={"Campus"}
          labelStyles={{ pointerEvents: "none" }}
          name="campus"
          defaultValue={campus}
          iconName={this.state.focused ? "arrowUp" : "arrowDown"}
          iconFill={this.state.focused ? "#6BAC43" : "#505050"}
          iconWidth={"24px"}
          iconHeight={"24px"}
          iconTitle={this.state.focused ? "Arrow Up Icon" : "Arrow Down Icon"}
          iconButtonToggle={this.buttonToggle}
          ignoreLastPass
          readOnly="readonly"
        />
        <div
          className={`push-half-sides push-half-bottom ${!this.state.focused
            ? "visuallyhidden"
            : "display-inline-block"}`}
        >
          {/* weird SSR stuff here to investigate */}
          {campuses.map((c, i) =>
            <Forms.Checkbox
              classes={[
                "soft-half-bottom",
                "float-left@lap-and-up",
                "one-half@lap-and-up",
                "display-inline-block@lap-and-up",
              ]}
              defaultChecked={campus === c ? "defaultChecked" : ""}
              name={c}
              key={i}
              clicked={this.onClick}
            >
              <span
                className="soft-half-top"
                style={{ textTransform: "capitalize" }}
              >
                {c}
              </span>
            </Forms.Checkbox>,
          )}
        </div>
      </div>
    );
  }
}
<|endoftext|>


<commit_before>define([
	'goo/math/Transform',
	'goo/entities/components/Component'
],
/** @lends */
function (
	Transform,
	Component
) {
	"use strict";

	/**
	 * @class Holds the transform of an entity. It also allows for a scene graph to be created, where transforms are inherited
	 * down the tree.
	 */
	function TransformComponent() {
		this.type = 'TransformComponent';

		/** Parent transformcomponent in the scene graph
		 * @type {TransformComponent}
		 * @default
		 */
		this.parent = null;
		/**
		 * Child transformcomponents in the "scenegraph"
		 * @type {TransformComponent[]}
		 */
		this.children = [];
		/** @type {Transform} */
		this.transform = new Transform();
		/** @type {Transform} */
		this.worldTransform = new Transform();

		this._dirty = true;
		this._updated = false;
	}

	TransformComponent.prototype = Object.create(Component.prototype);

	/**
	 * Mark the component for updates of world transform
	 */
	TransformComponent.prototype.setUpdated = function () {
		this._dirty = true;
	};

	/**
	 * Attach a child transform to this component tree
	 *
	 * @param childComponent child transform component to attach
	 */
	TransformComponent.prototype.attachChild = function (childComponent) {
		if (childComponent === this) {
			// REVIEW rickard: Do we need to check this recursively? ANSWER: Yes
			console.warn('attachChild: An object can\'t be added as a child of itself.');
			return;
		}

		if (childComponent.parent) {
			childComponent.parent.detachChild(childComponent);
		}
		childComponent.parent = this;
		this.children.push(childComponent);
	};

	/**
	 * Detach a child transform from this component tree
	 *
	 * @param childComponent child transform component to detach
	 */
	TransformComponent.prototype.detachChild = function (childComponent) {
		if (childComponent === this) {
			console.warn('attachChild: An object can\'t be removed from itself.');
			return;
		}

		var index = this.children.indexOf(childComponent);
		if (index !== -1) {
			childComponent.parent = null;
			this.children.splice(index, 1);
		}
	};

	/**
	 * Update target transform contained by this component
	 */
	TransformComponent.prototype.updateTransform = function () {
		this.transform.update();
	};

	/**
	 * Update this transform components world transform (resulting transform considering parent transformations)
	 */
	TransformComponent.prototype.updateWorldTransform = function () {
		if (this.parent) {
			this.worldTransform.multiply(this.parent.worldTransform, this.transform);
		} else {
			this.worldTransform.copy(this.transform);
		}
		this._dirty = false;
		this._updated = true;
	};

	return TransformComponent;
});<commit_msg>Fix of review comment. Transformcomponents can now not be descandants of their selves<commit_after>define([
	'goo/math/Transform',
	'goo/entities/components/Component'
],
/** @lends */
function (
	Transform,
	Component
) {
	"use strict";

	/**
	 * @class Holds the transform of an entity. It also allows for a scene graph to be created, where transforms are inherited
	 * down the tree.
	 */
	function TransformComponent() {
		this.type = 'TransformComponent';

		/** Parent transformcomponent in the scene graph
		 * @type {TransformComponent}
		 * @default
		 */
		this.parent = null;
		/**
		 * Child transformcomponents in the "scenegraph"
		 * @type {TransformComponent[]}
		 */
		this.children = [];
		/** @type {Transform} */
		this.transform = new Transform();
		/** @type {Transform} */
		this.worldTransform = new Transform();

		this._dirty = true;
		this._updated = false;
	}

	TransformComponent.prototype = Object.create(Component.prototype);

	/**
	 * Mark the component for updates of world transform
	 */
	TransformComponent.prototype.setUpdated = function () {
		this._dirty = true;
	};

	/**
	 * Attach a child transform to this component tree
	 *
	 * @param childComponent child transform component to attach
	 */
	TransformComponent.prototype.attachChild = function (childComponent) {
		var component = this;
		while(component) {
			if (component === childComponent) {
				console.warn('attachChild: An object can\'t be added as a descendant of itself.');
				return;
			}
			component = component.parent;
		}
		if (childComponent.parent) {
			childComponent.parent.detachChild(childComponent);
		}
		childComponent.parent = this;
		this.children.push(childComponent);
	};

	/**
	 * Detach a child transform from this component tree
	 *
	 * @param childComponent child transform component to detach
	 */
	TransformComponent.prototype.detachChild = function (childComponent) {
		if (childComponent === this) {
			console.warn('attachChild: An object can\'t be removed from itself.');
			return;
		}

		var index = this.children.indexOf(childComponent);
		if (index !== -1) {
			childComponent.parent = null;
			this.children.splice(index, 1);
		}
	};

	/**
	 * Update target transform contained by this component
	 */
	TransformComponent.prototype.updateTransform = function () {
		this.transform.update();
	};

	/**
	 * Update this transform components world transform (resulting transform considering parent transformations)
	 */
	TransformComponent.prototype.updateWorldTransform = function () {
		if (this.parent) {
			this.worldTransform.multiply(this.parent.worldTransform, this.transform);
		} else {
			this.worldTransform.copy(this.transform);
		}
		this._dirty = false;
		this._updated = true;
	};

	return TransformComponent;
});<|endoftext|>


<commit_before>//! moment.js locale configuration
//! locale : Marathi (mr)
//! author : Harshad Kale : https://github.com/kalehv
//! author : Vivek Athalye : https://github.com/vnathalye

(function (global, factory) {
   typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('../moment')) :
   typeof define === 'function' && define.amd ? define(['moment'], factory) :
   factory(global.moment)
}(this, function (moment) { 'use strict';

    var symbolMap = {
        '1': '१',
        '2': '२',
        '3': '३',
        '4': '४',
        '5': '५',
        '6': '६',
        '7': '७',
        '8': '८',
        '9': '९',
        '0': '०'
    },
    numberMap = {
        '१': '1',
        '२': '2',
        '३': '3',
        '४': '4',
        '५': '5',
        '६': '6',
        '७': '7',
        '८': '8',
        '९': '9',
        '०': '0'
    };

    function mr_relativeTime(number, withoutSuffix, string, isFuture)
    {
        var output = "";
        if (withoutSuffix) {
            switch(string) {
                case "s": output = 'काही सेकंद'; break;
                case "m": output = 'एक मिनिट'; break;
                case "mm": output = '%d मिनिटे'; break;
                case "h": output = 'एक तास'; break;
                case "hh": output = '%d तास'; break;
                case "d": output = 'एक दिवस'; break;
                case "dd": output = '%d दिवस'; break;
                case "M": output = 'एक महिना'; break;
                case "MM": output = '%d महिने'; break;
                case "y": output = 'एक वर्ष'; break;
                case "yy": output = '%d वर्षे'; break;
            }
        }
        else {
            switch (string) {
                case "s": output = 'काही सेकंदां'; break;
                case "m": output = 'एका मिनिटा'; break;
                case "mm": output = '%d मिनिटां'; break;
                case "h": output = 'एका तासा'; break;
                case "hh": output = '%d तासां'; break;
                case "d": output = 'एका दिवसा'; break;
                case "dd": output = '%d दिवसां'; break;
                case "M": output = 'एका महिन्या'; break;
                case "MM": output = '%d महिन्यां'; break;
                case "y": output = 'एका वर्षा'; break;
                case "yy": output = '%d वर्षां'; break;
            }
        }
        return output.replace(/%d/i, number);
    }

    var mr = moment.defineLocale('mr', {
        months : 'जानेवारी_फेब्रुवारी_मार्च_एप्रिल_मे_जून_जुलै_ऑगस्ट_सप्टेंबर_ऑक्टोबर_नोव्हेंबर_डिसेंबर'.split('_'),
        monthsShort: 'जाने._फेब्रु._मार्च._एप्रि._मे._जून._जुलै._ऑग._सप्टें._ऑक्टो._नोव्हें._डिसें.'.split('_'),
        weekdays : 'रविवार_सोमवार_मंगळवार_बुधवार_गुरूवार_शुक्रवार_शनिवार'.split('_'),
        weekdaysShort : 'रवि_सोम_मंगळ_बुध_गुरू_शुक्र_शनि'.split('_'),
        weekdaysMin : 'र_सो_मं_बु_गु_शु_श'.split('_'),
        longDateFormat : {
            LT : 'A h:mm वाजता',
            LTS : 'A h:mm:ss वाजता',
            L : 'DD/MM/YYYY',
            LL : 'D MMMM YYYY',
            LLL : 'D MMMM YYYY, A h:mm वाजता',
            LLLL : 'dddd, D MMMM YYYY, A h:mm वाजता'
        },
        calendar : {
            sameDay : '[आज] LT',
            nextDay : '[उद्या] LT',
            nextWeek : 'dddd, LT',
            lastDay : '[काल] LT',
            lastWeek: '[मागील] dddd, LT',
            sameElse : 'L'
        },
        relativeTime: {
            future: '%sमध्ये',
            past: '%sपूर्वी',
            s: mr_relativeTime,
            m: mr_relativeTime,
            mm: mr_relativeTime,
            h: mr_relativeTime,
            hh: mr_relativeTime,
            d: mr_relativeTime,
            dd: mr_relativeTime,
            M: mr_relativeTime,
            MM: mr_relativeTime,
            y: mr_relativeTime,
            yy: mr_relativeTime
        },
        preparse: function (string) {
            return string.replace(/[१२३४५६७८९०]/g, function (match) {
                return numberMap[match];
            });
        },
        postformat: function (string) {
            return string.replace(/\d/g, function (match) {
                return symbolMap[match];
            });
        },
        meridiemParse: /रात्री|सकाळी|दुपारी|सायंकाळी/,
        meridiemHour : function (hour, meridiem) {
            if (hour === 12) {
                hour = 0;
            }
            if (meridiem === 'रात्री') {
                return hour < 4 ? hour : hour + 12;
            } else if (meridiem === 'सकाळी') {
                return hour;
            } else if (meridiem === 'दुपारी') {
                return hour >= 10 ? hour : hour + 12;
            } else if (meridiem === 'सायंकाळी') {
                return hour + 12;
            }
        },
        meridiem: function (hour, minute, isLower) {
            if (hour < 4) {
                return 'रात्री';
            } else if (hour < 10) {
                return 'सकाळी';
            } else if (hour < 17) {
                return 'दुपारी';
            } else if (hour < 20) {
                return 'सायंकाळी';
            } else {
                return 'रात्री';
            }
        },
        week : {
            dow : 0, // Sunday is the first day of the week.
            doy : 6  // The week that contains Jan 1st is the first week of the year.
        }
    });

    return mr;

}));<commit_msg>Removing my changes<commit_after><|endoftext|>


<commit_before>require('../handler-base')();

var validateUUID = sinon.stub(),
  eventStore = {
    queryStatePartitionById: sinon.stub(),
    postToStream: sinon.stub().resolves()
  },
  translator = {
    translatePush: sinon.stub()
  },
  commitsAddedFormatAsHal = sinon.stub(),
  githubValidator = sinon.stub();

var handler = proxyquire('../../api/inboxes/commitsCreate', {
  '../validateUUID': validateUUID,
  '../helpers/eventStoreClient': eventStore,
  '../translators/githubTranslator': translator,
  './commitsAddedFormatAsHal': commitsAddedFormatAsHal,
  '../helpers/githubValidator': githubValidator
});

describe('commitsCreate', function() {

  describe('when posting a push event', function() {
    var instanceId = '872512eb-0d42-41fa-9a4e-fcb480ef265f',
      inboxId = 'e70ee98d-cd21-4bfe-a4fe-bbded9ce4584',
      digestId = 'ff1fdc30-d0e2-465b-b23d-fda510acc1bc',
      queryStatePartitionArgs,
      postToStreamArgs,
      request,
      response,
      inboxData;

    before(function() {
      eventStore.queryStatePartitionById.resolves({
        digestId: digestId
      });

      githubValidator.returns('push');

      commitsAddedFormatAsHal.returns({});
      translator.translatePush.returns({});

      request = httpMocks.createRequest({
        method: 'POST',
        url: '/api/' + instanceId + '/inboxes/' + inboxId + '/commits',
        body: {},
        headers: {}
      });

      response = httpMocks.createResponse();
      request.instance = {
        instanceId: instanceId
      };
      request.params = {
        inboxId: inboxId
      };
      request.href = sinon.spy();
      response.hal = sinon.spy();

      inboxData = {
        inboxId: inboxId,
        digestId: digestId
      };

      postToStreamArgs = {
        name: 'inboxCommits-' + inboxId,
        events: '{}'
      };

      queryStatePartitionArgs = {
        name: 'inbox',
        id: inboxId
      };

      handler(request, response);

    });

    it('should call validateUUID with correct args', function() {
      validateUUID.should.have.been.calledWith('inbox', inboxId);
    });

    it('should call eventStore.queryStatePartitionById with correct args', function() {
      eventStore.queryStatePartitionById.should.have.been.calledWith(queryStatePartitionArgs);
    });

    it('should call githubValidator with correct args', function() {
      githubValidator.should.have.been.calledWith({});
    });

    it('should call translator.translatePush with correct args', function() {
      translator.translatePush.should.have.been.calledWith({}, instanceId, digestId, inboxId);
    });

    it('should call eventStore.postToStream with correct args', function() {
      eventStore.postToStream.should.have.been.calledWith(postToStreamArgs);
    });

    it('should call commitsAddedFormatAsHal with correct args', function() {
      commitsAddedFormatAsHal.should.have.been.calledWith(request.href, instanceId, inboxData);
    });

    it('should call res.hal with correct args', function() {
      response.hal.should.have.been.calledWith({}, 201);
    });

  });

});<commit_msg>S-51679 Added test case for "ping" github event.<commit_after>require('../handler-base')();

var validateUUID = sinon.stub(),
  eventStore = {
    queryStatePartitionById: sinon.stub(),
    postToStream: sinon.stub().resolves()
  },
  translator = {
    translatePush: sinon.stub()
  },
  commitsAddedFormatAsHal = sinon.stub(),
  githubValidator = sinon.stub();

var handler = proxyquire('../../api/inboxes/commitsCreate', {
  '../validateUUID': validateUUID,
  '../helpers/eventStoreClient': eventStore,
  '../translators/githubTranslator': translator,
  './commitsAddedFormatAsHal': commitsAddedFormatAsHal,
  '../helpers/githubValidator': githubValidator
});

describe('commitsCreate', function() {

  var instanceId = '872512eb-0d42-41fa-9a4e-fcb480ef265f',
    inboxId = 'e70ee98d-cd21-4bfe-a4fe-bbded9ce4584',
    digestId = 'ff1fdc30-d0e2-465b-b23d-fda510acc1bc',
    queryStatePartitionArgs,
    postToStreamArgs,
    request,
    response,
    inboxData;

  before(function() {
    eventStore.queryStatePartitionById.resolves({
      digestId: digestId
    });

    commitsAddedFormatAsHal.returns({});
    translator.translatePush.returns({});

    request = httpMocks.createRequest({
      method: 'POST',
      url: '/api/' + instanceId + '/inboxes/' + inboxId + '/commits',
      body: {},
      headers: {}
    });

    response = httpMocks.createResponse();
    request.instance = {
      instanceId: instanceId
    };
    request.params = {
      inboxId: inboxId
    };
    request.href = sinon.spy();
    response.hal = sinon.spy();

    inboxData = {
      inboxId: inboxId,
      digestId: digestId
    };

    postToStreamArgs = {
      name: 'inboxCommits-' + inboxId,
      events: '{}'
    };

    queryStatePartitionArgs = {
      name: 'inbox',
      id: inboxId
    };
  });

  describe('when posting a push event', function() {
    before(function() {
      githubValidator.returns('push');
      handler(request, response);
    });

    it('should call validateUUID with correct args', function() {
      validateUUID.should.have.been.calledWith('inbox', inboxId);
    });

    it('should call eventStore.queryStatePartitionById with correct args', function() {
      eventStore.queryStatePartitionById.should.have.been.calledWith(queryStatePartitionArgs);
    });

    it('should call githubValidator with correct args', function() {
      githubValidator.should.have.been.calledWith({});
    });

    it('should call translator.translatePush with correct args', function() {
      translator.translatePush.should.have.been.calledWith({}, instanceId, digestId, inboxId);
    });

    it('should call eventStore.postToStream with correct args', function() {
      eventStore.postToStream.should.have.been.calledWith(postToStreamArgs);
    });

    it('should call commitsAddedFormatAsHal with correct args', function() {
      commitsAddedFormatAsHal.should.have.been.calledWith(request.href, instanceId, inboxData);
    });

    it('should call res.hal with correct args', function() {
      response.hal.should.have.been.calledWith({}, 201);
    });

  });

  describe('when posting a ping event', function() {
    before(function() {
      githubValidator.returns('ping');
      response.status = sinon.stub();
      response.status.returns({
        send: sinon.stub()
      });
      handler(request, response);
    });

    it('should call validateUUID with correct args', function() {
      validateUUID.should.have.been.calledWith('inbox', inboxId);
    });

    it('should call eventStore.queryStatePartitionById with correct args', function() {
      eventStore.queryStatePartitionById.should.have.been.calledWith(queryStatePartitionArgs);
    });

    it('should call githubValidator with correct args', function() {
      githubValidator.should.have.been.calledWith({});
    });

    it('should call res.status with correct args', function() {
      response.status.should.have.been.calledWith(200);
    });

    it('should call res.status.send with correct args', function() {
      response.status().send.should.have.been.calledWith({
        message: 'Pong.'
      });
    });

  });

});<|endoftext|>


<commit_before>/*
**  ComponentJS -- Component System for JavaScript <http://componentjs.com>
**  Copyright (c) 2009-2012 Ralf S. Engelschall <http://engelschall.com>
**
**  This Source Code Form is subject to the terms of the Mozilla Public
**  License, v. 2.0. If a copy of the MPL was not distributed with this
**  file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

/*  generic pattern: event  */
$cs.pattern.event = $cs.clazz({
    mixin: [
        $cs.pattern.spec
    ],
    dynamics: {
        /*  attributes  */
        target:      $cs.attribute("target",      null),        /*  target object the event is send to  */
        propagation: $cs.attribute("propagation", true),        /*  whether event propagation should continue  */
        processing:  $cs.attribute("processing",  true),        /*  whether final default event processing should be performed  */
        dispatched:  $cs.attribute("dispatched",  false),       /*  whether event was dispatched at least once to a subscriber  */
        decline:     $cs.attribute("decline",     false),       /*  whether event was declined by subscriber  */
        state:       $cs.attribute("state",       "targeting"), /*  state of dispatching: capturing, targeting, bubbling */
        result:      $cs.attribute("result",      undefined),   /*  optional result value event subscribers can provide  */
        async:       $cs.attribute("async",       false)        /*  whether event is dispatched asynchronously  */
    }
});

/*  event factory  */
$cs.event = function () {
    /*  determine parameters  */
    var params = $cs.params("event", arguments, {
        name:        { pos: 0,     def: null, req: true  },
        spec:        {             def: {}               },
        target:      { pos: 1,     def: null, req: true  },
        propagation: { pos: 2,     def: true             },
        processing:  { pos: 3,     def: true             },
        dispatched:  { pos: 4,     def: false            },
        decline:     { pos: 5,     def: false            },
        state:       { pos: 6,     def: "targeting"      },
        result:      { pos: 7,     def: undefined        },
        async:       { pos: 8,     def: false            }
    });

    /*  create new event  */
    var ev = new $cs.pattern.event();

    /*  configure event  */
    ev.name       (params.name);
    ev.target     (params.target);
    ev.propagation(params.propagation);
    ev.processing (params.processing);
    ev.dispatched (params.dispatched);
    ev.decline    (params.decline);
    ev.state      (params.state);
    ev.result     (params.result);
    ev.spec       (params.spec);
    ev.async      (params.async);

    return ev;
};

/*  generic pattern: eventing  */
$cs.pattern.eventing = $cs.trait({
    dynamics: {
        __subscription: {},
        __subscription_id: 0
    },
    protos: {
        /*  subscribe on an event  */
        subscribe: function () {
            /*  determine parameters  */
            var params = $cs.params("subscribe", arguments, {
                name:      { pos: 0,     def: null,    req: true },
                spec:      {             def: {}                 },
                ctx:       {             def: this               },
                func:      { pos: 1,     def: $cs.nop, req: true },
                args:      { pos: "...", def: []                 },
                capture:   {             def: false              },
                noevent:   {             def: false              },
                exclusive: {             def: false              },
                origin:    {             def: false              }
            });

            /*  honor exclusive request  */
            if (params.exclusive) {
                var subscribers = this.subscribers(params.name, params.spec);
                if (subscribers.length > 0)
                    throw _cs.exception("subscribe", "multiple exclusive subscribers not allowed");
            }

            /*  attach parameters to component  */
            var id = this.__subscription_id++;
            this.__subscription[id] = params;
            return id;
        },

        /*  unsubscribe from an event  */
        unsubscribe: function (id) {
            /*  determine parameters  */
            var params = $cs.params("unsubscribe", arguments, {
                id: { pos: 0, req: true }
            });

            /*  detach parameters from component  */
            if (typeof this.__subscription[params.id] === "undefined")
                throw _cs.exception("unsubscribe", "subscription not found");
            delete this.__subscription[params.id];
            return;
        },

        /*  determine subscribers  */
        subscribers: function () {
            /*  determine parameters  */
            var params = $cs.params("subscribers", arguments, {
                name:  { pos: 0, def: null, req: true },
                spec:  { pos: 1, def: {}              }
            });

            /*  make an event for matching only  */
            var ev = $cs.event({
                name: params.name,
                spec: params.spec
            });

            /*  find and return all matching subscribers  */
            var subscribers = [];
            for (var id in this.__subscription) {
                if (!_cs.isown(this.__subscription, id))
                    continue;
                var s = this.__subscription[id];
                if (ev.matches(s.name, s.spec))
                    subscribers.push(s);
            }
            return subscribers;
        },

        /*  publish an event */
        publish: function () {
            var i;
            var self = this;

            /*  determine parameters  */
            var params = $cs.params("publish", arguments, {
                name:         { pos: 0,     def: null, req: true },
                spec:         {             def: {}              },
                async:        {             def: false           },
                capturing:    {             def: true            },
                bubbling:     {             def: true            },
                completed:    {             def: $cs.nop         },
                directresult: {             def: false           },
                firstonly:    {             def: false           },
                args:         { pos: "...", def: []              }
            });

            /*  short-circuit processing (1/2) to speed up cases
                where no subscribers exist for a local event  */
            var short_circuit = false;
            if (!params.capturing && !params.bubbling) {
                var subscribers = false;
                for (var id in this.__subscription) {
                    if (!_cs.isown(this.__subscription, id))
                        continue;
                    subscribers = true;
                    break;
                }
                if (!subscribers) {
                    if (params.directresult)
                        return undefined;
                    else
                        short_circuit = true;
                }
            }

            /*  create event  */
            var ev = $cs.event({
                name:        params.name,
                spec:        params.spec,
                async:       params.async,
                target:      self,
                propagation: true,
                processing:  true,
                dispatched:  false
            });

            /*  short-circuit processing (2/2)  */
            if (short_circuit)
                return ev;

            /*  tracing  */
            $cs.debug(1, "event: " +
                ev.target().path("/") + ": publish: " +
                " name=" + ev.name() +
                " async=" + ev.async() +
                " capturing=" + params.capturing +
                " bubbling=" + params.bubbling +
                " directresult=" + params.directresult +
                " firstonly=" + params.firstonly
            );

            /*  helper function for dispatching event to single component  */
            var event_dispatch_single = function (ev, origin, comp, params, state) {
                for (var id in comp.__subscription) {
                    if (!_cs.isown(comp.__subscription, id))
                        continue;
                    var s = comp.__subscription[id];
                    if (   (   state === "capturing" &&  s.capture
                            || state === "targeting" && !s.capture
                            || state === "bubbling"  && !s.capture)
                        && ev.matches(s.name, s.spec)             ) {
                        $cs.debug(1, "event: " + comp.path("/") + ": dispatch on " + state);
                        ev.state(state);
                        ev.decline(false);
                        var args = _cs.concat(
                            s.origin  ? [ origin ] : [],
                            s.noevent ? [] : [ ev ],
                            s.args,
                            params.args
                        );
                        var result = s.func.apply(s.ctx, args);
                        if (s.noevent && _cs.isdefined(result))
                            ev.result(result);
                        if (!ev.decline()) {
                            ev.dispatched(true);
                            if (params.firstonly)
                                ev.propagation(false);
                        }
                    }
                }
            };

            /*  helper function for dispatching event to all components on hierarchy path  */
            var event_dispatch_all = function (ev, comp, params) {
                /*  determine component tree path  */
                var comp_path;
                if (params.capturing || params.bubbling)
                    comp_path = comp.path();

                /*  phase 1: CAPTURING
                    optionally dispatch event downwards from root component
                    towards target component for capturing subscribers  */
                if (params.capturing) {
                    for (i = comp_path.length - 1; i >= 1; i--) {
                        event_dispatch_single(ev, comp, comp_path[i], params, "capturing");
                        if (!ev.propagation())
                            break;
                    }
                }

                /*  phase 2: TARGETING
                    dispatch event to target component  */
                if (ev.propagation())
                    event_dispatch_single(ev, comp, comp, params, "targeting");

                /*  phase 3: BUBBLING
                    dispatch event upwards from target component towards
                    root component for bubbling (regular) subscribers  */
                if (params.bubbling && ev.propagation()) {
                    for (i = 1; i < comp_path.length; i++) {
                        event_dispatch_single(ev, comp, comp_path[i], params, "bubbling");
                        if (!ev.propagation())
                            break;
                    }
                }

                /*  notify publisher on dispatch completion  */
                params.completed.call(comp, ev);
            };

            /*  perform event publishing,
                either asynchronous or synchronous  */
            if (ev.async())
                setTimeout(function () { event_dispatch_all(ev, self, params); }, 0);
            else
                event_dispatch_all(ev, self, params);

            /*  return the event or directly the result value  */
            return (params.directresult ? ev.result() : ev);
        }
    }
});

<commit_msg>allow events to be published silently<commit_after>/*
**  ComponentJS -- Component System for JavaScript <http://componentjs.com>
**  Copyright (c) 2009-2012 Ralf S. Engelschall <http://engelschall.com>
**
**  This Source Code Form is subject to the terms of the Mozilla Public
**  License, v. 2.0. If a copy of the MPL was not distributed with this
**  file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

/*  generic pattern: event  */
$cs.pattern.event = $cs.clazz({
    mixin: [
        $cs.pattern.spec
    ],
    dynamics: {
        /*  attributes  */
        target:      $cs.attribute("target",      null),        /*  target object the event is send to  */
        propagation: $cs.attribute("propagation", true),        /*  whether event propagation should continue  */
        processing:  $cs.attribute("processing",  true),        /*  whether final default event processing should be performed  */
        dispatched:  $cs.attribute("dispatched",  false),       /*  whether event was dispatched at least once to a subscriber  */
        decline:     $cs.attribute("decline",     false),       /*  whether event was declined by subscriber  */
        state:       $cs.attribute("state",       "targeting"), /*  state of dispatching: capturing, targeting, bubbling */
        result:      $cs.attribute("result",      undefined),   /*  optional result value event subscribers can provide  */
        async:       $cs.attribute("async",       false)        /*  whether event is dispatched asynchronously  */
    }
});

/*  event factory  */
$cs.event = function () {
    /*  determine parameters  */
    var params = $cs.params("event", arguments, {
        name:        { pos: 0,     def: null, req: true  },
        spec:        {             def: {}               },
        target:      { pos: 1,     def: null, req: true  },
        propagation: { pos: 2,     def: true             },
        processing:  { pos: 3,     def: true             },
        dispatched:  { pos: 4,     def: false            },
        decline:     { pos: 5,     def: false            },
        state:       { pos: 6,     def: "targeting"      },
        result:      { pos: 7,     def: undefined        },
        async:       { pos: 8,     def: false            }
    });

    /*  create new event  */
    var ev = new $cs.pattern.event();

    /*  configure event  */
    ev.name       (params.name);
    ev.target     (params.target);
    ev.propagation(params.propagation);
    ev.processing (params.processing);
    ev.dispatched (params.dispatched);
    ev.decline    (params.decline);
    ev.state      (params.state);
    ev.result     (params.result);
    ev.spec       (params.spec);
    ev.async      (params.async);

    return ev;
};

/*  generic pattern: eventing  */
$cs.pattern.eventing = $cs.trait({
    dynamics: {
        __subscription: {},
        __subscription_id: 0
    },
    protos: {
        /*  subscribe on an event  */
        subscribe: function () {
            /*  determine parameters  */
            var params = $cs.params("subscribe", arguments, {
                name:      { pos: 0,     def: null,    req: true },
                spec:      {             def: {}                 },
                ctx:       {             def: this               },
                func:      { pos: 1,     def: $cs.nop, req: true },
                args:      { pos: "...", def: []                 },
                capture:   {             def: false              },
                noevent:   {             def: false              },
                exclusive: {             def: false              },
                origin:    {             def: false              }
            });

            /*  honor exclusive request  */
            if (params.exclusive) {
                var subscribers = this.subscribers(params.name, params.spec);
                if (subscribers.length > 0)
                    throw _cs.exception("subscribe", "multiple exclusive subscribers not allowed");
            }

            /*  attach parameters to component  */
            var id = this.__subscription_id++;
            this.__subscription[id] = params;
            return id;
        },

        /*  unsubscribe from an event  */
        unsubscribe: function (id) {
            /*  determine parameters  */
            var params = $cs.params("unsubscribe", arguments, {
                id: { pos: 0, req: true }
            });

            /*  detach parameters from component  */
            if (typeof this.__subscription[params.id] === "undefined")
                throw _cs.exception("unsubscribe", "subscription not found");
            delete this.__subscription[params.id];
            return;
        },

        /*  determine subscribers  */
        subscribers: function () {
            /*  determine parameters  */
            var params = $cs.params("subscribers", arguments, {
                name:  { pos: 0, def: null, req: true },
                spec:  { pos: 1, def: {}              }
            });

            /*  make an event for matching only  */
            var ev = $cs.event({
                name: params.name,
                spec: params.spec
            });

            /*  find and return all matching subscribers  */
            var subscribers = [];
            for (var id in this.__subscription) {
                if (!_cs.isown(this.__subscription, id))
                    continue;
                var s = this.__subscription[id];
                if (ev.matches(s.name, s.spec))
                    subscribers.push(s);
            }
            return subscribers;
        },

        /*  publish an event */
        publish: function () {
            var i;
            var self = this;

            /*  determine parameters  */
            var params = $cs.params("publish", arguments, {
                name:         { pos: 0,     def: null, req: true },
                spec:         {             def: {}              },
                async:        {             def: false           },
                capturing:    {             def: true            },
                bubbling:     {             def: true            },
                completed:    {             def: $cs.nop         },
                directresult: {             def: false           },
                firstonly:    {             def: false           },
                silent:       {             def: false           },
                args:         { pos: "...", def: []              }
            });

            /*  short-circuit processing (1/2) to speed up cases
                where no subscribers exist for a local event  */
            var short_circuit = false;
            if (!params.capturing && !params.bubbling) {
                var subscribers = false;
                for (var id in this.__subscription) {
                    if (!_cs.isown(this.__subscription, id))
                        continue;
                    subscribers = true;
                    break;
                }
                if (!subscribers) {
                    if (params.directresult)
                        return undefined;
                    else
                        short_circuit = true;
                }
            }

            /*  create event  */
            var ev = $cs.event({
                name:        params.name,
                spec:        params.spec,
                async:       params.async,
                target:      self,
                propagation: true,
                processing:  true,
                dispatched:  false
            });

            /*  short-circuit processing (2/2)  */
            if (short_circuit)
                return ev;

            /*  tracing  */
            if (!params.silent) {
                $cs.debug(1, "event: " +
                    ev.target().path("/") + ": publish: " +
                    " name=" + ev.name() +
                    " async=" + ev.async() +
                    " capturing=" + params.capturing +
                    " bubbling=" + params.bubbling +
                    " directresult=" + params.directresult +
                    " firstonly=" + params.firstonly
                );
            }

            /*  helper function for dispatching event to single component  */
            var event_dispatch_single = function (ev, origin, comp, params, state) {
                for (var id in comp.__subscription) {
                    if (!_cs.isown(comp.__subscription, id))
                        continue;
                    var s = comp.__subscription[id];
                    if (   (   state === "capturing" &&  s.capture
                            || state === "targeting" && !s.capture
                            || state === "bubbling"  && !s.capture)
                        && ev.matches(s.name, s.spec)             ) {
                        if (!params.silent)
                            $cs.debug(1, "event: " + comp.path("/") + ": dispatch on " + state);
                        ev.state(state);
                        ev.decline(false);
                        var args = _cs.concat(
                            s.origin  ? [ origin ] : [],
                            s.noevent ? [] : [ ev ],
                            s.args,
                            params.args
                        );
                        var result = s.func.apply(s.ctx, args);
                        if (s.noevent && _cs.isdefined(result))
                            ev.result(result);
                        if (!ev.decline()) {
                            ev.dispatched(true);
                            if (params.firstonly)
                                ev.propagation(false);
                        }
                    }
                }
            };

            /*  helper function for dispatching event to all components on hierarchy path  */
            var event_dispatch_all = function (ev, comp, params) {
                /*  determine component tree path  */
                var comp_path;
                if (params.capturing || params.bubbling)
                    comp_path = comp.path();

                /*  phase 1: CAPTURING
                    optionally dispatch event downwards from root component
                    towards target component for capturing subscribers  */
                if (params.capturing) {
                    for (i = comp_path.length - 1; i >= 1; i--) {
                        event_dispatch_single(ev, comp, comp_path[i], params, "capturing");
                        if (!ev.propagation())
                            break;
                    }
                }

                /*  phase 2: TARGETING
                    dispatch event to target component  */
                if (ev.propagation())
                    event_dispatch_single(ev, comp, comp, params, "targeting");

                /*  phase 3: BUBBLING
                    dispatch event upwards from target component towards
                    root component for bubbling (regular) subscribers  */
                if (params.bubbling && ev.propagation()) {
                    for (i = 1; i < comp_path.length; i++) {
                        event_dispatch_single(ev, comp, comp_path[i], params, "bubbling");
                        if (!ev.propagation())
                            break;
                    }
                }

                /*  notify publisher on dispatch completion  */
                params.completed.call(comp, ev);
            };

            /*  perform event publishing,
                either asynchronous or synchronous  */
            if (ev.async())
                setTimeout(function () { event_dispatch_all(ev, self, params); }, 0);
            else
                event_dispatch_all(ev, self, params);

            /*  return the event or directly the result value  */
            return (params.directresult ? ev.result() : ev);
        }
    }
});

<|endoftext|>


<commit_before>'use strict';

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-read-only-property' );
var isObject = require( '@stdlib/utils/is-plain-object' );
var randn = require( '@stdlib/math/base/random/randn' );
var isnan = require( '@stdlib/math/base/utils/is-nan' );
var validate = require( './validate.js' );
var normal0 = require( './_normal.js' );

// MAIN //

/**
* Returns a pseudorandom number generator for generating normally distributed random numbers.
*
* @param {number} [mu] - mean
* @param {PositiveNumber} [sigma] - standard deviation
* @param {Options} [options] - function options
* @param {*} [options.seed] - pseudorandom number generator seed
* @throws {TypeError} `mu` must be a number
* @throws {TypeError} `sigma` must be a positive number
* @throws {TypeError} options must be an object
* @returns {Function} pseudorandom number generator
*
* @example
* var normal = factory( 0.0, 1.0 );
* var v = normal();
* // returns <number>
*
* @example
* var normal = factory( -3.0, 0.5, {
*     'seed': 297
* });
* var v = normal();
* // returns <number>
*/
function factory() {
	var sigma;
	var opts;
	var rand;
	var prng;
	var err;
	var mu;

	if ( arguments.length === 0 ) {
		rand = randn.factory();
	} else if ( arguments.length === 1 ) {
		opts = arguments[ 0 ];
		if ( !isObject( opts ) ) {
			throw new TypeError( 'invalid input argument. Options argument must be an object. Value: `' + opts + '`.' );
		}
		rand = randn.factory( opts );
	} else {
		mu = arguments[ 0 ];
		sigma = arguments[ 1 ];
		err = validate( mu, sigma );
		if ( err ) {
			throw err;
		}
		if ( arguments.length > 2 ) {
			opts = arguments[ 2 ];
			if ( !isObject( opts ) ) {
				throw new TypeError( 'invalid input argument. Options argument must be an object. Value: `' + opts + '`.' );
			}
			rand = randn.factory( opts );
		} else {
			rand = randn.factory();
		}
	}
	if ( mu === void 0 ) {
		prng = normal2;
	} else {
		prng = normal1;
	}
	setReadOnly( prng, 'NAME', 'normal' );
	setReadOnly( prng, 'SEED', rand.SEED );
	setReadOnly( prng, 'PRNG', rand );

	return prng;

	/**
	* Returns a pseudorandom number from a normal distribution with bound parameters `mu` and `sigma`.
	*
	* @private
	* @returns {number} pseudorandom number
	*
	* @example
	* var v = normal1();
	* // returns <number>
	*/
	function normal1() {
		return normal0( rand, mu, sigma );
	} // end FUNCTION normal1()

	/**
	* Returns a normally distributed pseudorandom number with mean `mu` and standard deviation `sigma`.
	*
	* @private
	* @param {number} mu - mean
	* @param {PositiveNumber} sigma - standard deviation
	* @returns {number} pseudorandom number
	*
	* @example
	* var v = normal2( 0.0, 1.0 );
	* // returns <number>
	*
	* @example
	* var v = normal2( 0.0, -1.0 );
	* // returns NaN
	*/
	function normal2( mu, sigma ) {
		if (
			isnan( mu ) ||
			isnan( sigma ) ||
			sigma <= 0.0
		) {
			return NaN;
		}
		return normal0( rand, mu, sigma );
	} // end FUNCTION normal2()
} // end FUNCTION factory()

// EXPORTS //

module.exports = factory;
<commit_msg>Alias method directly<commit_after>'use strict';

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-read-only-property' );
var isObject = require( '@stdlib/utils/is-plain-object' );
var randn = require( '@stdlib/math/base/random/randn' ).factory;
var isnan = require( '@stdlib/math/base/utils/is-nan' );
var validate = require( './validate.js' );
var normal0 = require( './_normal.js' );

// MAIN //

/**
* Returns a pseudorandom number generator for generating normally distributed random numbers.
*
* @param {number} [mu] - mean
* @param {PositiveNumber} [sigma] - standard deviation
* @param {Options} [options] - function options
* @param {*} [options.seed] - pseudorandom number generator seed
* @throws {TypeError} `mu` must be a number
* @throws {TypeError} `sigma` must be a positive number
* @throws {TypeError} options must be an object
* @returns {Function} pseudorandom number generator
*
* @example
* var normal = factory( 0.0, 1.0 );
* var v = normal();
* // returns <number>
*
* @example
* var normal = factory( -3.0, 0.5, {
*     'seed': 297
* });
* var v = normal();
* // returns <number>
*/
function factory() {
	var sigma;
	var opts;
	var rand;
	var prng;
	var err;
	var mu;

	if ( arguments.length === 0 ) {
		rand = randn();
	} else if ( arguments.length === 1 ) {
		opts = arguments[ 0 ];
		if ( !isObject( opts ) ) {
			throw new TypeError( 'invalid input argument. Options argument must be an object. Value: `' + opts + '`.' );
		}
		rand = randn( opts );
	} else {
		mu = arguments[ 0 ];
		sigma = arguments[ 1 ];
		err = validate( mu, sigma );
		if ( err ) {
			throw err;
		}
		if ( arguments.length > 2 ) {
			opts = arguments[ 2 ];
			if ( !isObject( opts ) ) {
				throw new TypeError( 'invalid input argument. Options argument must be an object. Value: `' + opts + '`.' );
			}
			rand = randn( opts );
		} else {
			rand = randn();
		}
	}
	if ( mu === void 0 ) {
		prng = normal2;
	} else {
		prng = normal1;
	}
	setReadOnly( prng, 'NAME', 'normal' );
	setReadOnly( prng, 'SEED', rand.SEED );
	setReadOnly( prng, 'PRNG', rand );

	return prng;

	/**
	* Returns a pseudorandom number from a normal distribution with bound parameters `mu` and `sigma`.
	*
	* @private
	* @returns {number} pseudorandom number
	*
	* @example
	* var v = normal1();
	* // returns <number>
	*/
	function normal1() {
		return normal0( rand, mu, sigma );
	} // end FUNCTION normal1()

	/**
	* Returns a normally distributed pseudorandom number with mean `mu` and standard deviation `sigma`.
	*
	* @private
	* @param {number} mu - mean
	* @param {PositiveNumber} sigma - standard deviation
	* @returns {number} pseudorandom number
	*
	* @example
	* var v = normal2( 0.0, 1.0 );
	* // returns <number>
	*
	* @example
	* var v = normal2( 0.0, -1.0 );
	* // returns NaN
	*/
	function normal2( mu, sigma ) {
		if (
			isnan( mu ) ||
			isnan( sigma ) ||
			sigma <= 0.0
		) {
			return NaN;
		}
		return normal0( rand, mu, sigma );
	} // end FUNCTION normal2()
} // end FUNCTION factory()

// EXPORTS //

module.exports = factory;
<|endoftext|>


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

	// Configure RequireJS to shim Jasmine
	requirejs.config({
		baseUrl: "./",
		paths: {
			'jasmine': 'node_modules/jasmine-core/lib/jasmine-core/jasmine',
			'jasmine-html': 'node_modules/jasmine-core/lib/jasmine-core/jasmine-html',
			'boot': 'node_modules/jasmine-core/lib/jasmine-core/boot',
			'squire': 'node_modules/squirejs/src/Squire'
		},
		map: {
			"*": {
				"stub": "js/stub"/*,
				"foo": "js/stub",
				"hello": "js/stub"*/
			}
		},
		shim: {
			'jasmine': {
				exports: 'jasmine'
			},
			'jasmine-html': {
				deps: ['jasmine'],
				exports: 'jasmine'
			},
			'boot': {
				deps: ['jasmine', 'jasmine-html'],
				exports: 'jasmine'
			},
			"squire": {
				exports: "squire"
			}
		},
		urlArgs: "bust=" + (new Date()).getTime()
	});

	// Load Jasmine - This will still create all of the normal Jasmine browser globals unless `boot.js` is re-written to use the
	// AMD or UMD specs. `boot.js` will do a bunch of configuration and attach it's initializers to `window.onload()`. Because
	// we are using RequireJS `window.onload()` has already been triggered so we have to manually call it again. This will
	// initialize the HTML Reporter and execute the environment.
	require(['boot'], function () {

		// Load the specs
		require([
			"spec/stub-spec"
		], function () {

			// Initialize the HTML Reporter and execute the environment (setup by `boot.js`)
			window.onload();
		});
	});
})();<commit_msg>update<commit_after>(function () {
	'use strict';

	// Configure RequireJS to shim Jasmine
	requirejs.config({
		baseUrl: "./",
		paths: {
			'jasmine': 'node_modules/jasmine-core/lib/jasmine-core/jasmine',
			'jasmine-html': 'node_modules/jasmine-core/lib/jasmine-core/jasmine-html',
			'boot': 'node_modules/jasmine-core/lib/jasmine-core/boot',
			'squire': 'node_modules/squirejs/src/Squire'
		},
		shim: {
			'jasmine': {
				exports: 'jasmine'
			},
			'jasmine-html': {
				deps: ['jasmine'],
				exports: 'jasmine'
			},
			'boot': {
				deps: ['jasmine', 'jasmine-html'],
				exports: 'jasmine'
			},
			"squire": {
				exports: "squire"
			}
		},
		urlArgs: "bust=" + (new Date()).getTime()
	});

	// Load Jasmine - This will still create all of the normal Jasmine browser globals unless `boot.js` is re-written to use the
	// AMD or UMD specs. `boot.js` will do a bunch of configuration and attach it's initializers to `window.onload()`. Because
	// we are using RequireJS `window.onload()` has already been triggered so we have to manually call it again. This will
	// initialize the HTML Reporter and execute the environment.
	require(['boot'], function () {

		// Load the specs
		require([
			"spec/stub-spec"
		], function () {

			// Initialize the HTML Reporter and execute the environment (setup by `boot.js`)
			window.onload();
		});
	});
})();<|endoftext|>