<commit_before>'use strict';
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');
var path = require('path');
var fs = require('fs');
var mkdirp = require('mkdirp');

module.exports = yeoman.generators.Base.extend({
  prompting: function () {
    var done = this.async();

    // Have Yeoman greet the user.
    this.log(yosay(
      'Welcome to the praiseworthy ' + chalk.yellow('Nachos') + ' generator!'
    ));

    var prompts = [{
      type    : 'input',
      name    : 'name',
      message : 'What is your Taco\'s name?',
      default : this.appname
    },
    {
      type    : 'input',
      name    : 'description',
      message : 'What does your Taco do?',
      default : 'El loco Taco'
    },
    {
      type    : 'input',
      name    : 'clientFolder',
      message : 'How would you like your client folder to be named?',
      default : 'client'
    }];

    this.prompt(prompts, function (answers) {
      this.name = answers.name;
      this.description = answers.description;
      this.clientFolder = answers.clientFolder;

      done();
    }.bind(this));
  },

  writing: {
    app: function () {
      this.fs.copyTpl(
        this.templatePath('_package.json'),
        this.destinationPath('package.json'),
        { name: this.name,
          description: this.description }
      );
      this.fs.copyTpl(
        this.templatePath('_bower.json'),
        this.destinationPath('bower.json'),
        { name: this.name}
      );
      this.fs.copyTpl(
        this.templatePath('_.bowerrc'),
        this.destinationPath('.bowerrc'),
        { clientFolder: this.clientFolder }
      );
      this.fs.copyTpl(
        this.templatePath('_gulpfile.js'),
        this.destinationPath('gulpfile.js'),
        { clientFolder: this.clientFolder  }
      );
      this.fs.copyTpl(
        this.templatePath('_nwPackage.json'),
        this.destinationPath(path.join(this.clientFolder,'package.json')),
        { name: this.name,
          description: this.description }
      );
      this.fs.copy(
        this.templatePath('index.html'),
        this.destinationPath(path.join(this.clientFolder,'index.html') )
      );
      this.fs.copy(
        this.templatePath('_app.less'),
        this.destinationPath(path.join(path.join(this.clientFolder, 'app'),'app.less') )
      );

      // Create the bower folder empty so that wiredep wont go crazy
      var bowerFolder = path.join(path.join(this.destinationRoot(), this.clientFolder), 'bower_components');
      mkdirp(bowerFolder, function(err){
        if (err)
          console.log(err);
      });
    },

    projectfiles: function () {
      this.fs.copy(
        this.templatePath('editorconfig'),
        this.destinationPath('.editorconfig')
      );
      this.fs.copy(
        this.templatePath('jshintrc'),
        this.destinationPath('.jshintrc')
      );
    }
  },

  install: function () {
    this.log(yosay('Installing dependencies, this might take a while'))
    this.npmInstall(['del','gulp','gulp-inject','gulp-jshint','gulp-less','gulp-livereload',
                     'gulp-util','jshint-stylish','lazypipe','run-sequence','wiredep'], { 'saveDev': true })
    this.npmInstall(['nw'], { 'save': true});
  }
});
<commit_msg>Required dependencies for angular-material<commit_after>'use strict';
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');
var path = require('path');
var fs = require('fs');
var mkdirp = require('mkdirp');

module.exports = yeoman.generators.Base.extend({
  prompting: function () {
    var done = this.async();

    // Have Yeoman greet the user.
    this.log(yosay(
      'Welcome to the praiseworthy ' + chalk.yellow('Nachos') + ' generator!'
    ));

    var prompts = [{
      type    : 'input',
      name    : 'name',
      message : 'What is your Taco\'s name?',
      default : this.appname
    },
    {
      type    : 'input',
      name    : 'description',
      message : 'What does your Taco do?',
      default : 'El loco Taco'
    },
    {
      type    : 'input',
      name    : 'clientFolder',
      message : 'How would you like your client folder to be named?',
      default : 'client'
    },
    {
      type    : 'confirm',
      name    : 'isMaterial',
      message : 'Would you like angular-material to be a part of your app?',
      default : true
    }];

    this.prompt(prompts, function (answers) {
      this.name = answers.name;
      this.description = answers.description;
      this.clientFolder = answers.clientFolder;
      this.isMaterial = answers.isMaterial;

      done();
    }.bind(this));
  },

  writing: {
    app: function () {
      this.fs.copyTpl(
        this.templatePath('_package.json'),
        this.destinationPath('package.json'),
        { name: this.name,
          description: this.description }
      );
      this.fs.copyTpl(
        this.templatePath('_bower.json'),
        this.destinationPath('bower.json'),
        { name: this.name}
      );
      this.fs.copyTpl(
        this.templatePath('_.bowerrc'),
        this.destinationPath('.bowerrc'),
        { clientFolder: this.clientFolder }
      );
      this.fs.copyTpl(
        this.templatePath('_gulpfile.js'),
        this.destinationPath('gulpfile.js'),
        { clientFolder: this.clientFolder  }
      );
      this.fs.copyTpl(
        this.templatePath('_nwPackage.json'),
        this.destinationPath(path.join(this.clientFolder,'package.json')),
        { name: this.name,
          description: this.description }
      );
      this.fs.copy(
        this.templatePath('index.html'),
        this.destinationPath(path.join(this.clientFolder,'index.html') )
      );
      this.fs.copy(
        this.templatePath('_app.less'),
        this.destinationPath(path.join(path.join(this.clientFolder, 'app'),'app.less') )
      );

      // Create the bower folder empty so that wiredep wont go crazy
      var bowerFolder = path.join(path.join(this.destinationRoot(), this.clientFolder), 'bower_components');
      mkdirp(bowerFolder, function(err){
        if (err)
          console.log(err);
      });
    },

    projectfiles: function () {
      this.fs.copy(
        this.templatePath('editorconfig'),
        this.destinationPath('.editorconfig')
      );
      this.fs.copy(
        this.templatePath('jshintrc'),
        this.destinationPath('.jshintrc')
      );
    }
  },

  install: function () {
    this.log(yosay('Installing dependencies, this might take a while'))
    this.npmInstall(['del','gulp','gulp-inject','gulp-jshint','gulp-less','gulp-livereload',
                     'gulp-util','jshint-stylish','lazypipe','run-sequence','wiredep'], { 'saveDev': true })
    this.npmInstall(['nw'], { 'save': true});

    if(this.isMaterial)
      this.bowerInstall(['angular','angular-material','mdi','angular-ui-router'], { 'save': true });
  }
});
<|endoftext|>


<commit_before>// The Java "NervousText" example ported to JavaScript.
// Compile using java org.mozilla.tools.jsc.Main -extends java.applet.Applet -implements java.lang.Runnable NervousText.js
/*
Adapted from Java code by
    Daniel Wyszynski
    Center for Applied Large-Scale Computing (CALC)
    04-12-95

    Test of text animation.

    kwalrath: Changed string; added thread suspension. 5-9-95
*/
var Font = java.awt.Font;
var Thread = java.lang.Thread;
var separated;
var s = null;
var killme = null;
var i;
var x_coord = 0, y_coord = 0;
var num;
var speed=35;
var counter =0;
var threadSuspended = false; //added by kwalrath

function init() {
        resize(150,50);
        setFont(new Font("TimesRoman",Font.BOLD,36));
        s = getParameter("text");
        if (s == null) {
            s = "Rhino";
        }
        separated = s.split('');
}

function start() {
        if(killme == null)
        {
        killme = new java.lang.Thread(java.lang.Runnable(this));
        killme.start();
        }
}

function stop() {
        killme = null;
}

function run() {
        while (killme != null) {
        try {Thread.sleep(100);} catch (e){}
        repaint();
        }
        killme = null;
}

function paint(g) {
        for(i=0;i<separated.length;i++)
        {
        x_coord = Math.random()*10+15*i;
        y_coord = Math.random()*10+36;
        g.drawChars(separated, i,1,x_coord,y_coord);
        }
}

/* Added by kwalrath. */
function mouseDown(evt, x, y) {
        if (threadSuspended) {
            killme.resume();
        }
        else {
            killme.suspend();
        }
        threadSuspended = !threadSuspended;
    return true;
}

<commit_msg>Fix class path<commit_after>// The Java "NervousText" example ported to JavaScript.
// Compile using java org.mozilla..javascript.tools.jsc.Main -extends java.applet.Applet -implements java.lang.Runnable NervousText.js
/*
Adapted from Java code by
    Daniel Wyszynski
    Center for Applied Large-Scale Computing (CALC)
    04-12-95

    Test of text animation.

    kwalrath: Changed string; added thread suspension. 5-9-95
*/
var Font = java.awt.Font;
var Thread = java.lang.Thread;
var separated;
var s = null;
var killme = null;
var i;
var x_coord = 0, y_coord = 0;
var num;
var speed=35;
var counter =0;
var threadSuspended = false; //added by kwalrath

function init() {
        resize(150,50);
        setFont(new Font("TimesRoman",Font.BOLD,36));
        s = getParameter("text");
        if (s == null) {
            s = "Rhino";
        }
        separated = s.split('');
}

function start() {
        if(killme == null)
        {
        killme = new java.lang.Thread(java.lang.Runnable(this));
        killme.start();
        }
}

function stop() {
        killme = null;
}

function run() {
        while (killme != null) {
        try {Thread.sleep(100);} catch (e){}
        repaint();
        }
        killme = null;
}

function paint(g) {
        for(i=0;i<separated.length;i++)
        {
        x_coord = Math.random()*10+15*i;
        y_coord = Math.random()*10+36;
        g.drawChars(separated, i,1,x_coord,y_coord);
        }
}

/* Added by kwalrath. */
function mouseDown(evt, x, y) {
        if (threadSuspended) {
            killme.resume();
        }
        else {
            killme.suspend();
        }
        threadSuspended = !threadSuspended;
    return true;
}

<|endoftext|>


<commit_before>var assert = require('assert');

var RES_NACK     = exports.RES_NACK     = 1;
var REQ_PROPOSE  = exports.REQ_PROPOSE  = 10;
var RES_PROPOSED = exports.RES_PROPOSED = 11;
var REQ_ACCEPT   = exports.REQ_ACCEPT   = 20;
var RES_ACCEPTED = exports.RES_ACCEPTED = 21;

exports.proposer = function(node_name, node_restarts, slot,
                            acceptors, comm, opts) {
  assert(node_name != null);
  assert(node_restarts > 0);
  assert(acceptors.length > 0);

  opts = opts || {};
  var proposer_timeout = opts.proposer_timeout || 3000; // In milliseconds.
  var quorum           = opts.quorum || majority;

  var tot_propose_phase       = 0; // Stats counters.
  var tot_propose_phase_loop  = 0;
  var tot_propose_send        = 0;
  var tot_propose_recv        = 0;
  var tot_propose_recv_err    = 0;
  var tot_propose_vote        = 0;
  var tot_propose_vote_repeat = 0;
  var tot_propose_timeout     = 0;

  function propose(val, cb) {
    var self = {};
    var timer = null;
    var ballot = next_ballot();

    // Run through two similar, sequential phases: propose & accept.
    //
    phase(REQ_PROPOSE, RES_PROPOSED, {},
          function(err, info) {
            if (err) {
              cb(err, info);
            } else {
              phase(REQ_ACCEPT, RES_ACCEPTED, { "val": val }, cb);
            }
          });

    function phase(kind, yea_kind, req, cb_phase) {
      tot_propose_phase = tot_propose_phase + 1;

      req.slot   = slot;
      req.kind   = kind;
      req.ballot = ballot;
      req.sender = node_name;
      comm.broadcast(acceptors, req);
      tot_propose_send = tot_propose_send + acceptors.length;
      restart_timer();

      var yea_needed = quorum(acceptors.length);
      var nay_needed = acceptors.length - yea_needed + 1;

      var tally = {};
      tally[yea_kind] = [ [], yea_needed, null ];
      tally[RES_NACK] = [ [], nay_needed, "rejected" ];

      self.on_msg = function(src, res) {
        tot_propose_recv = tot_propose_recv + 1;

        if (!timer) {
          return; // Drop/ignore late messages.
        }

        if (timer) {
          clearTimeout(timer);
        }
        timer = null;

        if (opts.msg_preprocess) {
          res = opts.msg_preprocess(src, res);
        }

        // Stop when recv()'ed votes reach tally quorum, either yea or nay.
        //
        if (is_member(acceptors, src) &&
            res != null &&
            ballot_eq(res.ballot, ballot) &&
            tally[res.kind] != null) {
          var vkind = tally[res.kind];
          var votes = vkind[0];
          if (!is_member(votes, src)) {
            tot_propose_vote = tot_propose_vote + 1;
            votes[votes.length] = src;
            if (votes.length >= vkind[1]) {
              if (opts.on_phase_complete) {
                opts.on_phase_complete(yea_kind, vkind[2]);
              }

              cb_phase(vkind[2],
                       { "highest_proposed_ballot": res.highest_proposed_ballot,
                         "accepted_ballot":         res.accepted_ballot,
                         "accepted_val":            res.accepted_val });
              return;
            }
          } else {
            tot_propose_vote_repeat = tot_propose_vote_repeat + 1;
          }
        } else {
          tot_propose_recv_err = tot_propose_recv_err + 1;
        }

        tot_propose_phase_loop = tot_propose_phase_loop + 1;
        restart_timer();
      }

      function restart_timer() {
        assert(!timer);
        timer = setTimeout(function() {
                             tot_propose_timeout = tot_propose_timeout + 1;
                             if (timer != null) {
                               timer = null;
                               cb_phase('timeout');
                             }
                           }, proposer_timeout);
      }
    }

    return self; // Provids a self.on_msg(src, msg) function.
  }

  var cur_ballot = ballot_mk(-1, node_name, node_restarts);
  function next_ballot() {
    cur_ballot = ballot_inc(cur_ballot);
    return cur_ballot;
  }

  function stats() {
    return { "tot_propose_phase"       : tot_propose_phase,
             "tot_propose_phase_loop"  : tot_propose_phase_loop,
             "tot_propose_send"        : tot_propose_send,
             "tot_propose_recv"        : tot_propose_recv,
             "tot_propose_recv_err"    : tot_propose_recv_err,
             "tot_propose_vote"        : tot_propose_vote,
             "tot_propose_vote_repeat" : tot_propose_vote_repeat,
             "tot_propose_timeout"     : tot_propose_timeout };
  }

  return { "propose": propose,
           "stats": stats };
};

// ----------------------------------------------------------------

exports.acceptor = function(storage, comm, opts) {
  opts = opts || {};
  var quorum = opts.quorum || majority;

  var tot_accept_bad_req      = 0; // Stats counters.
  var tot_accept_bad_req_kind = 0;
  var tot_accept_recv         = 0;
  var tot_accept_send         = 0;
  var tot_accept_propose      = 0;
  var tot_accept_proposed     = 0;
  var tot_accept_accept       = 0;
  var tot_accept_accepted     = 0;
  var tot_accept_nack_storage = 0;
  var tot_accept_nack_behind  = 0;

  function on_msg(src, req) {
    tot_accept_recv = tot_accept_recv + 1;
    if (req != null &&
        req.slot != null &&
        req.ballot != null) {
      // The acceptor's main responsibility is to process incoming
      // propose or accept requests with higher ballots.
      //
      storage.slot_read(req.slot, on_slot_read);

      function on_slot_read(err, slot_state) {
        if (!err) {
          slot_state = slot_state || {};

          var highest_proposed_ballot = slot_state.highest_proposed_ballot;

          if (ballot_gte(req.ballot, highest_proposed_ballot)) {
            if (req.kind == REQ_PROPOSE) {
              tot_accept_propose = tot_accept_propose + 1;
              storage.slot_save_highest_proposed_ballot(
                req.slot, req.ballot,
                function(err) {
                  if (!err) {
                    tot_accept_proposed = tot_accept_proposed + 1;
                    highest_proposed_ballot = req.ballot;
                    respond(RES_PROPOSED);
                  } else {
                    tot_accept_nack_storage = tot_accept_nack_storage + 1;
                    respond(RES_NACK);
                  }
                });
            } else if (req.kind == REQ_ACCEPT) {
              tot_accept_accept = tot_accept_accept + 1;
              storage.slot_save_accepted(
                req.slot, req.ballot, req.val,
                function(err) {
                  if (!err) {
                    tot_accept_accepted = tot_accept_accepted + 1;
                    highest_proposed_ballot = req.ballot;
                    respond(RES_ACCEPTED);
                  } else {
                    tot_accept_nack_storage = tot_accept_nack_storage + 1;
                    respond(RES_NACK);
                  }
                });
            } else {
              tot_accept_bad_req_kind = tot_accept_bad_req_kind + 1;
              respond(RES_NACK);
            }
          } else {
            tot_accept_nack_behind = tot_accept_nack_behind + 1;
            respond(RES_NACK);
          }

          function respond(kind, msg) {
            msg = msg || {};
            msg.highest_proposed_ballot = highest_proposed_ballot;
            respond_full(req, kind, msg);
          }
        } else {
          tot_accept_nack_storage = tot_accept_nack_storage + 1;
          respond_full(req, RES_NACK);
        }
      }
    } else {
      tot_accept_bad_req = tot_accept_bad_req + 1;
    }
  }

  function respond_full(req, kind, msg) {
    msg = msg || {};
    msg.kind = kind;
    msg.slot = req.slot;
    msg.ballot = req.ballot;
    if (opts.respond_preprocess) {
      msg = opts.respond_preproces(msg);
    }
    comm.send(req.sender, msg);
    tot_accept_send = tot_accept_send + 1;
  }

  function stats() {
    return { "tot_accept_bad_req"      : tot_accept_bad_req,
             "tot_accept_bad_req_kind" : tot_accept_bad_req_kind,
             "tot_accept_recv"         : tot_accept_recv,
             "tot_accept_send"         : tot_accept_send,
             "tot_accept_propose"      : tot_accept_propose,
             "tot_accept_proposed"     : tot_accept_proposed,
             "tot_accept_accept"       : tot_accept_accept,
             "tot_accept_accepted"     : tot_accept_accepted,
             "tot_accept_nack_storage" : tot_accept_nack_storage,
             "tot_accept_nack_behind"  : tot_accept_nack_behind };
  }

  return { "on_msg": on_msg,
           "stats":  stats };
};

// ----------------------------------------------------------------

function majority(n) {
  return Math.floor(n / 2) + 1;
}
exports.majority = majority;

function is_member(collection, item) {
  for (var i in collection) {
    if (collection[i] == item) {
      return true;
    }
  }
  return false;
}
exports.is_member = is_member;

// ----------------------------------------------------------------

var BALLOT_SEQ_NUM           = exports.BALLOT_SEQ_NUM           = 0;
var BALLOT_PROPOSER_NAME     = exports.BALLOT_PROPOSER_NAME     = 1;
var BALLOT_PROPOSER_RESTARTS = exports.BALLOT_PROPOSER_RESTARTS = 2;

function ballot_mk(seq_num, proposer_name, proposer_restarts) {
  return [seq_num, proposer_name, proposer_restarts];
}

var BOTTOM_BALLOT = ballot_mk(-1, -1, -1);

function ballot_inc(ballot) {
  return ballot_mk(ballot[BALLOT_SEQ_NUM] + 1,
                   ballot[BALLOT_PROPOSER_NAME],
                   ballot[BALLOT_PROPOSER_RESTARTS]);
}

function ballot_gte(a, b) { // Greater than or equal.
  a = a || BOTTOM_BALLOT;
  b = b || BOTTOM_BALLOT;
  for (var i = 0; i < Math.min(a.length, b.length); i++) {
    if (a[i] > b[i]) {
      return true;
    }
    if (a[i] < b[i]) {
      return false;
    }
  }
  return true;
}

function ballot_eq(a, b) {
  for (var i = 0; i < Math.min(a.length, b.length); i++) {
    if (a[i] != b[i]) {
      return false;
    }
  }
  return true;
}

exports.ballot_mk  = ballot_mk;
exports.ballot_inc = ballot_inc;
exports.ballot_gte = ballot_gte;
exports.ballot_eq  = ballot_eq;

<commit_msg>Whitespace.<commit_after>var assert = require('assert');

var RES_NACK     = exports.RES_NACK     = 1;
var REQ_PROPOSE  = exports.REQ_PROPOSE  = 10;
var RES_PROPOSED = exports.RES_PROPOSED = 11;
var REQ_ACCEPT   = exports.REQ_ACCEPT   = 20;
var RES_ACCEPTED = exports.RES_ACCEPTED = 21;

exports.proposer = function(node_name, node_restarts, slot,
                            acceptors, comm, opts) {
  assert(node_name != null);
  assert(node_restarts > 0);
  assert(acceptors.length > 0);

  opts = opts || {};
  var proposer_timeout = opts.proposer_timeout || 3000; // In milliseconds.
  var quorum           = opts.quorum || majority;

  var tot_propose_phase       = 0; // Stats counters.
  var tot_propose_phase_loop  = 0;
  var tot_propose_send        = 0;
  var tot_propose_recv        = 0;
  var tot_propose_recv_err    = 0;
  var tot_propose_vote        = 0;
  var tot_propose_vote_repeat = 0;
  var tot_propose_timeout     = 0;

  function propose(val, cb) {
    var self = {};
    var timer = null;
    var ballot = next_ballot();

    // Run through two similar, sequential phases: propose & accept.
    //
    phase(REQ_PROPOSE, RES_PROPOSED, {},
          function(err, info) {
            if (err) {
              cb(err, info);
            } else {
              phase(REQ_ACCEPT, RES_ACCEPTED, { "val": val }, cb);
            }
          });

    function phase(kind, yea_kind, req, cb_phase) {
      tot_propose_phase = tot_propose_phase + 1;

      req.slot   = slot;
      req.kind   = kind;
      req.ballot = ballot;
      req.sender = node_name;
      comm.broadcast(acceptors, req);
      tot_propose_send = tot_propose_send + acceptors.length;
      restart_timer();

      var yea_needed = quorum(acceptors.length);
      var nay_needed = acceptors.length - yea_needed + 1;

      var tally = {};
      tally[yea_kind] = [ [], yea_needed, null ];
      tally[RES_NACK] = [ [], nay_needed, "rejected" ];

      self.on_msg = function(src, res) {
        tot_propose_recv = tot_propose_recv + 1;

        if (!timer) {
          return; // Drop/ignore late messages.
        }
        if (timer) {
          clearTimeout(timer);
        }
        timer = null;

        if (opts.msg_preprocess) {
          res = opts.msg_preprocess(src, res);
        }

        // Stop when recv()'ed votes reach tally quorum, either yea or nay.
        //
        if (is_member(acceptors, src) &&
            res != null &&
            ballot_eq(res.ballot, ballot) &&
            tally[res.kind] != null) {
          var vkind = tally[res.kind];
          var votes = vkind[0];

          if (!is_member(votes, src)) {
            tot_propose_vote = tot_propose_vote + 1;
            votes[votes.length] = src;
            if (votes.length >= vkind[1]) {
              if (opts.on_phase_complete) {
                opts.on_phase_complete(yea_kind, vkind[2]);
              }
              cb_phase(vkind[2],
                       { "highest_proposed_ballot": res.highest_proposed_ballot,
                         "accepted_ballot":         res.accepted_ballot,
                         "accepted_val":            res.accepted_val });
              return;
            }
          } else {
            tot_propose_vote_repeat = tot_propose_vote_repeat + 1;
          }
        } else {
          tot_propose_recv_err = tot_propose_recv_err + 1;
        }

        tot_propose_phase_loop = tot_propose_phase_loop + 1;
        restart_timer();
      }

      function restart_timer() {
        assert(!timer);
        timer = setTimeout(function() {
                             tot_propose_timeout = tot_propose_timeout + 1;
                             if (timer != null) {
                               timer = null;
                               cb_phase('timeout');
                             }
                           }, proposer_timeout);
      }
    }

    return self; // Provids a self.on_msg(src, msg) function.
  }

  var cur_ballot = ballot_mk(-1, node_name, node_restarts);
  function next_ballot() {
    cur_ballot = ballot_inc(cur_ballot);
    return cur_ballot;
  }

  function stats() {
    return { "tot_propose_phase"       : tot_propose_phase,
             "tot_propose_phase_loop"  : tot_propose_phase_loop,
             "tot_propose_send"        : tot_propose_send,
             "tot_propose_recv"        : tot_propose_recv,
             "tot_propose_recv_err"    : tot_propose_recv_err,
             "tot_propose_vote"        : tot_propose_vote,
             "tot_propose_vote_repeat" : tot_propose_vote_repeat,
             "tot_propose_timeout"     : tot_propose_timeout };
  }

  return { "propose": propose, "stats": stats };
};

// ----------------------------------------------------------------

exports.acceptor = function(storage, comm, opts) {
  opts = opts || {};
  var quorum = opts.quorum || majority;

  var tot_accept_bad_req      = 0; // Stats counters.
  var tot_accept_bad_req_kind = 0;
  var tot_accept_recv         = 0;
  var tot_accept_send         = 0;
  var tot_accept_propose      = 0;
  var tot_accept_proposed     = 0;
  var tot_accept_accept       = 0;
  var tot_accept_accepted     = 0;
  var tot_accept_nack_storage = 0;
  var tot_accept_nack_behind  = 0;

  function on_msg(src, req) {
    tot_accept_recv = tot_accept_recv + 1;
    if (req != null &&
        req.slot != null &&
        req.ballot != null) {
      // The acceptor's main responsibility is to process incoming
      // propose or accept requests with higher ballots.
      //
      storage.slot_read(req.slot, on_slot_read);

      function on_slot_read(err, slot_state) {
        if (!err) {
          var highest_proposed_ballot = slot_state.highest_proposed_ballot;

          if (ballot_gte(req.ballot, highest_proposed_ballot)) {
            if (req.kind == REQ_PROPOSE) {
              tot_accept_propose = tot_accept_propose + 1;
              storage.slot_save_highest_proposed_ballot(
                req.slot, req.ballot,
                function(err) {
                  if (!err) {
                    tot_accept_proposed = tot_accept_proposed + 1;
                    highest_proposed_ballot = req.ballot;
                    respond(RES_PROPOSED);
                  } else {
                    tot_accept_nack_storage = tot_accept_nack_storage + 1;
                    respond(RES_NACK);
                  }
                });
            } else if (req.kind == REQ_ACCEPT) {
              tot_accept_accept = tot_accept_accept + 1;
              storage.slot_save_accepted(
                req.slot, req.ballot, req.val,
                function(err) {
                  if (!err) {
                    tot_accept_accepted = tot_accept_accepted + 1;
                    highest_proposed_ballot = req.ballot;
                    respond(RES_ACCEPTED);
                  } else {
                    tot_accept_nack_storage = tot_accept_nack_storage + 1;
                    respond(RES_NACK);
                  }
                });
            } else {
              tot_accept_bad_req_kind = tot_accept_bad_req_kind + 1;
              respond(RES_NACK);
            }
          } else {
            tot_accept_nack_behind = tot_accept_nack_behind + 1;
            respond(RES_NACK);
          }

          function respond(kind, msg) {
            msg = msg || {};
            msg.highest_proposed_ballot = highest_proposed_ballot;
            respond_full(req, kind, msg);
          }
        } else {
          tot_accept_nack_storage = tot_accept_nack_storage + 1;
          respond_full(req, RES_NACK, {});
        }
      }
    } else {
      tot_accept_bad_req = tot_accept_bad_req + 1;
    }
  }

  function respond_full(req, kind, msg) {
    msg.kind = kind;
    msg.slot = req.slot;
    msg.ballot = req.ballot;
    if (opts.respond_preprocess) {
      msg = opts.respond_preproces(msg);
    }
    comm.send(req.sender, msg);
    tot_accept_send = tot_accept_send + 1;
  }

  function stats() {
    return { "tot_accept_bad_req"      : tot_accept_bad_req,
             "tot_accept_bad_req_kind" : tot_accept_bad_req_kind,
             "tot_accept_recv"         : tot_accept_recv,
             "tot_accept_send"         : tot_accept_send,
             "tot_accept_propose"      : tot_accept_propose,
             "tot_accept_proposed"     : tot_accept_proposed,
             "tot_accept_accept"       : tot_accept_accept,
             "tot_accept_accepted"     : tot_accept_accepted,
             "tot_accept_nack_storage" : tot_accept_nack_storage,
             "tot_accept_nack_behind"  : tot_accept_nack_behind };
  }

  return { "on_msg": on_msg, "stats": stats };
};

// ----------------------------------------------------------------

function majority(n) {
  return Math.floor(n / 2) + 1;
}
exports.majority = majority;

function is_member(collection, item) {
  for (var i in collection) {
    if (collection[i] == item) {
      return true;
    }
  }
  return false;
}
exports.is_member = is_member;

// ----------------------------------------------------------------

var BALLOT_SEQ_NUM           = exports.BALLOT_SEQ_NUM           = 0;
var BALLOT_PROPOSER_NAME     = exports.BALLOT_PROPOSER_NAME     = 1;
var BALLOT_PROPOSER_RESTARTS = exports.BALLOT_PROPOSER_RESTARTS = 2;

function ballot_mk(seq_num, proposer_name, proposer_restarts) {
  return [seq_num, proposer_name, proposer_restarts];
}

var BOTTOM_BALLOT = ballot_mk(-1, -1, -1);

function ballot_inc(ballot) {
  return ballot_mk(ballot[BALLOT_SEQ_NUM] + 1,
                   ballot[BALLOT_PROPOSER_NAME],
                   ballot[BALLOT_PROPOSER_RESTARTS]);
}

function ballot_gte(a, b) { // Greater than or equal.
  a = a || BOTTOM_BALLOT;
  b = b || BOTTOM_BALLOT;
  for (var i = 0; i < Math.min(a.length, b.length); i++) {
    if (a[i] > b[i]) {
      return true;
    }
    if (a[i] < b[i]) {
      return false;
    }
  }
  return true;
}

function ballot_eq(a, b) {
  for (var i = 0; i < Math.min(a.length, b.length); i++) {
    if (a[i] != b[i]) {
      return false;
    }
  }
  return true;
}

exports.ballot_mk  = ballot_mk;
exports.ballot_inc = ballot_inc;
exports.ballot_gte = ballot_gte;
exports.ballot_eq  = ballot_eq;
<|endoftext|>


<commit_before>if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/sw.js').then(function() {
    console.log('service worker is is all cool.');
  }).catch(function(e) {
    console.error('service worker is not so cool.', e);
    throw e;
  });
}

/* global $ */

(function() {
  'use strict';

  var from, to, when, data = {};

  function is_defined(obj) {
    return typeof (obj) !== 'undefined';
  }

  function saveScheduleSelection() {
    localStorage.setItem('caltrain-schedule-from', $('#from select').val());
    localStorage.setItem('caltrain-schedule-to', $('#to select').val());
    localStorage.setItem('caltrain-schedule-when', $('.when-button.selected').val());
  }

  function select(elm, val) {
    elm[0].selectedIndex = elm.find('option[value="' + val + '"]').index();
  }

  function loadPreviousSettings() {
    if (is_defined(localStorage.getItem('caltrain-schedule-from'))) {
      select($('#from select'), localStorage.getItem('caltrain-schedule-from'));
    }
    if (is_defined(localStorage.getItem('caltrain-schedule-to'))) {
      select($('#to select'), localStorage.getItem('caltrain-schedule-to'));
    }
    if (is_defined(localStorage.getItem('caltrain-schedule-when'))) {
      $('.when-button').removeClass('selected');
      $('.when-button[value="' + localStorage.getItem('caltrain-schedule-when') + '"]').addClass('selected');
    }
  }

  String.prototype.repeat = function(num) {
    return (num <= 0) ? '' : this + this.repeat(num - 1);
  };

  String.prototype.rjust = function(width, padding) {
    padding = (padding || ' ').substr(0, 1); // one and only one char
    return padding.repeat(width - this.length) + this;
  };

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

  // now in seconds since the midnight
  function now() {
    var date = new Date();
    return date.getHours() * 60 * 60 +
           date.getMinutes() * 60 +
           date.getSeconds();
  }

  // now date in format YYYYMMDD
  function now_date() {
    var d = new Date();
    // getMonth starts from 0
    return parseInt([d.getFullYear(), d.getMonth() + 1, d.getDate()].map(function(n) {
      return n.toString().rjust(2, '0');
    }).join(''));
  }

  function second2str(seconds) {
    var minutes = Math.floor(seconds / 60);
    return [
      Math.floor(minutes / 60),
      minutes % 60
    ].map(function(item) {
      return item.toString().rjust(2, '0');
    }).join(':');
  }

  function time_relative(from, to) {
    return Math.round((to - from) / 60); // in minute
  }

  function is_now() {
    return $('.when-button.selected').val() === 'now';
  }

  function get_service_ids(calendar, calendar_dates) {
    var date = now_date();

    var selected_schedule = $('.when-button.selected').val();
    var target_schedule = selected_schedule;
    if (target_schedule === 'now') {
      // getDay is "0 for Sunday", map to "0 for Monday"
      switch ((new Date().getDay() + 6) % 7) {
        case 5: target_schedule = 'saturday'; break;
        case 6: target_schedule = 'sunday'; break;
        case 0: case 1: case 2: case 3: case 4: target_schedule = 'weekday'; break;
        default: console.error('Unknown current day', (new Date().getDay() + 6) % 7); return [];
      }
    }

    // calendar:
    //   service_id => [monday,tuesday,wednesday,thursday,friday,saturday,sunday,start_date,end_date]
    // calendar_dates:
    //   service_id => [date,exception_type]
    var service_ids = Object.keys(calendar).filter(function(service_id) {
      // check calendar start/end dates
      var item = calendar[service_id];
      return (item.start_date <= date) && (date <= item.end_date);
    }).filter(function(service_id) {
      // check calendar available days
      return calendar[service_id][target_schedule];
    });

    // In now schedule, we consider exceptional days like holidays defined in calendar_dates file
    if (selected_schedule === 'now') {
      service_ids = service_ids.filter(function(service_id) {
        // check calendar_dates with exception_type 2 (if any to remove)
        return !(service_id in calendar_dates) ||
          calendar_dates[service_id].filter(function(exception_date) {
            return (exception_date[0] === date) && (exception_date[1] === 2);
          }).length === 0;
      }).concat(Object.keys(calendar_dates).filter(function(service_id) {
        // check calendar_dates with exception_type 1 (if any to add)
        return calendar_dates[service_id].filter(function(exception_date) {
          return (exception_date[0] === date) && (exception_date[1] === 1);
        }).length !== 0;
      }));
    }

    if (service_ids.length === 0) {
      console.log('Can\'t get service for now.');
    }
    return service_ids;
  }

  function get_available_services(routes, calendar, calendar_dates) {
    var availables = {};

    get_service_ids(calendar, calendar_dates).forEach(function(service_id) {
      Object.keys(routes).forEach(function(route_id) {
        var services = routes[route_id];
        var trips = services[service_id];

        if (!is_defined(trips)) {
          // this route does not have this service
          return;
        }

        if (!is_defined(availables[route_id])) {
          availables[route_id] = {};
        }
        Object.extend(availables[route_id], trips);
      });
    });

    return availables;
  }

  function search_index(trip_ids, target_ids) {
    return target_ids.map(function(target_id) {
      return trip_ids.indexOf(target_id);
    }).filter(function(index) {
      return index != -1;
    });
  }

  function compare_trip(a, b) {
    return a.departure_time - b.departure_time;
  }

  function get_trips(services, from_ids, to_ids) {
    var result = [];

    Object.keys(services)
      .forEach(function(service_id) {
        var trips = services[service_id];
        Object.keys(trips)
          .forEach(function(trip_id) {
            var trip = trips[trip_id];
            var trip_stop_ids = trip.map(function(t) { return t[0]; });
            var from_indexes = search_index(trip_stop_ids, from_ids);
            var to_indexes = search_index(trip_stop_ids, to_ids);
            if (!is_defined(from_indexes) || !is_defined(to_indexes) ||
                from_indexes.length === 0 || to_indexes.length === 0) {
              return;
            }
            var from_index = Math.min.apply(this, from_indexes);
            var to_index = Math.max.apply(this, to_indexes);
            // must be in order
            if (from_index >= to_index) {
              return;
            }

            if (!is_now() || trip[from_index][1] > now()) {
              result.push({
                departure_time: trip[from_index][1],
                arrival_time: trip[to_index][1]
              });
            }
          });
      });

    return result.sort(compare_trip);
  }

  function render_info(next_train) {
    var info = $('#info').empty();
    if (is_now() && is_defined(next_train)) {
      var next_relative = time_relative(now(), next_train.departure_time);
      info.append('
Next train: ' + next_relative + 'min
');
    }
  }

  function render_result(trips) {
    var result = $('#result').empty();
    trips.forEach(function(trip) {
      result.append('
' +
                    '' + second2str(trip.departure_time) + '' +
                    '' + time_relative(trip.departure_time, trip.arrival_time) + ' min' +
                    '' + second2str(trip.arrival_time) + '' +
                    '
');
    });
  }

  function schedule() {
    var stops = data.stops, routes = data.routes,
      calendar = data.calendar, calendar_dates = data.calendar_dates;
    var from_ids = stops[$('#from select').val()],
      to_ids = stops[$('#to select').val()],
      services = get_available_services(routes, calendar, calendar_dates);

    // if some input is invalid, just return
    if (!is_defined(from_ids) || !is_defined(to_ids) || !is_defined(services)) {
      return;
    }

    var trips = get_trips(services, from_ids, to_ids);

    saveScheduleSelection();
    render_info(trips[0]);
    render_result(trips);
  }

  function bind_events() {
    [$('#from select'), $('#to select')].forEach(function(c) {
      c.on('change', schedule);
    });

    when.each(function(index, elem) {
      $(elem).on('click', function() {
        when.each(function(index, elem) {
          $(elem).removeClass('selected');
        });
        $(elem).addClass('selected');
        schedule();
      });
    });

    $('#reverse').on('click', function() {
      var from = $('#from select').val();
      var to = $('#to select').val();

      select($('#from select'), to);
      select($('#to select'), from);

      schedule();
    });
  }

  function constructSelect(opts) {
    return '<select>' + opts.reduce(function(prev, curr) {
      return prev + '<option value="' + curr + '">' + curr + '</option>';
    }, '') + '</select>';
  }

  function initialize() {
    // init inputs elements
    when = $('.when-button');

    // generate select options
    var names = Object.keys(data.stops);
    $('#from').append(constructSelect(names));
    $('#to').append(constructSelect(names));

    // init
    loadPreviousSettings();
    bind_events();
    schedule(); // init schedule
  }

  function data_checker(names, callback) {
    var mark = {};
    names.forEach(function(name) {
      mark[name] = false;
    });

    return function(name) {
      mark[name] = true;

      var all_true = true;
      for (var n in mark)
        if (!mark[n]) {
          all_true = false;
          break;
        }

      if (all_true)
        callback();
    };
  }

  // init after document and data are ready
  var data_names = ['calendar', 'calendar_dates', 'stops', 'routes'];
  var checker = data_checker(data_names, function() {
    initialize();
  });

  // download data
  data_names.forEach(function(name) {
    data[name] = window[name];
    checker(name);
  });
}());
<commit_msg>Add a default option to selects<commit_after>if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/sw.js').then(function() {
    console.log('service worker is is all cool.');
  }).catch(function(e) {
    console.error('service worker is not so cool.', e);
    throw e;
  });
}

/* global $ */

(function() {
  'use strict';

  var from, to, when, data = {};

  function is_defined(obj) {
    return typeof (obj) !== 'undefined';
  }

  function saveScheduleSelection() {
    localStorage.setItem('caltrain-schedule-from', $('#from select').val());
    localStorage.setItem('caltrain-schedule-to', $('#to select').val());
    localStorage.setItem('caltrain-schedule-when', $('.when-button.selected').val());
  }

  function select(elm, val) {
    elm[0].selectedIndex = elm.find('option[value="' + val + '"]').index();
  }

  function loadPreviousSettings() {
    if (is_defined(localStorage.getItem('caltrain-schedule-from'))) {
      select($('#from select'), localStorage.getItem('caltrain-schedule-from'));
    }
    if (is_defined(localStorage.getItem('caltrain-schedule-to'))) {
      select($('#to select'), localStorage.getItem('caltrain-schedule-to'));
    }
    if (is_defined(localStorage.getItem('caltrain-schedule-when'))) {
      $('.when-button').removeClass('selected');
      $('.when-button[value="' + localStorage.getItem('caltrain-schedule-when') + '"]').addClass('selected');
    }
  }

  String.prototype.repeat = function(num) {
    return (num <= 0) ? '' : this + this.repeat(num - 1);
  };

  String.prototype.rjust = function(width, padding) {
    padding = (padding || ' ').substr(0, 1); // one and only one char
    return padding.repeat(width - this.length) + this;
  };

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

  // now in seconds since the midnight
  function now() {
    var date = new Date();
    return date.getHours() * 60 * 60 +
           date.getMinutes() * 60 +
           date.getSeconds();
  }

  // now date in format YYYYMMDD
  function now_date() {
    var d = new Date();
    // getMonth starts from 0
    return parseInt([d.getFullYear(), d.getMonth() + 1, d.getDate()].map(function(n) {
      return n.toString().rjust(2, '0');
    }).join(''));
  }

  function second2str(seconds) {
    var minutes = Math.floor(seconds / 60);
    return [
      Math.floor(minutes / 60),
      minutes % 60
    ].map(function(item) {
      return item.toString().rjust(2, '0');
    }).join(':');
  }

  function time_relative(from, to) {
    return Math.round((to - from) / 60); // in minute
  }

  function is_now() {
    return $('.when-button.selected').val() === 'now';
  }

  function get_service_ids(calendar, calendar_dates) {
    var date = now_date();

    var selected_schedule = $('.when-button.selected').val();
    var target_schedule = selected_schedule;
    if (target_schedule === 'now') {
      // getDay is "0 for Sunday", map to "0 for Monday"
      switch ((new Date().getDay() + 6) % 7) {
        case 5: target_schedule = 'saturday'; break;
        case 6: target_schedule = 'sunday'; break;
        case 0: case 1: case 2: case 3: case 4: target_schedule = 'weekday'; break;
        default: console.error('Unknown current day', (new Date().getDay() + 6) % 7); return [];
      }
    }

    // calendar:
    //   service_id => [monday,tuesday,wednesday,thursday,friday,saturday,sunday,start_date,end_date]
    // calendar_dates:
    //   service_id => [date,exception_type]
    var service_ids = Object.keys(calendar).filter(function(service_id) {
      // check calendar start/end dates
      var item = calendar[service_id];
      return (item.start_date <= date) && (date <= item.end_date);
    }).filter(function(service_id) {
      // check calendar available days
      return calendar[service_id][target_schedule];
    });

    // In now schedule, we consider exceptional days like holidays defined in calendar_dates file
    if (selected_schedule === 'now') {
      service_ids = service_ids.filter(function(service_id) {
        // check calendar_dates with exception_type 2 (if any to remove)
        return !(service_id in calendar_dates) ||
          calendar_dates[service_id].filter(function(exception_date) {
            return (exception_date[0] === date) && (exception_date[1] === 2);
          }).length === 0;
      }).concat(Object.keys(calendar_dates).filter(function(service_id) {
        // check calendar_dates with exception_type 1 (if any to add)
        return calendar_dates[service_id].filter(function(exception_date) {
          return (exception_date[0] === date) && (exception_date[1] === 1);
        }).length !== 0;
      }));
    }

    if (service_ids.length === 0) {
      console.log('Can\'t get service for now.');
    }
    return service_ids;
  }

  function get_available_services(routes, calendar, calendar_dates) {
    var availables = {};

    get_service_ids(calendar, calendar_dates).forEach(function(service_id) {
      Object.keys(routes).forEach(function(route_id) {
        var services = routes[route_id];
        var trips = services[service_id];

        if (!is_defined(trips)) {
          // this route does not have this service
          return;
        }

        if (!is_defined(availables[route_id])) {
          availables[route_id] = {};
        }
        Object.extend(availables[route_id], trips);
      });
    });

    return availables;
  }

  function search_index(trip_ids, target_ids) {
    return target_ids.map(function(target_id) {
      return trip_ids.indexOf(target_id);
    }).filter(function(index) {
      return index != -1;
    });
  }

  function compare_trip(a, b) {
    return a.departure_time - b.departure_time;
  }

  function get_trips(services, from_ids, to_ids) {
    var result = [];

    Object.keys(services)
      .forEach(function(service_id) {
        var trips = services[service_id];
        Object.keys(trips)
          .forEach(function(trip_id) {
            var trip = trips[trip_id];
            var trip_stop_ids = trip.map(function(t) { return t[0]; });
            var from_indexes = search_index(trip_stop_ids, from_ids);
            var to_indexes = search_index(trip_stop_ids, to_ids);
            if (!is_defined(from_indexes) || !is_defined(to_indexes) ||
                from_indexes.length === 0 || to_indexes.length === 0) {
              return;
            }
            var from_index = Math.min.apply(this, from_indexes);
            var to_index = Math.max.apply(this, to_indexes);
            // must be in order
            if (from_index >= to_index) {
              return;
            }

            if (!is_now() || trip[from_index][1] > now()) {
              result.push({
                departure_time: trip[from_index][1],
                arrival_time: trip[to_index][1]
              });
            }
          });
      });

    return result.sort(compare_trip);
  }

  function render_info(next_train) {
    var info = $('#info').empty();
    if (is_now() && is_defined(next_train)) {
      var next_relative = time_relative(now(), next_train.departure_time);
      info.append('
Next train: ' + next_relative + 'min
');
    }
  }

  function render_result(trips) {
    var result = $('#result').empty();
    trips.forEach(function(trip) {
      result.append('
' +
                    '' + second2str(trip.departure_time) + '' +
                    '' + time_relative(trip.departure_time, trip.arrival_time) + ' min' +
                    '' + second2str(trip.arrival_time) + '' +
                    '
');
    });
  }

  function schedule() {
    var stops = data.stops, routes = data.routes,
      calendar = data.calendar, calendar_dates = data.calendar_dates;
    var from_ids = stops[$('#from select').val()],
      to_ids = stops[$('#to select').val()],
      services = get_available_services(routes, calendar, calendar_dates);

    // if some input is invalid, just return
    if (!is_defined(from_ids) || !is_defined(to_ids) || !is_defined(services)) {
      return;
    }

    var trips = get_trips(services, from_ids, to_ids);

    saveScheduleSelection();
    render_info(trips[0]);
    render_result(trips);
  }

  function bind_events() {
    [$('#from select'), $('#to select')].forEach(function(c) {
      c.on('change', schedule);
    });

    when.each(function(index, elem) {
      $(elem).on('click', function() {
        when.each(function(index, elem) {
          $(elem).removeClass('selected');
        });
        $(elem).addClass('selected');
        schedule();
      });
    });

    $('#reverse').on('click', function() {
      var from = $('#from select').val();
      var to = $('#to select').val();

      select($('#from select'), to);
      select($('#to select'), from);

      schedule();
    });
  }

  function constructSelect(opts) {
    return '<select>' + opts.reduce(function(prev, curr) {
      return prev + '<option value="' + curr + '">' + curr + '</option>';
    }, '<option disabled selected>Select A Stop</option>') + '</select>';
  }

  function initialize() {
    // init inputs elements
    when = $('.when-button');

    // generate select options
    var names = Object.keys(data.stops);
    $('#from').append(constructSelect(names));
    $('#to').append(constructSelect(names));

    // init
    loadPreviousSettings();
    bind_events();
    schedule(); // init schedule
  }

  function data_checker(names, callback) {
    var mark = {};
    names.forEach(function(name) {
      mark[name] = false;
    });

    return function(name) {
      mark[name] = true;

      var all_true = true;
      for (var n in mark)
        if (!mark[n]) {
          all_true = false;
          break;
        }

      if (all_true)
        callback();
    };
  }

  // init after document and data are ready
  var data_names = ['calendar', 'calendar_dates', 'stops', 'routes'];
  var checker = data_checker(data_names, function() {
    initialize();
  });

  // download data
  data_names.forEach(function(name) {
    data[name] = window[name];
    checker(name);
  });
}());
<|endoftext|>


<commit_before>require('moonstone');

/**
* Contains the declaration for the {@link module:moonstone/Spinner~Spinner} kind.
* @module moonstone/Spinner
*/

var
	kind = require('enyo/kind'),
	util = require('enyo/utils'),
	Control = require('enyo/Control');

var
	Marquee = require('../Marquee'),
	MarqueeText = Marquee.Text,
	MarqueeSupport = Marquee.Support;

/**
* {@link module:moonstone/Spinner~Spinner} is a [control]{@link module:enyo/Control~Control} that shows a spinning animation
* to indicate that activity is taking place. By default, the spinner is light-colored and
* suitable for displaying against a dark background. If you need a dark spinner (to be
* shown on a lighter background), apply the `moon-light` CSS class:
*
* ```javascript
* var
* 	kind = require('enyo/kind'),
* 	Spinner = require('moonstone/Spinner');
*
* // Normal
* {kind: Spinner}
* // Light
* {kind: Spinner, classes: 'moon-light'}
* // Normal with a message
* {kind: Spinner, content: 'Loading...'}
* // Transparent background
* {kind: Spinner, transparent: true}
* ```
*
* Typically, a spinner is shown to indicate activity and hidden to indicate that the activity
* has ended. The animation automatically starts when the spinner is shown. If you wish, you
* may control the animation directly by calling the [start()]{@link module:moonstone/Spinner~Spinner#start},
* [stop()]{@link module:moonstone/Spinner~Spinner#stop}, and [toggle()]{@link module:moonstone/Spinner~Spinner#toggle} methods.
*
* `moon.Spinner` supports both `content` text and a `components` block. Note that you
* may only use one of these at a time. Using a `components` block may be desirable if,
* for example, the text in the content section needs [marquee]{@link module:moonstone/Marquee~MarqueeSupport}
* functionality or you'd like to include an [icon]{@link module:moonstone/Icon~Icon} in the message.
*
* @class Spinner
* @extends module:enyo/Control~Control
* @ui
* @public
*/
module.exports = kind(
	/** @lends module:moonstone/Spinner~Spinner.prototype */ {

	/**
	* @private
	*/
	name: 'moon.Spinner',

	/**
	* @private
	*/
	kind: Control,

	/**
	* @private
	*/
	classes: 'moon-spinner',

	/**
	* Determines whether spinner's background is transparent.
	*
	* @type {Boolean}
	* @default false
	* @public
	*/
	transparent: false,

	/**
	* Sets the spinner to be horizontally centered, relative to its containing control. Use in
	* combination with [moon.Spinner#center]{@link module:moonstone/Spinner~Spinner#middle} to center this spinner
	* both horizontally and vertically, or just horizontally.
	*
	* @type {Boolean}
	* @default false
	* @public
	*/
	center: false,

	/**
	* When `true`, sets the spinner to be vertically centered inside its container. This option
	* has no effect if [moon.Spinner#center]{@link module:moonstone/Spinner~Spinner#center} is `false`. Setting this
	* to false allows the spinner to only be horizontally centered, and not vertically centered.
	*
	* @type {Boolean}
	* @default true
	* @public
	*/
	middle: true,

	/**
	* @private
	*/
	components: [
		{name: 'decorator', kind: Control, classes: 'moon-spinner-ball-decorator spin-ball-animation', components: [
			{kind: Control, classes: 'moon-spinner-ball moon-spinner-ball1'},
			{kind: Control, classes: 'moon-spinner-ball moon-spinner-ball2'},
			{kind: Control, classes: 'moon-spinner-ball moon-spinner-ball3'}
		]}
	],

	/**
	* @private
	*/
	spinnerTools: [
		{name: 'client', kind: Control, classes: 'moon-spinner-client'}
	],

	/**
	* @private
	*/
	initComponents: function() {
		Control.prototype.initComponents.apply(this, arguments);
		this.createTools();
	},

	/**
	* @private
	*/
	createTools: function() {
		// This allows for the spinner instances with child components to not have
		// MarqueeText kind on the client container.
		var tools = util.clone(this.spinnerTools);
		if (!(this.components && this.components.length > 0)) {
			// If there are no components in the spinner, convert its client area to a MarqueeText kind
			util.mixin(tools[0], {
				kind: MarqueeText,
				mixins: [MarqueeSupport],
				marqueeOnSpotlight: false,
				marqueeOnHover: true,
				marqueeOnRender: true,
				marqueeOnRenderDelay: 1000
			});
		}
		this.createChrome(tools);
	},

	/**
	* @private
	*/
	create: function() {
		Control.prototype.create.apply(this, arguments);
		this.contentChanged();
		this.transparentChanged();
		this.centerChanged();
		this.middleChanged();
		this.addClass('running');
	},

	/**
	* Hides the animating spinner.
	*
	* @public
	*/
	stop: function() {
		this.set('showing', false);
	},

	/**
	* Shows the spinner with animation.
	*
	* @public
	*/
	start: function() {
		this.set('showing', true);
	},

	/**
	* Toggles the spinner's visibility state.
	*
	* @public
	*/
	toggle: function() {
		this.set('showing', !this.get('showing'));
	},

	/**
	* @private
	*/
	hasContent: function() {
		// true if this.content is set to something OR if there are more than zero components
		return (!!this.content || (this.components && this.components.length > 0));
	},

	/**
	* @private
	*/
	contentChanged: function(old) {
		Control.prototype.contentChanged.apply(this, arguments);
		if (this.content || old) {
			this.$.client.set('content', this.content);
		}
		this.$.client.set('showing', !!this.content);
		this.addRemoveClass('content', this.hasContent());
	},

	/**
	* @private
	*/
	centerChanged: function(old) {
		this.addRemoveClass('center',this.get('center'));
	},

	/**
	* @private
	*/
	middleChanged: function(old) {
		this.addRemoveClass('middle',this.get('middle'));
	},

	/**
	* @private
	*/
	transparentChanged: function() {
		this.addRemoveClass('moon-spinner-transparent-background', !!this.get('transparent'));
	}
});
<commit_msg>PLAT-6920: Add Text to Speech Accessibility support to Spinner<commit_after>require('moonstone');

/**
* Contains the declaration for the {@link module:moonstone/Spinner~Spinner} kind.
* @module moonstone/Spinner
*/

var
	kind = require('enyo/kind'),
	util = require('enyo/utils'),
	Control = require('enyo/Control');

var
	Marquee = require('../Marquee'),
	MarqueeText = Marquee.Text,
	MarqueeSupport = Marquee.Support;

/**
* {@link module:moonstone/Spinner~Spinner} is a [control]{@link module:enyo/Control~Control} that shows a spinning animation
* to indicate that activity is taking place. By default, the spinner is light-colored and
* suitable for displaying against a dark background. If you need a dark spinner (to be
* shown on a lighter background), apply the `moon-light` CSS class:
*
* ```javascript
* var
* 	kind = require('enyo/kind'),
* 	Spinner = require('moonstone/Spinner');
*
* // Normal
* {kind: Spinner}
* // Light
* {kind: Spinner, classes: 'moon-light'}
* // Normal with a message
* {kind: Spinner, content: 'Loading...'}
* // Transparent background
* {kind: Spinner, transparent: true}
* ```
*
* Typically, a spinner is shown to indicate activity and hidden to indicate that the activity
* has ended. The animation automatically starts when the spinner is shown. If you wish, you
* may control the animation directly by calling the [start()]{@link module:moonstone/Spinner~Spinner#start},
* [stop()]{@link module:moonstone/Spinner~Spinner#stop}, and [toggle()]{@link module:moonstone/Spinner~Spinner#toggle} methods.
*
* `moon.Spinner` supports both `content` text and a `components` block. Note that you
* may only use one of these at a time. Using a `components` block may be desirable if,
* for example, the text in the content section needs [marquee]{@link module:moonstone/Marquee~MarqueeSupport}
* functionality or you'd like to include an [icon]{@link module:moonstone/Icon~Icon} in the message.
*
* @class Spinner
* @extends module:enyo/Control~Control
* @ui
* @public
*/
module.exports = kind(
	/** @lends module:moonstone/Spinner~Spinner.prototype */ {

	/**
	* @private
	*/
	name: 'moon.Spinner',

	/**
	* @private
	*/
	kind: Control,

	/**
	* @private
	*/
	classes: 'moon-spinner',

	/**
	* Determines whether spinner's background is transparent.
	*
	* @type {Boolean}
	* @default false
	* @public
	*/
	transparent: false,

	/**
	* Sets the spinner to be horizontally centered, relative to its containing control. Use in
	* combination with [moon.Spinner#center]{@link module:moonstone/Spinner~Spinner#middle} to center this spinner
	* both horizontally and vertically, or just horizontally.
	*
	* @type {Boolean}
	* @default false
	* @public
	*/
	center: false,

	/**
	* When `true`, sets the spinner to be vertically centered inside its container. This option
	* has no effect if [moon.Spinner#center]{@link module:moonstone/Spinner~Spinner#center} is `false`. Setting this
	* to false allows the spinner to only be horizontally centered, and not vertically centered.
	*
	* @type {Boolean}
	* @default true
	* @public
	*/
	middle: true,

	/**
	* @private
	*/
	components: [
		{name: 'decorator', kind: Control, classes: 'moon-spinner-ball-decorator spin-ball-animation', components: [
			{kind: Control, classes: 'moon-spinner-ball moon-spinner-ball1'},
			{kind: Control, classes: 'moon-spinner-ball moon-spinner-ball2'},
			{kind: Control, classes: 'moon-spinner-ball moon-spinner-ball3'}
		]}
	],

	/**
	* @private
	*/
	spinnerTools: [
		{name: 'client', kind: Control, classes: 'moon-spinner-client'}
	],

	/**
	* @private
	*/
	initComponents: function() {
		Control.prototype.initComponents.apply(this, arguments);
		this.createTools();
	},

	/**
	* @private
	*/
	createTools: function() {
		// This allows for the spinner instances with child components to not have
		// MarqueeText kind on the client container.
		var tools = util.clone(this.spinnerTools);
		if (!(this.components && this.components.length > 0)) {
			// If there are no components in the spinner, convert its client area to a MarqueeText kind
			util.mixin(tools[0], {
				kind: MarqueeText,
				mixins: [MarqueeSupport],
				marqueeOnSpotlight: false,
				marqueeOnHover: true,
				marqueeOnRender: true,
				marqueeOnRenderDelay: 1000
			});
		}
		this.createChrome(tools);
	},

	/**
	* @private
	*/
	create: function() {
		Control.prototype.create.apply(this, arguments);
		this.contentChanged();
		this.transparentChanged();
		this.centerChanged();
		this.middleChanged();
		this.addClass('running');
	},

	/**
	* Hides the animating spinner.
	*
	* @public
	*/
	stop: function() {
		this.set('showing', false);
	},

	/**
	* Shows the spinner with animation.
	*
	* @public
	*/
	start: function() {
		this.set('showing', true);
	},

	/**
	* Toggles the spinner's visibility state.
	*
	* @public
	*/
	toggle: function() {
		this.set('showing', !this.get('showing'));
	},

	/**
	* @private
	*/
	hasContent: function() {
		// true if this.content is set to something OR if there are more than zero components
		return (!!this.content || (this.components && this.components.length > 0));
	},

	/**
	* @private
	*/
	contentChanged: function(old) {
		Control.prototype.contentChanged.apply(this, arguments);
		if (this.content || old) {
			this.$.client.set('content', this.content);
		}
		this.$.client.set('showing', !!this.content);
		this.addRemoveClass('content', this.hasContent());
	},

	/**
	* @private
	*/
	centerChanged: function(old) {
		this.addRemoveClass('center',this.get('center'));
	},

	/**
	* @private
	*/
	middleChanged: function(old) {
		this.addRemoveClass('middle',this.get('middle'));
	},

	/**
	* @private
	*/
	transparentChanged: function() {
		this.addRemoveClass('moon-spinner-transparent-background', !!this.get('transparent'));
	},

	// Accessibility

	/**
	* @default true
	* @type {Boolean}
	* @see enyo/AccessibilitySupport~AccessibilitySupport#accessibilityAlert
	* @public
	*/
	accessibilityAlert: true,

	/**
	* @default off
	* @type {String}
	* @see enyo/AccessibilitySupport~AccessibilitySupport#accessibilityLive
	* @public
	*/
    accessibilityLive: 'off'
});
<|endoftext|>


<commit_before>'use strict';

const wrapper         = require('./util/result-wrapper'),
      logger          = require('../../../util/logger'),
      timeoutRejector = require('../../../util/promise').timeoutRejector,
      Backendless     = require('backendless'),
      path            = require('path');

const SHUTDOWN_CODE = 32768;
const SHUTDOWN_ACTION = 'SHUTDOWN';

/**
 * @typedef {Object} InitAppData
 * @property {string} secretKey
 * @property {string} url
 * @property {string} appVersionName
 */

/**
 * @typedef {Object} CodeRunnerTask
 * @property {String} ___jsonclass
 * @property {String} applicationId;
 * @property {String} appVersionId;
 * @property {InitAppData} initAppData;
 * @property {Number} timeout
 * @property {String} relativePath
 * @property {String} codePath
 */

const executor = module.exports = {};

executor.RMI = 'com.backendless.coderunner.commons.protocol.RequestMethodInvocation';
executor.RAI = 'com.backendless.coderunner.commons.protocol.RequestActionInvocation';
executor.RSI = 'com.backendless.coderunner.commons.protocol.RequestServiceInvocation';

const executors = {
  [executor.RMI]: './invoke-handler',
  [executor.RAI]: './invoke-action',
  [executor.RSI]: './invoke-service'
};

/**
 * @param {CodeRunnerTask} task
 * @returns {Function} task executor
 */
function getTaskExecutor(task) {
  const taskClass = task.___jsonclass;

  if (!executors[taskClass]) {
    throw new Error(`Unknown task [${taskClass}]`);
  }

  return require(executors[taskClass]);
}

function executeTask(task, model) {
  const taskExecutor = getTaskExecutor(task);

  return Promise.race([
    taskExecutor(task, model),
    timeoutRejector(task.timeout, 'Task execution is aborted due to timeout')
  ]);
}

/**
 * @param {CodeRunnerTask} task
 */
function initClientSdk(task) {
  if (task.initAppData) {
    Backendless.serverURL = task.initAppData.url;
    Backendless.initApp(task.applicationId, task.initAppData.secretKey, task.initAppData.appVersionName);
    Backendless.Logging.setLogReportingPolicy(1, 0);
  }
}

/**
 * @param {CodeRunnerTask} task
 * @param {Object} opts
 */
function enrichTask(task, opts) {
  task.codePath = path.resolve(opts.backendless.repoPath, task.applicationId.toLowerCase(), task.relativePath || '');

  //TODO: workaround for http://bugs.backendless.com/browse/BKNDLSS-12041
  if (task.___jsonclass === executor.RMI && task.eventId === SHUTDOWN_CODE) {
    task.___jsonclass = executor.RAI;
    task.actionType = SHUTDOWN_ACTION;
  }
}

/**
 * @param {CodeRunnerTask} task
 * @param {?*} result
 * @param {?Error|ExceptionWrapper|String=} error
 * @returns {String} task invocation result in JSON
 */
function wrapResult(task, result, error) {
  error && logger.error(`Error: ${error.message || error}`);

  return JSON.stringify(
    rsiTask(task)
      ? [error ? wrapper.exception(error) : result]
      : wrapper.invocationResult(error, result)
  );
}

function rsiTask(task) {
  return task.___jsonclass === executor.RSI;
}

/**
 * @param {CodeRunnerTask} task
 * @param {Object} opts
 * @param {ServerCodeModel=} model
 * @returns {Promise.<?string>} task invocation result in JSON (if any)
 */
executor.execute = function(task, opts, model) {
  return Promise.resolve()
    .then(() => enrichTask(task, opts))
    .then(() => initClientSdk(task))
    .then(() => executeTask(task, model))
    .then(res => res !== undefined ? wrapResult(task, res) : res)
    .catch(err => wrapResult(task, null, err));
};

<commit_msg>feat: print server code error stack in verbose mode<commit_after>'use strict';

const wrapper         = require('./util/result-wrapper'),
      logger          = require('../../../util/logger'),
      timeoutRejector = require('../../../util/promise').timeoutRejector,
      Backendless     = require('backendless'),
      path            = require('path');

const SHUTDOWN_CODE = 32768;
const SHUTDOWN_ACTION = 'SHUTDOWN';

/**
 * @typedef {Object} InitAppData
 * @property {string} secretKey
 * @property {string} url
 * @property {string} appVersionName
 */

/**
 * @typedef {Object} CodeRunnerTask
 * @property {String} ___jsonclass
 * @property {String} applicationId;
 * @property {String} appVersionId;
 * @property {InitAppData} initAppData;
 * @property {Number} timeout
 * @property {String} relativePath
 * @property {String} codePath
 */

const executor = module.exports = {};

executor.RMI = 'com.backendless.coderunner.commons.protocol.RequestMethodInvocation';
executor.RAI = 'com.backendless.coderunner.commons.protocol.RequestActionInvocation';
executor.RSI = 'com.backendless.coderunner.commons.protocol.RequestServiceInvocation';

const executors = {
  [executor.RMI]: './invoke-handler',
  [executor.RAI]: './invoke-action',
  [executor.RSI]: './invoke-service'
};

/**
 * @param {CodeRunnerTask} task
 * @returns {Function} task executor
 */
function getTaskExecutor(task) {
  const taskClass = task.___jsonclass;

  if (!executors[taskClass]) {
    throw new Error(`Unknown task [${taskClass}]`);
  }

  return require(executors[taskClass]);
}

function executeTask(task, model) {
  const taskExecutor = getTaskExecutor(task);

  return Promise.race([
    taskExecutor(task, model),
    timeoutRejector(task.timeout, 'Task execution is aborted due to timeout')
  ]);
}

/**
 * @param {CodeRunnerTask} task
 */
function initClientSdk(task) {
  if (task.initAppData) {
    Backendless.serverURL = task.initAppData.url;
    Backendless.initApp(task.applicationId, task.initAppData.secretKey, task.initAppData.appVersionName);
    Backendless.Logging.setLogReportingPolicy(1, 0);
  }
}

/**
 * @param {CodeRunnerTask} task
 * @param {Object} opts
 */
function enrichTask(task, opts) {
  task.codePath = path.resolve(opts.backendless.repoPath, task.applicationId.toLowerCase(), task.relativePath || '');

  //TODO: workaround for http://bugs.backendless.com/browse/BKNDLSS-12041
  if (task.___jsonclass === executor.RMI && task.eventId === SHUTDOWN_CODE) {
    task.___jsonclass = executor.RAI;
    task.actionType = SHUTDOWN_ACTION;
  }
}

/**
 * @param {CodeRunnerTask} task
 * @param {?*} result
 * @param {?Error|ExceptionWrapper|String=} error
 * @returns {String} task invocation result in JSON
 */
function wrapResult(task, result, error) {
  error && logger.error(`Error: ${logger.verbose && error.stack || error.message || error}`);

  return JSON.stringify(
    rsiTask(task)
      ? [error ? wrapper.exception(error) : result]
      : wrapper.invocationResult(error, result)
  );
}

function rsiTask(task) {
  return task.___jsonclass === executor.RSI;
}

/**
 * @param {CodeRunnerTask} task
 * @param {Object} opts
 * @param {ServerCodeModel=} model
 * @returns {Promise.<?string>} task invocation result in JSON (if any)
 */
executor.execute = function(task, opts, model) {
  return Promise.resolve()
    .then(() => enrichTask(task, opts))
    .then(() => initClientSdk(task))
    .then(() => executeTask(task, model))
    .then(res => res !== undefined ? wrapResult(task, res) : res)
    .catch(err => wrapResult(task, null, err));
};

<|endoftext|>


<commit_before>var async    = require('async');
var moment   = require('moment');
var mongoose = require('../../bootstrap');
var db       = mongoose.connection.db;
var CheckHourlyStat = require('../../models/checkHourlyStat');
var Tag      = require('../../models/tag');
var QosAggregator = require('../../lib/qosAggregator');

var migrateCheckStats = function(name, callback) {
  var nbMigratedDocuments = 0;
  var collection = db.collection(name);
  var statStream = collection.find().stream();
  var unset = {
    ups: 1,
    responsives: 1,
    time: 1
  };
  statStream.on('data', function(stat) {
    if (stat.availability) {
      // already merged
      return;
    }
    var newStat = {
      availability: stat.ups / stat.count,
      responsiveness: stat.responsives / stat.count,
      responseTime: stat.time / stat.count,
      outages: [] // no way to get that back since CheckEvents are purged
    };
    collection.update({ _id: stat._id }, { $set: newStat, $unset: unset });
    nbMigratedDocuments++;
    if (nbMigratedDocuments % 100 == 0) {
      console.log('  Migrating ' + name + ' #' + nbMigratedDocuments);
    }
  });
  statStream.on('error', function(err) {
    callback(err);
  });
  statStream.on('end', function() {
    if (nbMigratedDocuments > 0) {
      console.log('  Finished: ' + nbMigratedDocuments + ' ' + name + ' migrated');
    } else {
      console.log('  No ' + name + ' to migrate');
    }
    callback();
  });
}

var addEndToMonthlyStat = function(name, callback) {
  var nbMigratedDocuments = 0;
  var collection = db.collection(name);
  var statStream = collection.find().stream();
  statStream.on('data', function(stat) {
    if (stat.end) {
      // already merged
      return;
    }
    var end = moment(stat.timestamp).endOf('month').toDate();
    collection.update({ _id: stat._id }, { $set: { end: end } });
    nbMigratedDocuments++;
    if (nbMigratedDocuments % 100 == 0) {
      console.log('  Adding end date to ' + name + ' #' + nbMigratedDocuments);
    }
  });
  statStream.on('error', function(err) {
    callback(err);
  });
  statStream.on('end', function() {
    if (nbMigratedDocuments > 0) {
      console.log('  Finished: Added end date to' + nbMigratedDocuments + ' ' + name + ' stats');
    } else {
      console.log('  No ' + name + ' missing end date');
    }
    callback();
  });
}

var getOldestDate = function(callback) {
  CheckHourlyStat
  .find()
  .sort({ 'timestamp': 1 })
  .findOne(function(err, stat) {
    return callback(err, stat ? stat.timestamp.valueOf() : null);
  });
}

var updateMonthlyQos = function(start, callback) {
  var date = Date.now() + 28 * 24 * 60 * 60 * 1000;
  nbDates = 0;
  async.whilst(
    function() { date -= 28 * 24 * 60 * 60 * 1000; return date > start; },
    function(cb) {
      var dateObject = new Date(date);
      QosAggregator.updateMonthlyQos(dateObject, cb);
      nbDates++;
      console.log('Computing monthly stats for ' + dateObject.toUTCString());
    },
    callback
  );
}

var updateYearlyQos = function(start, callback) {
  var date = Date.now() + 365 * 24 * 60 * 60 * 1000;
  nbDates = 0;
  async.whilst(
    function() { date -= 365 * 24 * 60 * 60 * 1000; return date > start; },
    function(cb) {
      var dateObject = new Date(date);
      QosAggregator.updateYearlyQos(dateObject, cb);
      nbDates++;
      console.log('Computing yearly stats for ' + dateObject.getFullYear());
    },
    callback
  );
}

var ensureTagsHaveFirstTestedDate = function(callback) {
  console.log('Updating tags for firstTested date');
  Tag.ensureTagsHaveFirstTestedDate(callback);
}

mongoose.connection.on('open', function(err) {
  if (err) return console.error(err);
  getOldestDate(function (err, oldestDate) {
    if (err) return console.error(err);
    async.series([
      function(next) {
        async.forEach(['checkhourlystats', 'checkdailystats', 'taghourlystats', 'tagdailystats'], migrateCheckStats, next);
      },
      function(next) {
        async.forEach(['checkmonthlystats', 'tagmonthlystats'], addEndToMonthlyStat, next);
      },
      function(next) {
        updateMonthlyQos(oldestDate, next);
      },
      function(next) {
        updateYearlyQos(oldestDate, next);
      },
      ensureTagsHaveFirstTestedDate,
      QosAggregator.updateLast24HoursQos.bind(QosAggregator)
    ], function(err2) {
      if (err2) return console.error(err2);
      console.log('Successfully migrated ' + db.databaseName + ' database');
      setTimeout(function() { mongoose.connection.close(); }, 1000);
    });
  });
});<commit_msg>some code quality improvements<commit_after>var async    = require('async');
var moment   = require('moment');
var mongoose = require('../../bootstrap');
var db       = mongoose.connection.db;
var CheckHourlyStat = require('../../models/checkHourlyStat');
var Tag      = require('../../models/tag');
var QosAggregator = require('../../lib/qosAggregator');

var migrateCheckStats = function(name, callback) {
  var nbMigratedDocuments = 0;
  var collection = db.collection(name);
  var statStream = collection.find().stream();
  var unset = {
    ups: 1,
    responsives: 1,
    time: 1
  };
  statStream.on('data', function(stat) {
    if (stat.availability) {
      // already merged
      return;
    }
    var newStat = {
      availability: stat.ups / stat.count,
      responsiveness: stat.responsives / stat.count,
      responseTime: stat.time / stat.count,
      outages: [] // no way to get that back since CheckEvents are purged
    };
    collection.update({ _id: stat._id }, { $set: newStat, $unset: unset });
    nbMigratedDocuments++;
    if (nbMigratedDocuments % 100 == 0) {
      console.log('  Migrating ' + name + ' #' + nbMigratedDocuments);
    }
  });
  statStream.on('error', function(err) {
    callback(err);
  });
  statStream.on('end', function() {
    if (nbMigratedDocuments > 0) {
      console.log('  Finished: ' + nbMigratedDocuments + ' ' + name + ' migrated');
    } else {
      console.log('  No ' + name + ' to migrate');
    }
    callback();
  });
};

var addEndToMonthlyStat = function(name, callback) {
  var nbMigratedDocuments = 0;
  var collection = db.collection(name);
  var statStream = collection.find().stream();
  statStream.on('data', function(stat) {
    if (stat.end) {
      // already merged
      return;
    }
    var end = moment(stat.timestamp).endOf('month').toDate();
    collection.update({ _id: stat._id }, { $set: { end: end } });
    nbMigratedDocuments++;
    if (nbMigratedDocuments % 100 == 0) {
      console.log('  Adding end date to ' + name + ' #' + nbMigratedDocuments);
    }
  });
  statStream.on('error', function(err) {
    callback(err);
  });
  statStream.on('end', function() {
    if (nbMigratedDocuments > 0) {
      console.log('  Finished: Added end date to' + nbMigratedDocuments + ' ' + name + ' stats');
    } else {
      console.log('  No ' + name + ' missing end date');
    }
    callback();
  });
};

var getOldestDate = function(callback) {
  CheckHourlyStat
  .find()
  .sort({ 'timestamp': 1 })
  .findOne(function(err, stat) {
    return callback(err, stat ? stat.timestamp.valueOf() : null);
  });
};

var updateMonthlyQos = function(start, callback) {
  var date = Date.now() + 28 * 24 * 60 * 60 * 1000;
  nbDates = 0;
  async.whilst(
    function() { date -= 28 * 24 * 60 * 60 * 1000; return date > start; },
    function(cb) {
      var dateObject = new Date(date);
      QosAggregator.updateMonthlyQos(dateObject, cb);
      nbDates++;
      console.log('Computing monthly stats for ' + dateObject.toUTCString());
    },
    callback
  );
};

var updateYearlyQos = function(start, callback) {
  var date = Date.now() + 365 * 24 * 60 * 60 * 1000;
  nbDates = 0;
  async.whilst(
    function() { date -= 365 * 24 * 60 * 60 * 1000; return date > start; },
    function(cb) {
      var dateObject = new Date(date);
      QosAggregator.updateYearlyQos(dateObject, cb);
      nbDates++;
      console.log('Computing yearly stats for ' + dateObject.getFullYear());
    },
    callback
  );
};

var ensureTagsHaveFirstTestedDate = function(callback) {
  console.log('Updating tags for firstTested date');
  Tag.ensureTagsHaveFirstTestedDate(callback);
};

mongoose.connection.on('open', function(err) {
  if (err) return console.error(err);
  getOldestDate(function (err, oldestDate) {
    if (err) return console.error(err);
    async.series([
      function(next) {
        async.forEach(['checkhourlystats', 'checkdailystats', 'taghourlystats', 'tagdailystats'], migrateCheckStats, next);
      },
      function(next) {
        async.forEach(['checkmonthlystats', 'tagmonthlystats'], addEndToMonthlyStat, next);
      },
      function(next) {
        updateMonthlyQos(oldestDate, next);
      },
      function(next) {
        updateYearlyQos(oldestDate, next);
      },
      ensureTagsHaveFirstTestedDate,
      QosAggregator.updateLast24HoursQos.bind(QosAggregator)
    ], function(err2) {
      if (err2) return console.error(err2);
      console.log('Successfully migrated ' + db.databaseName + ' database');
      setTimeout(function() { mongoose.connection.close(); }, 1000);
    });
  });
});
<|endoftext|>


<commit_before>import superagent from 'superagent'
import superagentProxy from 'superagent-proxy'
import superagentPromise from 'superagent-promise'

const agent = superagentPromise(superagentProxy(superagent), Promise)

import constants from '../constants'

export default class Build {

  constructor (token, language) {
    this.token = token
    this.language = language
  }

  dialog = (message, options = {}) => {
    const token = options.token || this.token
    const data = {
      message,
      conversation_id: options.conversationId,
      language: options.language || this.language,
    }

    return agent('POST', `${constants.DIALOG_ENDPOINT}/dialog`)
      .set('Authorization', `Token ${token}`)
      .send(data)
  }

  getConversation = (user, bot, conversationId, options = {}) => {
    const token = options.token || this.token
    return agent('GET', `${constants.DIALOG_ENDPOINT}/users/${user}/bots/${bot}/builders/v1/conversation_states/${conversationId}`)
      .set('Authorization', `Token ${token}`)
      .send()
  }

  updateConversation = (user, bot, conversationId, data = {}, options = {}) => {
    const token = options.token || this.token
    if (data.memory && data.memory.constructor !== Object) {
      return Promise.reject('Invalid memory parameter')
    }

    return agent('PUT', `${constants.DIALOG_ENDPOINT}/users/${user}/bots/${bot}/builders/v1/conversation_states/${conversationId}`)
      .set('Authorization', `Token ${token}`)
      .send(data)
  }

  deleteConversation = (user, bot, conversationId, options = {}) => {
    const token = options.token || this.token
    return agent('DELETE', `${constants.DIALOG_ENDPOINT}/users/${user}/bots/${bot}/builders/v1/conversation_states/${conversationId}`)
      .set('Authorization', `Token ${token}`)
      .send()
  }

}
<commit_msg>refactor(build) unwrap results<commit_after>import superagent from 'superagent'
import superagentProxy from 'superagent-proxy'
import superagentPromise from 'superagent-promise'

const agent = superagentPromise(superagentProxy(superagent), Promise)

import constants from '../constants'

export default class Build {

  constructor (token, language) {
    this.token = token
    this.language = language
  }

  dialog = (message, options = {}) => {
    const token = options.token || this.token
    const data = {
      message,
      conversation_id: options.conversationId,
      language: options.language || this.language,
    }

    return agent('POST', `${constants.DIALOG_ENDPOINT}/dialog`)
      .set('Authorization', `Token ${token}`)
      .send(data)
      .then(res => res.body.results)
  }

  getConversation = (user, bot, conversationId, options = {}) => {
    const token = options.token || this.token
    return agent('GET', `${constants.DIALOG_ENDPOINT}/users/${user}/bots/${bot}/builders/v1/conversation_states/${conversationId}`)
      .set('Authorization', `Token ${token}`)
      .send()
  }

  updateConversation = (user, bot, conversationId, data = {}, options = {}) => {
    const token = options.token || this.token
    if (data.memory && data.memory.constructor !== Object) {
      return Promise.reject('Invalid memory parameter')
    }

    return agent('PUT', `${constants.DIALOG_ENDPOINT}/users/${user}/bots/${bot}/builders/v1/conversation_states/${conversationId}`)
      .set('Authorization', `Token ${token}`)
      .send(data)
  }

  deleteConversation = (user, bot, conversationId, options = {}) => {
    const token = options.token || this.token
    return agent('DELETE', `${constants.DIALOG_ENDPOINT}/users/${user}/bots/${bot}/builders/v1/conversation_states/${conversationId}`)
      .set('Authorization', `Token ${token}`)
      .send()
  }

}
<|endoftext|>


<commit_before>/*!
 * ${copyright}
 */

// Provides control sap.uxap.HierarchicalSelect.
sap.ui.define(["jquery.sap.global", "sap/m/Select", "sap/ui/Device", "./library"], function (jQuery, Select, Device, library) {
	"use strict";

	/**
	 * Constructor for a new HierarchicalSelect.
	 *
	 * @param {string} [sId] id for the new control, generated automatically if no id is given
	 * @param {object} [mSettings] initial settings for the new control
	 *
	 * @class
	 * A select that display items on 2 level of hierarchy.
	 * If a provided item has a custom data named "secondLevel", then it will be displayed as a second level, otherwise it would be displayed as a first level.
	 * @extends sap.m.Select
	 *
	 * @author SAP SE
	 *
	 * @constructor
	 * @public
	 * @since 1.26
	 * @alias sap.uxap.HierarchicalSelect
	 * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
	 */
	var HierarchicalSelect = Select.extend("sap.uxap.HierarchicalSelect", /** @lends sap.uxap.HierarchicalSelect.prototype */ {
		metadata: {

			library: "sap.uxap",
			properties: {

				/**
				 * Determines whether the HierarchicalSelect items are displayed in upper case.
				 */
				upperCase: {type: "boolean", group: "Appearance", defaultValue: false}
			}
		}
	});

	HierarchicalSelect.POPOVER_MIN_WIDTH_REM = 11;

	HierarchicalSelect.prototype.onAfterRenderingPicker = function () {

		Select.prototype.onAfterRenderingPicker.call(this);

		var aItems = this.getItems() || [];

		aItems.forEach(function (oItem) {
			var sClass = (oItem.data("secondLevel") === true) ? "sapUxAPHierarchicalSelectSecondLevel" : "sapUxAPHierarchicalSelectFirstLevel";

			oItem.$().addClass(sClass);
		}, this);
	};

	HierarchicalSelect.prototype.setUpperCase = function (bValue, bSuppressInvalidate) {

		this.setProperty("upperCase", bValue, bSuppressInvalidate);
		this.toggleStyleClass("sapUxAPHierarchicalSelectUpperCase", bValue);
		var oPicker = this.getAggregation("picker");
		if (oPicker) {
			oPicker.toggleStyleClass("sapMSltPickerFirstLevelUpperCase", bValue);
			if (!bSuppressInvalidate) {
				oPicker.invalidate();
			}
		}
		return this;
	};

	/**
	 * Keyboard handling requirement to have the same behavior on [ENTER] key
	 * as on [SPACE] key (namely, to toggle the open state the select dropdown)
	 */
	HierarchicalSelect.prototype.onsapenter = Select.prototype.onsapspace;

	/**
	 * Keyboard handling of [UP], [PAGE-UP], [PAGE-DOWN], [HOME], [END] keys
	 * Stops propagation to avoid triggering the listeners for the same keys of the parent control (the AnchorBar)
	 */
	["onsapup", "onsappageup", "onsappagedown", "onsaphome", "onsapend"].forEach(function (sName) {
		HierarchicalSelect.prototype[sName] = function (oEvent) {
			Select.prototype[sName].call(this, oEvent);
			oEvent.stopPropagation();
		};
	});

	HierarchicalSelect.prototype._createDialog = function () {
		var oDialog = Select.prototype._createDialog.call(this),
			oCustomHeader = oDialog.getCustomHeader();

		if (oCustomHeader){
			oCustomHeader.addStyleClass("sapUxAPHierarchicalSelect");
		}

		return oDialog;

	};

	/**
	 * Decorate a Popover instance by adding some private methods.
	 *
	 * We are overriding function from sap.m.Select
	 * in order to redefine position of popover
	 *
	 * @param {sap.m.Popover}
	 * @private
	 */
	HierarchicalSelect.prototype._decoratePopover = function (oPopover) {

		Select.prototype._decoratePopover.call(this, oPopover);

		oPopover._adaptPositionParams = function () {
			this._marginTop = 0;
			this._marginLeft = 0;
			this._marginRight = 0;
			this._marginBottom = 0;

			this._arrowOffset = 0;
			this._offsets = ["0 0", "0 0", "0 0", "0 0"];

			this._myPositions = ["end bottom", "end center", "end top", "begin center"];
			this._atPositions = ["end top", "end center", "end bottom", "begin center"];
		};

		// offset the popup to make it cover the scrollbar (to avoid having page-scrollbar and popup-scrollbar appearing next to each other)
		if (Device.system.tablet || Device.system.desktop) {
			var fRight = jQuery.position.scrollbarWidth();
			if (fRight > 0) {
				oPopover.setOffsetX(fRight);
			}
		}
	};

	/**
	 * Overriding function from sap.m.Select to access min-width of the popover
	 * in order to ensure that min-width is not smaller than sap.uxap.HierarchicalSelect.POPOVER_MIN_WIDTH_REM
	 */
	HierarchicalSelect.prototype._onAfterRenderingPopover = function () {
		var oPopover = this.getPicker(),
			oPopoverDomRef = oPopover.getDomRef("cont"),
			sMinWidth = oPopoverDomRef.style.minWidth;

		if (jQuery.sap.endsWith(sMinWidth, "rem")) {
			sMinWidth = sMinWidth.substring(0, sMinWidth.length - 3);
			var iMinWidth = parseFloat(sMinWidth);
			if (iMinWidth < HierarchicalSelect.POPOVER_MIN_WIDTH_REM && oPopoverDomRef) {
				oPopoverDomRef.style.minWidth = HierarchicalSelect.POPOVER_MIN_WIDTH_REM + "rem";
			}
		}
	};

	return HierarchicalSelect;
});
<commit_msg>[FIX] sap.uxap.HierarchicalSelect: there was a redundant tab stop<commit_after>/*!
 * ${copyright}
 */

// Provides control sap.uxap.HierarchicalSelect.
sap.ui.define(["jquery.sap.global", "sap/m/Select", "sap/ui/Device", "./library"], function (jQuery, Select, Device, library) {
	"use strict";

	/**
	 * Constructor for a new HierarchicalSelect.
	 *
	 * @param {string} [sId] id for the new control, generated automatically if no id is given
	 * @param {object} [mSettings] initial settings for the new control
	 *
	 * @class
	 * A select that display items on 2 level of hierarchy.
	 * If a provided item has a custom data named "secondLevel", then it will be displayed as a second level, otherwise it would be displayed as a first level.
	 * @extends sap.m.Select
	 *
	 * @author SAP SE
	 *
	 * @constructor
	 * @public
	 * @since 1.26
	 * @alias sap.uxap.HierarchicalSelect
	 * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
	 */
	var HierarchicalSelect = Select.extend("sap.uxap.HierarchicalSelect", /** @lends sap.uxap.HierarchicalSelect.prototype */ {
		metadata: {

			library: "sap.uxap",
			properties: {

				/**
				 * Determines whether the HierarchicalSelect items are displayed in upper case.
				 */
				upperCase: {type: "boolean", group: "Appearance", defaultValue: false}
			}
		}
	});

	HierarchicalSelect.POPOVER_MIN_WIDTH_REM = 11;

	HierarchicalSelect.prototype.onAfterRendering = function (){
		Select.prototype.onAfterRendering.apply(this, arguments);
			/*  incident 1680116122. Redundant tab comes from the select, and it's undesired */
			this.$().attr("tabindex", "-1");
	};

	HierarchicalSelect.prototype.onAfterRenderingPicker = function () {

		Select.prototype.onAfterRenderingPicker.call(this);

		var aItems = this.getItems() || [];

		aItems.forEach(function (oItem) {
			var sClass = (oItem.data("secondLevel") === true) ? "sapUxAPHierarchicalSelectSecondLevel" : "sapUxAPHierarchicalSelectFirstLevel";

			oItem.$().addClass(sClass);
		}, this);
	};

	HierarchicalSelect.prototype.setUpperCase = function (bValue, bSuppressInvalidate) {

		this.setProperty("upperCase", bValue, bSuppressInvalidate);
		this.toggleStyleClass("sapUxAPHierarchicalSelectUpperCase", bValue);
		var oPicker = this.getAggregation("picker");
		if (oPicker) {
			oPicker.toggleStyleClass("sapMSltPickerFirstLevelUpperCase", bValue);
			if (!bSuppressInvalidate) {
				oPicker.invalidate();
			}
		}
		return this;
	};

	/**
	 * Keyboard handling requirement to have the same behavior on [ENTER] key
	 * as on [SPACE] key (namely, to toggle the open state the select dropdown)
	 */
	HierarchicalSelect.prototype.onsapenter = Select.prototype.onsapspace;

	/**
	 * Keyboard handling of [UP], [PAGE-UP], [PAGE-DOWN], [HOME], [END] keys
	 * Stops propagation to avoid triggering the listeners for the same keys of the parent control (the AnchorBar)
	 */
	["onsapup", "onsappageup", "onsappagedown", "onsaphome", "onsapend"].forEach(function (sName) {
		HierarchicalSelect.prototype[sName] = function (oEvent) {
			Select.prototype[sName].call(this, oEvent);
			oEvent.stopPropagation();
		};
	});

	HierarchicalSelect.prototype._createDialog = function () {
		var oDialog = Select.prototype._createDialog.call(this),
			oCustomHeader = oDialog.getCustomHeader();

		if (oCustomHeader){
			oCustomHeader.addStyleClass("sapUxAPHierarchicalSelect");
		}

		return oDialog;

	};

	/**
	 * Decorate a Popover instance by adding some private methods.
	 *
	 * We are overriding function from sap.m.Select
	 * in order to redefine position of popover
	 *
	 * @param {sap.m.Popover}
	 * @private
	 */
	HierarchicalSelect.prototype._decoratePopover = function (oPopover) {

		Select.prototype._decoratePopover.call(this, oPopover);

		oPopover._adaptPositionParams = function () {
			this._marginTop = 0;
			this._marginLeft = 0;
			this._marginRight = 0;
			this._marginBottom = 0;

			this._arrowOffset = 0;
			this._offsets = ["0 0", "0 0", "0 0", "0 0"];

			this._myPositions = ["end bottom", "end center", "end top", "begin center"];
			this._atPositions = ["end top", "end center", "end bottom", "begin center"];
		};

		// offset the popup to make it cover the scrollbar (to avoid having page-scrollbar and popup-scrollbar appearing next to each other)
		if (Device.system.tablet || Device.system.desktop) {
			var fRight = jQuery.position.scrollbarWidth();
			if (fRight > 0) {
				oPopover.setOffsetX(fRight);
			}
		}
	};

	/**
	 * Overriding function from sap.m.Select to access min-width of the popover
	 * in order to ensure that min-width is not smaller than sap.uxap.HierarchicalSelect.POPOVER_MIN_WIDTH_REM
	 */
	HierarchicalSelect.prototype._onAfterRenderingPopover = function () {
		var oPopover = this.getPicker(),
			oPopoverDomRef = oPopover.getDomRef("cont"),
			sMinWidth = oPopoverDomRef.style.minWidth;

		if (jQuery.sap.endsWith(sMinWidth, "rem")) {
			sMinWidth = sMinWidth.substring(0, sMinWidth.length - 3);
			var iMinWidth = parseFloat(sMinWidth);
			if (iMinWidth < HierarchicalSelect.POPOVER_MIN_WIDTH_REM && oPopoverDomRef) {
				oPopoverDomRef.style.minWidth = HierarchicalSelect.POPOVER_MIN_WIDTH_REM + "rem";
			}
		}
	};

	return HierarchicalSelect;
});
<|endoftext|>


<commit_before>const AuthApi = require('../auth/auth_api');
const basicAuth = require('basic-auth');

module.exports = function authorization (userDatabaseService, forceToBeAuthenticated = false) {
    return function authorizationMiddleware (req, res, next) {
        const { user } = res.locals;
        const credentials = getCredentialsFromRequest(req, user);

        if (!userMatches(credentials, user)) {
            return next(new Error('permission denied'));
        }

        res.locals.api_key = credentials.apiKeyToken;

        const params = Object.assign({}, res.locals, req.query, req.body);
        const authApi = new AuthApi(req, res, params);

        userDatabaseService.getConnectionParams(authApi, user, function (err, userDbParams, authDbParams, userLimits) {
            if (req.profiler) {
                req.profiler.done('setDBAuth');
            }

            if (err) {
                return next(err);
            }

            if (forceToBeAuthenticated && !userDbParams.authenticated) {
                return next(new Error('permission denied'));
            }

            res.locals.userDbParams = userDbParams;
            res.locals.authDbParams = authDbParams;
            res.locals.userLimits = userLimits;

            next();
        });
    };
};

const credentialsGetters = [
    getCredentialsFromHeaderAuthorization,
    getCredentialsFromRequestQueryString,
    getCredentialsFromRequestBody,
];

function getCredentialsFromRequest (req) {
    let credentials = null;

    for (var getter of credentialsGetters) {
        credentials = getter(req);

        if (apiKeyTokenFound(credentials)) {
            break;
        }
    }

    return credentials;
}

function getCredentialsFromHeaderAuthorization(req) {
    const { pass, name } = basicAuth(req) || {};

    if (pass !== undefined && name !== undefined) {
        return {
            apiKeyToken: pass,
            user: name
        };
    }

    return false;
}

function getCredentialsFromRequestQueryString(req) {
    if (req.query.api_key) {
        return {
            apiKeyToken: req.query.api_key
        };
    }

    if (req.query.map_key) {
        return {
            apiKeyToken: req.query.map_key
        };
    }

    return false;
}

function getCredentialsFromRequestBody(req) {
    if (req.body && req.body.api_key) {
        return {
            apiKeyToken: req.body.api_key
        };
    }

    if (req.body && req.body.map_key) {
        return {
            apiKeyToken: req.body.map_key
        };
    }

    return false;
}

function apiKeyTokenFound(credentials) {
    if (typeof credentials === 'boolean') {
        return credentials;
    }

    if (credentials.apiKeyToken !== undefined) {
        return true;
    }

    return false;
}

function userMatches (credentials, user) {
    return !(credentials.user !== undefined && credentials.user !== user);
}
<commit_msg>Remove unused param<commit_after>const AuthApi = require('../auth/auth_api');
const basicAuth = require('basic-auth');

module.exports = function authorization (userDatabaseService, forceToBeAuthenticated = false) {
    return function authorizationMiddleware (req, res, next) {
        const { user } = res.locals;
        const credentials = getCredentialsFromRequest(req);

        if (!userMatches(credentials, user)) {
            return next(new Error('permission denied'));
        }

        res.locals.api_key = credentials.apiKeyToken;

        const params = Object.assign({}, res.locals, req.query, req.body);
        const authApi = new AuthApi(req, res, params);

        userDatabaseService.getConnectionParams(authApi, user, function (err, userDbParams, authDbParams, userLimits) {
            if (req.profiler) {
                req.profiler.done('setDBAuth');
            }

            if (err) {
                return next(err);
            }

            if (forceToBeAuthenticated && !userDbParams.authenticated) {
                return next(new Error('permission denied'));
            }

            res.locals.userDbParams = userDbParams;
            res.locals.authDbParams = authDbParams;
            res.locals.userLimits = userLimits;

            next();
        });
    };
};

const credentialsGetters = [
    getCredentialsFromHeaderAuthorization,
    getCredentialsFromRequestQueryString,
    getCredentialsFromRequestBody,
];

function getCredentialsFromRequest (req) {
    let credentials = null;

    for (var getter of credentialsGetters) {
        credentials = getter(req);

        if (apiKeyTokenFound(credentials)) {
            break;
        }
    }

    return credentials;
}

function getCredentialsFromHeaderAuthorization(req) {
    const { pass, name } = basicAuth(req) || {};

    if (pass !== undefined && name !== undefined) {
        return {
            apiKeyToken: pass,
            user: name
        };
    }

    return false;
}

function getCredentialsFromRequestQueryString(req) {
    if (req.query.api_key) {
        return {
            apiKeyToken: req.query.api_key
        };
    }

    if (req.query.map_key) {
        return {
            apiKeyToken: req.query.map_key
        };
    }

    return false;
}

function getCredentialsFromRequestBody(req) {
    if (req.body && req.body.api_key) {
        return {
            apiKeyToken: req.body.api_key
        };
    }

    if (req.body && req.body.map_key) {
        return {
            apiKeyToken: req.body.map_key
        };
    }

    return false;
}

function apiKeyTokenFound(credentials) {
    if (typeof credentials === 'boolean') {
        return credentials;
    }

    if (credentials.apiKeyToken !== undefined) {
        return true;
    }

    return false;
}

function userMatches (credentials, user) {
    return !(credentials.user !== undefined && credentials.user !== user);
}
<|endoftext|>