<commit_before>var util     = require('./util');
var forever  = require('forever');
var _        = require('underscore');
var async    = require('async');
var fs       = require('fs');
var db       = require('../db');
var mongodb  = require('mongodb');

exports.restartProcess = function(req, res) {

  var uid = req.params.uid;

  util.getProcessIndexbyID(uid, function(err, processIndex) {

    if (err || !processIndex) {
      GLOBAL.messages.push({ type: 'error', copy: 'Unable to find the process to restart.'});
      res.redirect('/');
      return;
    }

    forever.restart(processIndex);

    util.logNow({ type: 'notce', owner: req.session.user.github.name, name: 'Manual restart of process ' + uid, message: "User used the UI to force a restart." });

    GLOBAL.messages.push({ type: 'info', copy: 'Restarting and existing process.'});
    res.redirect('/');
  });

}

exports.slugDelete = function(req, res) {

  var id = req.params.id;

  var exec = require('child_process').exec;

  var path = GLOBAL.root + '/tmp/' + id;
  var cmd = 'rm -Rf ' + path;

  var deleteConfirm = function (error, stdout, stderr) {
    GLOBAL.messages.push({ type: 'error', copy: 'Deleted the slug at ' + path + ' with ' + cmd });
    res.redirect('/sites');
  }

  exec(cmd, deleteConfirm);

}

exports.sites = function(req, res) {

  util.getBuilds(function(err, data) {
    res.render('sites', { data: data });
  });

}

exports.startDialog = function(req, res) {

  var shaOrBranch = req.params.sha;

  var githubAPI  = require('github');
  var github = new githubAPI({ version: '3.0.0' });
  github.authenticate({ type: 'oauth', token: req.session.user.access_token });

  var options = {
    repo:   GLOBAL.config.repository.repo,
    user:   GLOBAL.config.repository.user
  };

  var process_type = req.urlparams.process_type || 'snapshot';

  github.repos.getBranches(options, function(err, data) {
    res.render('build_commit', { process_type: process_type, branches: data, id: shaOrBranch } );
  });

}

exports.startProcess = function(req, res) {

  var sha                   = req.body.sha;
  var reference_name        = req.body.reference_name || 'Manual Build ' + sha;
  var reference_description = req.body.reference_description || '';
  var environment           = req.body.environment || 'development';
  var max_attempts          = req.body.max_attempts || 5;
  var process_type          = req.body.process_type || 'snapshot';

  // Check if we have the process running.
  util.getProcessIndexbySHA(sha, function(err, currentProcessIdx) {

    if (currentProcessIdx == -1) {

       // No Love. Since we did not find what we needed. we need to build it.

       var options = {
         type:        process_type,
         sha:         sha,
         name:        reference_name,
         description: reference_description,
         max:         max_attempts,
         environment: environment,
         owner:       req.session.user.github.name || 'CI',
         // PORT:     port,
         // Domain:   domain
       };

       util.logNow({
         type:    'manual',
         name:    'New ' + process_type.toUpperCase() + ' build',
         message: req.session.user.github.name + ' has manually created a ' + process_type + ' build.'
       });

       util.setupBuild(options, function(err, data) {
         res.redirect('/');
       });

    } else {

       // We have it, so restart it.
       // Use the following to rebuild the git status and

       util.logNow({
         type:    'manual',
         name:    'Refreshing a ' + process_type.toUpperCase() + ' build',
         message: req.session.user.github.name + ' has manually requested to add/refresh a ' + process_type + ' build.'
       });

       util.restartBuild(sha, function(err, data) {
         res.redirect('/');
       });

    }
  });

}

exports.stopProcess = function(req, res) {

  var uid = req.params.uid;

  util.getProcessIndexbyID(uid, function(err, processIndex) {

    if (err) {
      GLOBAL.messages.push({ type: 'error', copy: 'Unable to find the process to stop.'});
      res.redirect('/');
      return;
    }

    if (!processIndex) {
      GLOBAL.messages.push({ type: 'error', copy: 'Unable to find the process using UID, attempting Index.'});
      processIndex = parseInt(req.params.index);
    }

    util.logNow({ owner: req.session.user.github.name, name: 'Stopping Process', message: 'Manual Action to stop a process, idx: ' + processIndex });

    forever.stop(processIndex);

    GLOBAL.messages.push({ type: 'info', copy: 'Stopping the build process.'});
    res.redirect('/');
  });

}

exports.cleanupProcesses = function(req, res) {

  forever.cleanUp();

  GLOBAL.messages.push({ type: 'info', copy: 'Running the forever cleanup processes.'});

  util.logNow({ name: 'Process Cleanup', message: 'User requested the Process Cleanup for forever tasks' });

  res.redirect('/');
}

exports.buildCommitSlug = function(req, res) {

  var sha = req.params.sha;

  var exec = require('child_process').exec;

  function puts(error, stdout, stderr) {
    console.log('Completed the commit setup.')

    GLOBAL.messages.push({ type: 'info', copy: 'Building... Might take a bit.' });
    res.redirect('/');
  }

  var pdir = GLOBAL.root + '/tmp/' + sha;

  var command = 'rm -Rf ' + pdir + '; ' +
                'git clone git@github.com:npr/composer.git ' + pdir + '; ' +
                'GIT_WORK_TREE=' + pdir + ' git --git-dir=' + pdir + '/.git --work-tree=' + pdir + ' checkout ' + sha

  GLOBAL.messages.push({ type: 'info', copy: 'Buidling an install from a commit.' });
  GLOBAL.messages.push({ type: 'info', copy: 'Commit SHA: ' + sha });
  GLOBAL.messages.push({ type: 'info', copy: 'Build Path: ' + pdir });
  GLOBAL.messages.push({ type: 'info', copy: command });

  exec(command, puts);

}

exports.listProcesses = function(req, res) {

  async.parallel({
    builds: function(callback) {

      util.getBuilds(function(err, data) {
        callback(null, data);
      });

    },
    sites: function(callback) {

      util.getSites(function(err, data) {
        callback(null, data);
      });

    },
    activity: function(callback) {

      var query = {};
      var options = { "sort": [['timestamp','desc']] };

      var collection = new mongodb.Collection(DbManager.getDb(), 'logs');
      collection.find(query, options).limit(5).toArray(function(err, data) {
        if (err || !data) {
          cb(null, 'No Episiodes found.');
          return
        }

        callback(null, data);
      });

    },
    branches: function(callback) {

      if (!req.session.user) {
        callback(null, null)
      } else {
        util.getBranches(req.session, function(err, data) {
          callback(null, data);
        });
      }

    }
  }, function(err, data) {

    res.render('list', { branches: data.branches, activity: data.activity, sites: data.sites, builds: data.builds, messages: GLOBAL.messages } );
    GLOBAL.messages = [];
  });

}

exports.tailProcessLog = function(req, res) {

  var uid = req.params.uid;

  util.getProcessIndexbyID(uid, function(err, processIndex) {

    if (err || !processIndex) {
      GLOBAL.messages.push({ type: 'error', copy: 'Unable to fetch the requested process.'});
      res.redirect('/');
      return;
    }

    forever.tail(processIndex, function (err, data) {

      if (err || !data) {
        GLOBAL.messages.push({ type: 'error', copy: 'Unable to fetch tail information the requested process.'});
        res.redirect('/');
        return;
      }

      res.render('tail', { data: data } );
    })

  });

}

/**

 This function provides process details. It wrapps the the forever.list() function.
 It accepts an ID and finds the required process.

**/
exports.processDetail = function(req, res) {

  var uid = req.params.id;

  util.getProcessByID(uid, function(err, process) {

    if (err || !process) {
      GLOBAL.messages.push({ type: 'error', copy: 'Unable to fetch the requested process.'});
      res.redirect('/');
      return;
    }

    res.render('detail', { data: process } );
  });

}

/**

  This function handles the github commit payloads
  generated by the webhooks when a commit it reveived
  by github.

  This is a new version that will rebuild a given folder and
  will restart the correct builds.

**/
exports.catchCommitPayloadv2 = function(req, res) {

  var load = JSON.parse(req.body.payload);

  var sha = load.ref.replace('refs/heads/', '').trim();

  util.getProcessIndexbySHA(sha, function(err, currentProcessIdx) {

    if (currentProcessIdx == -1) {

       var options = {
         type:        'hook',
         sha:         sha,
         name:        'Hook Tracking',
         description: 'Github Web hook delivered ' + sha,
         environment: 'development',
         owner:       'CI'
       };

       util.setupBuild(options, function(err, data) {
         if (err) return util.logNow({type: 'hook', name: 'Github Hook Start Failed', message: 'A github webhook requested failed ' + err.message });

         util.logNow({ type: 'hook', name: 'Github Hook Build Complete', message: 'A github webhook requested setup the branch ' + ref });
       });
    } else {
       util.restartBuild(sha, function(err, data) {
         if (err) return util.logNow({type: 'hook', name: 'Github Hook Restart Failed', message: 'A github webhook requested failed ' + err.message });

         util.logNow({ type: 'hook', name: 'Github Hook Rebuild Complete', message: 'A github webhook requested rebuild the branch ' + ref });
       });
    }
  });

}
<commit_msg>Typo on var name.<commit_after>var util     = require('./util');
var forever  = require('forever');
var _        = require('underscore');
var async    = require('async');
var fs       = require('fs');
var db       = require('../db');
var mongodb  = require('mongodb');

exports.restartProcess = function(req, res) {

  var uid = req.params.uid;

  util.getProcessIndexbyID(uid, function(err, processIndex) {

    if (err || !processIndex) {
      GLOBAL.messages.push({ type: 'error', copy: 'Unable to find the process to restart.'});
      res.redirect('/');
      return;
    }

    forever.restart(processIndex);

    util.logNow({ type: 'notce', owner: req.session.user.github.name, name: 'Manual restart of process ' + uid, message: "User used the UI to force a restart." });

    GLOBAL.messages.push({ type: 'info', copy: 'Restarting and existing process.'});
    res.redirect('/');
  });

}

exports.slugDelete = function(req, res) {

  var id = req.params.id;

  var exec = require('child_process').exec;

  var path = GLOBAL.root + '/tmp/' + id;
  var cmd = 'rm -Rf ' + path;

  var deleteConfirm = function (error, stdout, stderr) {
    GLOBAL.messages.push({ type: 'error', copy: 'Deleted the slug at ' + path + ' with ' + cmd });
    res.redirect('/sites');
  }

  exec(cmd, deleteConfirm);

}

exports.sites = function(req, res) {

  util.getBuilds(function(err, data) {
    res.render('sites', { data: data });
  });

}

exports.startDialog = function(req, res) {

  var shaOrBranch = req.params.sha;

  var githubAPI  = require('github');
  var github = new githubAPI({ version: '3.0.0' });
  github.authenticate({ type: 'oauth', token: req.session.user.access_token });

  var options = {
    repo:   GLOBAL.config.repository.repo,
    user:   GLOBAL.config.repository.user
  };

  var process_type = req.urlparams.process_type || 'snapshot';

  github.repos.getBranches(options, function(err, data) {
    res.render('build_commit', { process_type: process_type, branches: data, id: shaOrBranch } );
  });

}

exports.startProcess = function(req, res) {

  var sha                   = req.body.sha;
  var reference_name        = req.body.reference_name || 'Manual Build ' + sha;
  var reference_description = req.body.reference_description || '';
  var environment           = req.body.environment || 'development';
  var max_attempts          = req.body.max_attempts || 5;
  var process_type          = req.body.process_type || 'snapshot';

  // Check if we have the process running.
  util.getProcessIndexbySHA(sha, function(err, currentProcessIdx) {

    if (currentProcessIdx == -1) {

       // No Love. Since we did not find what we needed. we need to build it.

       var options = {
         type:        process_type,
         sha:         sha,
         name:        reference_name,
         description: reference_description,
         max:         max_attempts,
         environment: environment,
         owner:       req.session.user.github.name || 'CI',
         // PORT:     port,
         // Domain:   domain
       };

       util.logNow({
         type:    'manual',
         name:    'New ' + process_type.toUpperCase() + ' build',
         message: req.session.user.github.name + ' has manually created a ' + process_type + ' build.'
       });

       util.setupBuild(options, function(err, data) {
         res.redirect('/');
       });

    } else {

       // We have it, so restart it.
       // Use the following to rebuild the git status and

       util.logNow({
         type:    'manual',
         name:    'Refreshing a ' + process_type.toUpperCase() + ' build',
         message: req.session.user.github.name + ' has manually requested to add/refresh a ' + process_type + ' build.'
       });

       util.restartBuild(sha, function(err, data) {
         res.redirect('/');
       });

    }
  });

}

exports.stopProcess = function(req, res) {

  var uid = req.params.uid;

  util.getProcessIndexbyID(uid, function(err, processIndex) {

    if (err) {
      GLOBAL.messages.push({ type: 'error', copy: 'Unable to find the process to stop.'});
      res.redirect('/');
      return;
    }

    if (!processIndex) {
      GLOBAL.messages.push({ type: 'error', copy: 'Unable to find the process using UID, attempting Index.'});
      processIndex = parseInt(req.params.index);
    }

    util.logNow({ owner: req.session.user.github.name, name: 'Stopping Process', message: 'Manual Action to stop a process, idx: ' + processIndex });

    forever.stop(processIndex);

    GLOBAL.messages.push({ type: 'info', copy: 'Stopping the build process.'});
    res.redirect('/');
  });

}

exports.cleanupProcesses = function(req, res) {

  forever.cleanUp();

  GLOBAL.messages.push({ type: 'info', copy: 'Running the forever cleanup processes.'});

  util.logNow({ name: 'Process Cleanup', message: 'User requested the Process Cleanup for forever tasks' });

  res.redirect('/');
}

exports.buildCommitSlug = function(req, res) {

  var sha = req.params.sha;

  var exec = require('child_process').exec;

  function puts(error, stdout, stderr) {
    console.log('Completed the commit setup.')

    GLOBAL.messages.push({ type: 'info', copy: 'Building... Might take a bit.' });
    res.redirect('/');
  }

  var pdir = GLOBAL.root + '/tmp/' + sha;

  var command = 'rm -Rf ' + pdir + '; ' +
                'git clone git@github.com:npr/composer.git ' + pdir + '; ' +
                'GIT_WORK_TREE=' + pdir + ' git --git-dir=' + pdir + '/.git --work-tree=' + pdir + ' checkout ' + sha

  GLOBAL.messages.push({ type: 'info', copy: 'Buidling an install from a commit.' });
  GLOBAL.messages.push({ type: 'info', copy: 'Commit SHA: ' + sha });
  GLOBAL.messages.push({ type: 'info', copy: 'Build Path: ' + pdir });
  GLOBAL.messages.push({ type: 'info', copy: command });

  exec(command, puts);

}

exports.listProcesses = function(req, res) {

  async.parallel({
    builds: function(callback) {

      util.getBuilds(function(err, data) {
        callback(null, data);
      });

    },
    sites: function(callback) {

      util.getSites(function(err, data) {
        callback(null, data);
      });

    },
    activity: function(callback) {

      var query = {};
      var options = { "sort": [['timestamp','desc']] };

      var collection = new mongodb.Collection(DbManager.getDb(), 'logs');
      collection.find(query, options).limit(5).toArray(function(err, data) {
        if (err || !data) {
          cb(null, 'No Episiodes found.');
          return
        }

        callback(null, data);
      });

    },
    branches: function(callback) {

      if (!req.session.user) {
        callback(null, null)
      } else {
        util.getBranches(req.session, function(err, data) {
          callback(null, data);
        });
      }

    }
  }, function(err, data) {

    res.render('list', { branches: data.branches, activity: data.activity, sites: data.sites, builds: data.builds, messages: GLOBAL.messages } );
    GLOBAL.messages = [];
  });

}

exports.tailProcessLog = function(req, res) {

  var uid = req.params.uid;

  util.getProcessIndexbyID(uid, function(err, processIndex) {

    if (err || !processIndex) {
      GLOBAL.messages.push({ type: 'error', copy: 'Unable to fetch the requested process.'});
      res.redirect('/');
      return;
    }

    forever.tail(processIndex, function (err, data) {

      if (err || !data) {
        GLOBAL.messages.push({ type: 'error', copy: 'Unable to fetch tail information the requested process.'});
        res.redirect('/');
        return;
      }

      res.render('tail', { data: data } );
    })

  });

}

/**

 This function provides process details. It wrapps the the forever.list() function.
 It accepts an ID and finds the required process.

**/
exports.processDetail = function(req, res) {

  var uid = req.params.id;

  util.getProcessByID(uid, function(err, process) {

    if (err || !process) {
      GLOBAL.messages.push({ type: 'error', copy: 'Unable to fetch the requested process.'});
      res.redirect('/');
      return;
    }

    res.render('detail', { data: process } );
  });

}

/**

  This function handles the github commit payloads
  generated by the webhooks when a commit it reveived
  by github.

  This is a new version that will rebuild a given folder and
  will restart the correct builds.

**/
exports.catchCommitPayloadv2 = function(req, res) {

  var load = JSON.parse(req.body.payload);

  var sha = load.ref.replace('refs/heads/', '').trim();

  util.getProcessIndexbySHA(sha, function(err, currentProcessIdx) {

    if (currentProcessIdx == -1) {

       var options = {
         type:        'hook',
         sha:         sha,
         name:        'Hook Tracking',
         description: 'Github Web hook delivered ' + sha,
         environment: 'development',
         owner:       'CI'
       };

       util.setupBuild(options, function(err, data) {
         if (err) return util.logNow({type: 'hook', name: 'Github Hook Start Failed', message: 'A github webhook requested failed ' + err.message });

         util.logNow({ type: 'hook', name: 'Github Hook Build Complete', message: 'A github webhook requested setup the branch ' + sha + ' ' + load.ref });
       });
    } else {
       util.restartBuild(sha, function(err, data) {
         if (err) return util.logNow({type: 'hook', name: 'Github Hook Restart Failed', message: 'A github webhook requested failed ' + err.message });

         util.logNow({ type: 'hook', name: 'Github Hook Rebuild Complete', message: 'A github webhook requested rebuild the branch ' + sha + ' ' + load.ref });
       });
    }
  });

}
<|endoftext|>


<commit_before>/******************************************************************************
 * Copyright © 2016 The Waves Core Developers.                             	  *
 *                                                                            *
 * See the LICENSE files at     											  *
 * the top-level directory of this distribution for the individual copyright  *
 * holder information and the developer policies on copyright and licensing.  *
 *                                                                            *
 * Unless otherwise agreed in a custom licensing agreement, no part of the    *
 * Waves software, including this file, may be copied, modified, propagated,  *
 * or distributed except according to the terms contained in the LICENSE.txt  *
 * file.                                                                      *
 *                                                                            *
 * Removal or modification of this copyright notice is prohibited.            *
 *                                                                            *
 ******************************************************************************/

/**
 * @depends {../3rdparty/jquery-2.1.0.js}
 */

var PassPhraseGenerator = {
	seeds: 0,
	seedLimit: 512,

	push: function(seed) {
		Math.seedrandom(seed, true);
		this.seeds++;
	},

	isDone: function() {
		if (this.seeds == this.seedLimit) {
			return true;
		}
		return false;
	},

	percentage: function() {
		return Math.round((this.seeds / this.seedLimit) * 100)
	},

	passPhrase: "",

	wordCount: 1626,

	words: ["like", "just", "love", "know", "never", "want", "time", "out", "there", "make", "look", "eye", "down", "only", "think", "heart", "back", "then", "into", "about", "more", "away", "still", "them", "take", "thing", "even", "through", "long", "always", "world", "too", "friend", "tell", "try", "hand", "thought", "over", "here", "other", "need", "smile", "again", "much", "cry", "been", "night", "ever", "little", "said", "end", "some", "those", "around", "mind", "people", "girl", "leave", "dream", "left", "turn", "myself", "give", "nothing", "really", "off", "before", "something", "find", "walk", "wish", "good", "once", "place", "ask", "stop", "keep", "watch", "seem", "everything", "wait", "got", "yet", "made", "remember", "start", "alone", "run", "hope", "maybe", "believe", "body", "hate", "after", "close", "talk", "stand", "own", "each", "hurt", "help", "home", "god", "soul", "new", "many", "two", "inside", "should", "true", "first", "fear", "mean", "better", "play", "another", "gone", "change", "use", "wonder", "someone", "hair", "cold", "open", "best", "any", "behind", "happen", "water", "dark", "laugh", "stay", "forever", "name", "work", "show", "sky", "break", "came", "deep", "door", "put", "black", "together", "upon", "happy", "such", "great", "white", "matter", "fill", "past", "please", "burn", "cause", "enough", "touch", "moment", "soon", "voice", "scream", "anything", "stare", "sound", "red", "everyone", "hide", "kiss", "truth", "death", "beautiful", "mine", "blood", "broken", "very", "pass", "next", "forget", "tree", "wrong", "air", "mother", "understand", "lip", "hit", "wall", "memory", "sleep", "free", "high", "realize", "school", "might", "skin", "sweet", "perfect", "blue", "kill", "breath", "dance", "against", "fly", "between", "grow", "strong", "under", "listen", "bring", "sometimes", "speak", "pull", "person", "become", "family", "begin", "ground", "real", "small", "father", "sure", "feet", "rest", "young", "finally", "land", "across", "today", "different", "guy", "line", "fire", "reason", "reach", "second", "slowly", "write", "eat", "smell", "mouth", "step", "learn", "three", "floor", "promise", "breathe", "darkness", "push", "earth", "guess", "save", "song", "above", "along", "both", "color", "house", "almost", "sorry", "anymore", "brother", "okay", "dear", "game", "fade", "already", "apart", "warm", "beauty", "heard", "notice", "question", "shine", "began", "piece", "whole", "shadow", "secret", "street", "within", "finger", "point", "morning", "whisper", "child", "moon", "green", "story", "glass", "kid", "silence", "since", "soft", "yourself", "empty", "shall", "angel", "answer", "baby", "bright", "dad", "path", "worry", "hour", "drop", "follow", "power", "war", "half", "flow", "heaven", "act", "chance", "fact", "least", "tired", "children", "near", "quite", "afraid", "rise", "sea", "taste", "window", "cover", "nice", "trust", "lot", "sad", "cool", "force", "peace", "return", "blind", "easy", "ready", "roll", "rose", "drive", "held", "music", "beneath", "hang", "mom", "paint", "emotion", "quiet", "clear", "cloud", "few", "pretty", "bird", "outside", "paper", "picture", "front", "rock", "simple", "anyone", "meant", "reality", "road", "sense", "waste", "bit", "leaf", "thank", "happiness", "meet", "men", "smoke", "truly", "decide", "self", "age", "book", "form", "alive", "carry", "escape", "damn", "instead", "able", "ice", "minute", "throw", "catch", "leg", "ring", "course", "goodbye", "lead", "poem", "sick", "corner", "desire", "known", "problem", "remind", "shoulder", "suppose", "toward", "wave", "drink", "jump", "woman", "pretend", "sister", "week", "human", "joy", "crack", "grey", "pray", "surprise", "dry", "knee", "less", "search", "bleed", "caught", "clean", "embrace", "future", "king", "son", "sorrow", "chest", "hug", "remain", "sat", "worth", "blow", "daddy", "final", "parent", "tight", "also", "create", "lonely", "safe", "cross", "dress", "evil", "silent", "bone", "fate", "perhaps", "anger", "class", "scar", "snow", "tiny", "tonight", "continue", "control", "dog", "edge", "mirror", "month", "suddenly", "comfort", "given", "loud", "quickly", "gaze", "plan", "rush", "stone", "town", "battle", "ignore", "spirit", "stood", "stupid", "yours", "brown", "build", "dust", "hey", "kept", "pay", "phone", "twist", "although", "ball", "beyond", "hidden", "nose", "taken", "fail", "float", "pure", "somehow", "wash", "wrap", "angry", "cheek", "creature", "forgotten", "heat", "rip", "single", "space", "special", "weak", "whatever", "yell", "anyway", "blame", "job", "choose", "country", "curse", "drift", "echo", "figure", "grew", "laughter", "neck", "suffer", "worse", "yeah", "disappear", "foot", "forward", "knife", "mess", "somewhere", "stomach", "storm", "beg", "idea", "lift", "offer", "breeze", "field", "five", "often", "simply", "stuck", "win", "allow", "confuse", "enjoy", "except", "flower", "seek", "strength", "calm", "grin", "gun", "heavy", "hill", "large", "ocean", "shoe", "sigh", "straight", "summer", "tongue", "accept", "crazy", "everyday", "exist", "grass", "mistake", "sent", "shut", "surround", "table", "ache", "brain", "destroy", "heal", "nature", "shout", "sign", "stain", "choice", "doubt", "glance", "glow", "mountain", "queen", "stranger", "throat", "tomorrow", "city", "either", "fish", "flame", "rather", "shape", "spin", "spread", "ash", "distance", "finish", "image", "imagine", "important", "nobody", "shatter", "warmth", "became", "feed", "flesh", "funny", "lust", "shirt", "trouble", "yellow", "attention", "bare", "bite", "money", "protect", "amaze", "appear", "born", "choke", "completely", "daughter", "fresh", "friendship", "gentle", "probably", "six", "deserve", "expect", "grab", "middle", "nightmare", "river", "thousand", "weight", "worst", "wound", "barely", "bottle", "cream", "regret", "relationship", "stick", "test", "crush", "endless", "fault", "itself", "rule", "spill", "art", "circle", "join", "kick", "mask", "master", "passion", "quick", "raise", "smooth", "unless", "wander", "actually", "broke", "chair", "deal", "favorite", "gift", "note", "number", "sweat", "box", "chill", "clothes", "lady", "mark", "park", "poor", "sadness", "tie", "animal", "belong", "brush", "consume", "dawn", "forest", "innocent", "pen", "pride", "stream", "thick", "clay", "complete", "count", "draw", "faith", "press", "silver", "struggle", "surface", "taught", "teach", "wet", "bless", "chase", "climb", "enter", "letter", "melt", "metal", "movie", "stretch", "swing", "vision", "wife", "beside", "crash", "forgot", "guide", "haunt", "joke", "knock", "plant", "pour", "prove", "reveal", "steal", "stuff", "trip", "wood", "wrist", "bother", "bottom", "crawl", "crowd", "fix", "forgive", "frown", "grace", "loose", "lucky", "party", "release", "surely", "survive", "teacher", "gently", "grip", "speed", "suicide", "travel", "treat", "vein", "written", "cage", "chain", "conversation", "date", "enemy", "however", "interest", "million", "page", "pink", "proud", "sway", "themselves", "winter", "church", "cruel", "cup", "demon", "experience", "freedom", "pair", "pop", "purpose", "respect", "shoot", "softly", "state", "strange", "bar", "birth", "curl", "dirt", "excuse", "lord", "lovely", "monster", "order", "pack", "pants", "pool", "scene", "seven", "shame", "slide", "ugly", "among", "blade", "blonde", "closet", "creek", "deny", "drug", "eternity", "gain", "grade", "handle", "key", "linger", "pale", "prepare", "swallow", "swim", "tremble", "wheel", "won", "cast", "cigarette", "claim", "college", "direction", "dirty", "gather", "ghost", "hundred", "loss", "lung", "orange", "present", "swear", "swirl", "twice", "wild", "bitter", "blanket", "doctor", "everywhere", "flash", "grown", "knowledge", "numb", "pressure", "radio", "repeat", "ruin", "spend", "unknown", "buy", "clock", "devil", "early", "false", "fantasy", "pound", "precious", "refuse", "sheet", "teeth", "welcome", "add", "ahead", "block", "bury", "caress", "content", "depth", "despite", "distant", "marry", "purple", "threw", "whenever", "bomb", "dull", "easily", "grasp", "hospital", "innocence", "normal", "receive", "reply", "rhyme", "shade", "someday", "sword", "toe", "visit", "asleep", "bought", "center", "consider", "flat", "hero", "history", "ink", "insane", "muscle", "mystery", "pocket", "reflection", "shove", "silently", "smart", "soldier", "spot", "stress", "train", "type", "view", "whether", "bus", "energy", "explain", "holy", "hunger", "inch", "magic", "mix", "noise", "nowhere", "prayer", "presence", "shock", "snap", "spider", "study", "thunder", "trail", "admit", "agree", "bag", "bang", "bound", "butterfly", "cute", "exactly", "explode", "familiar", "fold", "further", "pierce", "reflect", "scent", "selfish", "sharp", "sink", "spring", "stumble", "universe", "weep", "women", "wonderful", "action", "ancient", "attempt", "avoid", "birthday", "branch", "chocolate", "core", "depress", "drunk", "especially", "focus", "fruit", "honest", "match", "palm", "perfectly", "pillow", "pity", "poison", "roar", "shift", "slightly", "thump", "truck", "tune", "twenty", "unable", "wipe", "wrote", "coat", "constant", "dinner", "drove", "egg", "eternal", "flight", "flood", "frame", "freak", "gasp", "glad", "hollow", "motion", "peer", "plastic", "root", "screen", "season", "sting", "strike", "team", "unlike", "victim", "volume", "warn", "weird", "attack", "await", "awake", "built", "charm", "crave", "despair", "fought", "grant", "grief", "horse", "limit", "message", "ripple", "sanity", "scatter", "serve", "split", "string", "trick", "annoy", "blur", "boat", "brave", "clearly", "cling", "connect", "fist", "forth", "imagination", "iron", "jock", "judge", "lesson", "milk", "misery", "nail", "naked", "ourselves", "poet", "possible", "princess", "sail", "size", "snake", "society", "stroke", "torture", "toss", "trace", "wise", "bloom", "bullet", "cell", "check", "cost", "darling", "during", "footstep", "fragile", "hallway", "hardly", "horizon", "invisible", "journey", "midnight", "mud", "nod", "pause", "relax", "shiver", "sudden", "value", "youth", "abuse", "admire", "blink", "breast", "bruise", "constantly", "couple", "creep", "curve", "difference", "dumb", "emptiness", "gotta", "honor", "plain", "planet", "recall", "rub", "ship", "slam", "soar", "somebody", "tightly", "weather", "adore", "approach", "bond", "bread", "burst", "candle", "coffee", "cousin", "crime", "desert", "flutter", "frozen", "grand", "heel", "hello", "language", "level", "movement", "pleasure", "powerful", "random", "rhythm", "settle", "silly", "slap", "sort", "spoken", "steel", "threaten", "tumble", "upset", "aside", "awkward", "bee", "blank", "board", "button", "card", "carefully", "complain", "crap", "deeply", "discover", "drag", "dread", "effort", "entire", "fairy", "giant", "gotten", "greet", "illusion", "jeans", "leap", "liquid", "march", "mend", "nervous", "nine", "replace", "rope", "spine", "stole", "terror", "accident", "apple", "balance", "boom", "childhood", "collect", "demand", "depression", "eventually", "faint", "glare", "goal", "group", "honey", "kitchen", "laid", "limb", "machine", "mere", "mold", "murder", "nerve", "painful", "poetry", "prince", "rabbit", "shelter", "shore", "shower", "soothe", "stair", "steady", "sunlight", "tangle", "tease", "treasure", "uncle", "begun", "bliss", "canvas", "cheer", "claw", "clutch", "commit", "crimson", "crystal", "delight", "doll", "existence", "express", "fog", "football", "gay", "goose", "guard", "hatred", "illuminate", "mass", "math", "mourn", "rich", "rough", "skip", "stir", "student", "style", "support", "thorn", "tough", "yard", "yearn", "yesterday", "advice", "appreciate", "autumn", "bank", "beam", "bowl", "capture", "carve", "collapse", "confusion", "creation", "dove", "feather", "girlfriend", "glory", "government", "harsh", "hop", "inner", "loser", "moonlight", "neighbor", "neither", "peach", "pig", "praise", "screw", "shield", "shimmer", "sneak", "stab", "subject", "throughout", "thrown", "tower", "twirl", "wow", "army", "arrive", "bathroom", "bump", "cease", "cookie", "couch", "courage", "dim", "guilt", "howl", "hum", "husband", "insult", "led", "lunch", "mock", "mostly", "natural", "nearly", "needle", "nerd", "peaceful", "perfection", "pile", "price", "remove", "roam", "sanctuary", "serious", "shiny", "shook", "sob", "stolen", "tap", "vain", "void", "warrior", "wrinkle", "affection", "apologize", "blossom", "bounce", "bridge", "cheap", "crumble", "decision", "descend", "desperately", "dig", "dot", "flip", "frighten", "heartbeat", "huge", "lazy", "lick", "odd", "opinion", "process", "puzzle", "quietly", "retreat", "score", "sentence", "separate", "situation", "skill", "soak", "square", "stray", "taint", "task", "tide", "underneath", "veil", "whistle", "anywhere", "bedroom", "bid", "bloody", "burden", "careful", "compare", "concern", "curtain", "decay", "defeat", "describe", "double", "dreamer", "driver", "dwell", "evening", "flare", "flicker", "grandma", "guitar", "harm", "horrible", "hungry", "indeed", "lace", "melody", "monkey", "nation", "object", "obviously", "rainbow", "salt", "scratch", "shown", "shy", "stage", "stun", "third", "tickle", "useless", "weakness", "worship", "worthless", "afternoon", "beard", "boyfriend", "bubble", "busy", "certain", "chin", "concrete", "desk", "diamond", "doom", "drawn", "due", "felicity", "freeze", "frost", "garden", "glide", "harmony", "hopefully", "hunt", "jealous", "lightning", "mama", "mercy", "peel", "physical", "position", "pulse", "punch", "quit", "rant", "respond", "salty", "sane", "satisfy", "savior", "sheep", "slept", "social", "sport", "tuck", "utter", "valley", "wolf", "aim", "alas", "alter", "arrow", "awaken", "beaten", "belief", "brand", "ceiling", "cheese", "clue", "confidence", "connection", "daily", "disguise", "eager", "erase", "essence", "everytime", "expression", "fan", "flag", "flirt", "foul", "fur", "giggle", "glorious", "ignorance", "law", "lifeless", "measure", "mighty", "muse", "north", "opposite", "paradise", "patience", "patient", "pencil", "petal", "plate", "ponder", "possibly", "practice", "slice", "spell", "stock", "strife", "strip", "suffocate", "suit", "tender", "tool", "trade", "velvet", "verse", "waist", "witch", "aunt", "bench", "bold", "cap", "certainly", "click", "companion", "creator", "dart", "delicate", "determine", "dish", "dragon", "drama", "drum", "dude", "everybody", "feast", "forehead", "former", "fright", "fully", "gas", "hook", "hurl", "invite", "juice", "manage", "moral", "possess", "raw", "rebel", "royal", "scale", "scary", "several", "slight", "stubborn", "swell", "talent", "tea", "terrible", "thread", "torment", "trickle", "usually", "vast", "violence", "weave", "acid", "agony", "ashamed", "awe", "belly", "blend", "blush", "character", "cheat", "common", "company", "coward", "creak", "danger", "deadly", "defense", "define", "depend", "desperate", "destination", "dew", "duck", "dusty", "embarrass", "engine", "example", "explore", "foe", "freely", "frustrate", "generation", "glove", "guilty", "health", "hurry", "idiot", "impossible", "inhale", "jaw", "kingdom", "mention", "mist", "moan", "mumble", "mutter", "observe", "ode", "pathetic", "pattern", "pie", "prefer", "puff", "rape", "rare", "revenge", "rude", "scrape", "spiral", "squeeze", "strain", "sunset", "suspend", "sympathy", "thigh", "throne", "total", "unseen", "weapon", "weary"],

	generatePassPhrase: function() {

		var crypto = window.crypto || window.msCrypto;

		bits = 128;

		var random = new Uint32Array(bits / 32);

		crypto.getRandomValues(random);

		var i = 0,
			l = random.length,
			n = this.wordCount,
			words = [],
			x, w1, w2, w3;

		for (; i < l; i++) {
			x = random[i];
			w1 = x % n;
			w2 = (((x / n) >> 0) + w1) % n;
			w3 = (((((x / n) >> 0) / n) >> 0) + w2) % n;

			words.push(this.words[w1]);
			words.push(this.words[w2]);
			words.push(this.words[w3]);
		}

		this.passPhrase = words.join(" ");

		crypto.getRandomValues(random);

		return this.passPhrase;
	},

	reset: function() {
		this.passPhrase = "";
		this.seeds = 0;
	}
}<commit_msg>adding words<commit_after>/******************************************************************************
 * Copyright © 2016 The Waves Core Developers.                             	  *
 *                                                                            *
 * See the LICENSE files at     											  *
 * the top-level directory of this distribution for the individual copyright  *
 * holder information and the developer policies on copyright and licensing.  *
 *                                                                            *
 * Unless otherwise agreed in a custom licensing agreement, no part of the    *
 * Waves software, including this file, may be copied, modified, propagated,  *
 * or distributed except according to the terms contained in the LICENSE.txt  *
 * file.                                                                      *
 *                                                                            *
 * Removal or modification of this copyright notice is prohibited.            *
 *                                                                            *
 ******************************************************************************/

/**
 * @depends {../3rdparty/jquery-2.1.0.js}
 */

var PassPhraseGenerator = {
	seeds: 0,
	seedLimit: 512,

	push: function(seed) {
		Math.seedrandom(seed, true);
		this.seeds++;
	},

	isDone: function() {
		if (this.seeds == this.seedLimit) {
			return true;
		}
		return false;
	},

	percentage: function() {
		return Math.round((this.seeds / this.seedLimit) * 100)
	},

	passPhrase: "",

	wordCount: 2048,

	words: ClientWordList,

	generatePassPhrase: function() {

		var crypto = window.crypto || window.msCrypto;

		bits = 160;

		var random = new Uint32Array(bits / 32);

		crypto.getRandomValues(random);

		var i = 0,
			l = random.length,
			n = this.wordCount,
			words = [],
			x, w1, w2, w3;

		for (; i < l; i++) {
			x = random[i];
			w1 = x % n;
			w2 = (((x / n) >> 0) + w1) % n;
			w3 = (((((x / n) >> 0) / n) >> 0) + w2) % n;

			words.push(this.words[w1]);
			words.push(this.words[w2]);
			words.push(this.words[w3]);
		}

		this.passPhrase = words.join(" ");

		crypto.getRandomValues(random);

		return this.passPhrase;
	},

	reset: function() {
		this.passPhrase = "";
		this.seeds = 0;
	}
}<|endoftext|>


<commit_before>/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

/*
 * Copyright (c) 2014, Joyent, Inc.
 */

var Task = require('../task_agent/task');
var VM  = require('/usr/vm/node_modules/VM');
var async = require('async');
var common = require('../common');
var fs = require('fs');
var imgadm = require('../imgadm');
var kvmdebug = require('./kvmdebug');
var path = require('path');
var spawn = require('child_process').spawn;
var util = require('util');
var zfs = require('zfs').zfs;

var kvm_debugging = false;

var MachineCreateTask = module.exports = function (req) {
    Task.call(this);
    this.req = req;
    this.zpool = req.params.zfs_storage_pool_name || 'zones';
};

Task.createTask(MachineCreateTask);

function start(callback) {
    var self = this;

    VM.logger = common.makeVmadmLogger(self);
    VM.logname = 'machine_create';
    var creationGuardFilename;

    self.pre_check(function (error) {
        if (error) {
            self.fatal(error.message);
            return;
        }

        async.waterfall([
            function (cb) {
                common.provisionInProgressFile(
                    self.req.params.uuid,
                    function (err, filename) {
                        creationGuardFilename = filename;
                        cb();
                        return;
                    });
            },
            self.ensure_dataset_present.bind(self),
            function (found, cb) {
                // The previous step (ensure..) returns a boolean indicating
                // whether the dataset was found. If that flag is set, we'll
                // run this (fetch) step and skip it if not.
                if (!found) {
                    return self.fetch_dataset(cb);
                } else {
                    return cb();
                }
            },
            self.create_machine.bind(self)
        ],
        function (err0) {
            if (kvm_debugging) {
                kvmdebug.stopKVMDebugging(self.log);
                kvm_debugging = false;
            }

            VM.load(self.req.params.uuid, function (err1, machine) {
                var err = err0 || err1;
                if (err) {
                    var msg = err instanceof Error ? err.message : err;
                    self.log.error('VM.load error: ' + msg);
                    return;
                }

                fs.unlink(creationGuardFilename, function () {
                    if (err) {
                        self.fatal(err.message, null, { vm: self.vm });
                        return;
                    }

                    self.finish({ vm: machine });
                });
            });
        });
    });
}

function pre_check(callback) {
    var self = this;
    var zoneDataset = path.join(self.zpool, self.req.params.uuid);

    async.waterfall([
        function (cb) {
            // fail if zone with uuid exists
            common.zoneList(self.req.params.uuid, function (error, zones) {
                if (zones[self.req.params.uuid]) {
                    cb(new Error(
                        'Machine ' + self.req.params.uuid + ' exists.'));
                    return;
                }
                cb();
            });
        },
        function (cb) {
            // If we don't get an error on this `list` it means the dataset
            // exists.
            zfs.list(
            zoneDataset, { type: 'all' }, function (error, fields, list) {
                if (list && list.length) {
                    cb(new Error('Dataset ' + zoneDataset + ' exists.'));
                    return;
                }
                cb();
            });
        }
    ],
    function (error) {
        if (error) {
            callback(error);
            return;
        }
        callback();
    });
}

function ensure_dataset_present(callback) {
    var self = this;

    var fullDataset;
    var params = self.req.params;

    // TODO Enable provisioner to be able to check a list of image_uuids and
    // fetch any that are not installed
    self.toImport = null;

    if (params.image_uuid) {
        self.toImport = params.image_uuid;
    } else if (self.req.params.disks && self.req.params.disks.length) {
        self.toImport = self.req.params.disks[0].image_uuid;
    }

    fullDataset = this.zpool + '/' + self.toImport;

    self.log.info(
        'Checking whether zone template dataset '
        + fullDataset + ' exists on the system.');

    zfs.list(
        fullDataset,
        { type: 'all' },
        function (error, fields, list) {
            if (!error && list.length) {
                self.log.info('Dataset ' + fullDataset + ' exists.');
                callback(null, true);
                return;
            } else if (error && error.toString().match(/does not exist/)) {
                self.log.info('Dataset template didn\'t appear to exist.');
                callback(null, false);
                return;
            }
        });
}

function fetch_dataset(callback) {
    var self = this;

    var options = {
        uuid: self.toImport,
        zpool: self.zpool,
        log: self.log
    };
    imgadm.importImage(options, function (err) {
        if (err) {
            self.log.error(err);
            callback(err);
            return;
        }
        callback();
    });
}

function normalizeError(error) {
    if (error instanceof String || typeof (error === 'string')) {
        return new Error(error);
    }
    return error;
}

function create_machine(callback) {
    var self = this;
    var req = self.req;

    if (req.params.brand === 'kvm') {
        kvmdebug.startKVMDebugging(self.log, function (cmd, args, output) {
            var cmdline = cmd + ' ' + args.join(' ');
            self.log.debug({cmdline: cmdline, output: output});
        });
        kvm_debugging = true;
    }

    VM.create(req.params, function (error, info) {
        if (error) {
            var msg = error instanceof Error ? error.message : error;
            return callback(new Error('VM.create error: ' + msg));
        }
        return callback();
    });
}

MachineCreateTask.setStart(start);

MachineCreateTask.createSteps({
    pre_check: {
        fn: pre_check,
        progress: 20,
        description: 'Pre-flight sanity check'
    },
    ensure_dataset_present: {
        fn: ensure_dataset_present,
        progress: 30,
        description: 'Checking for zone template dataset'
    },
    fetch_dataset: {
        fn: fetch_dataset,
        progress: 50,
        description: 'Fetching zone template dataset'
    },
    create_machine: {
        fn: create_machine,
        progress: 100,
        description: 'Creating machine'
    }
});
<commit_msg>AGENT-801: don't drop finish event in case of error<commit_after>/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

/*
 * Copyright (c) 2014, Joyent, Inc.
 */

var Task = require('../task_agent/task');
var VM  = require('/usr/vm/node_modules/VM');
var async = require('async');
var common = require('../common');
var fs = require('fs');
var imgadm = require('../imgadm');
var kvmdebug = require('./kvmdebug');
var path = require('path');
var spawn = require('child_process').spawn;
var util = require('util');
var zfs = require('zfs').zfs;

var kvm_debugging = false;

var MachineCreateTask = module.exports = function (req) {
    Task.call(this);
    this.req = req;
    this.zpool = req.params.zfs_storage_pool_name || 'zones';
};

Task.createTask(MachineCreateTask);

function start(callback) {
    var self = this;

    VM.logger = common.makeVmadmLogger(self);
    VM.logname = 'machine_create';
    var creationGuardFilename;

    self.pre_check(function (error) {
        if (error) {
            self.fatal(error.message);
            return;
        }

        async.waterfall([
            function (cb) {
                common.provisionInProgressFile(
                    self.req.params.uuid,
                    function (err, filename) {
                        creationGuardFilename = filename;
                        cb();
                        return;
                    });
            },
            self.ensure_dataset_present.bind(self),
            function (found, cb) {
                // The previous step (ensure..) returns a boolean indicating
                // whether the dataset was found. If that flag is set, we'll
                // run this (fetch) step and skip it if not.
                if (!found) {
                    return self.fetch_dataset(cb);
                } else {
                    return cb();
                }
            },
            self.create_machine.bind(self)
        ],
        function (err0) {
            if (kvm_debugging) {
                kvmdebug.stopKVMDebugging(self.log);
                kvm_debugging = false;
            }

            VM.load(self.req.params.uuid, function (err1, machine) {
                fs.unlink(creationGuardFilename, function (err2) {
                    if (err2) {
                        self.log.error(err2.message);
                        return;
                    }

                    if (err1) {
                        self.log.error(err1.message);
                        return;
                    }

                    if (err0) {
                        if (machine) {
                            self.fatal(err0.message, null, { vm: machine });
                            return;
                        } else {
                            self.fatal(err0.message);
                            return;
                        }
                    } else {
                        self.finish({ vm: machine });
                    }
                });

            });
        });
    });
}

function pre_check(callback) {
    var self = this;
    var zoneDataset = path.join(self.zpool, self.req.params.uuid);

    async.waterfall([
        function (cb) {
            // fail if zone with uuid exists
            common.zoneList(self.req.params.uuid, function (error, zones) {
                if (zones[self.req.params.uuid]) {
                    cb(new Error(
                        'Machine ' + self.req.params.uuid + ' exists.'));
                    return;
                }
                cb();
            });
        },
        function (cb) {
            // If we don't get an error on this `list` it means the dataset
            // exists.
            zfs.list(
            zoneDataset, { type: 'all' }, function (error, fields, list) {
                if (list && list.length) {
                    cb(new Error('Dataset ' + zoneDataset + ' exists.'));
                    return;
                }
                cb();
            });
        }
    ],
    function (error) {
        if (error) {
            callback(error);
            return;
        }
        callback();
    });
}

function ensure_dataset_present(callback) {
    var self = this;

    var fullDataset;
    var params = self.req.params;

    // TODO Enable provisioner to be able to check a list of image_uuids and
    // fetch any that are not installed
    self.toImport = null;

    if (params.image_uuid) {
        self.toImport = params.image_uuid;
    } else if (self.req.params.disks && self.req.params.disks.length) {
        self.toImport = self.req.params.disks[0].image_uuid;
    }

    fullDataset = this.zpool + '/' + self.toImport;

    self.log.info(
        'Checking whether zone template dataset '
        + fullDataset + ' exists on the system.');

    zfs.list(
        fullDataset,
        { type: 'all' },
        function (error, fields, list) {
            if (!error && list.length) {
                self.log.info('Dataset ' + fullDataset + ' exists.');
                callback(null, true);
                return;
            } else if (error && error.toString().match(/does not exist/)) {
                self.log.info('Dataset template didn\'t appear to exist.');
                callback(null, false);
                return;
            }
        });
}

function fetch_dataset(callback) {
    var self = this;

    var options = {
        uuid: self.toImport,
        zpool: self.zpool,
        log: self.log
    };
    imgadm.importImage(options, function (err) {
        if (err) {
            self.log.error(err);
            callback(err);
            return;
        }
        callback();
    });
}

function normalizeError(error) {
    if (error instanceof String || typeof (error === 'string')) {
        return new Error(error);
    }
    return error;
}

function create_machine(callback) {
    var self = this;
    var req = self.req;

    if (req.params.brand === 'kvm') {
        kvmdebug.startKVMDebugging(self.log, function (cmd, args, output) {
            var cmdline = cmd + ' ' + args.join(' ');
            self.log.debug({cmdline: cmdline, output: output});
        });
        kvm_debugging = true;
    }

    VM.create(req.params, function (error, info) {
        if (error) {
            var msg = error instanceof Error ? error.message : error;
            return callback(new Error('VM.create error: ' + msg));
        }
        return callback();
    });
}

MachineCreateTask.setStart(start);

MachineCreateTask.createSteps({
    pre_check: {
        fn: pre_check,
        progress: 20,
        description: 'Pre-flight sanity check'
    },
    ensure_dataset_present: {
        fn: ensure_dataset_present,
        progress: 30,
        description: 'Checking for zone template dataset'
    },
    fetch_dataset: {
        fn: fetch_dataset,
        progress: 50,
        description: 'Fetching zone template dataset'
    },
    create_machine: {
        fn: create_machine,
        progress: 100,
        description: 'Creating machine'
    }
});
<|endoftext|>


<commit_before>zaa.controller("CrudController", function($scope, $http, $sce, $state) {

	$scope.loading = true;

	$scope.parentController = $scope.$parent;

	//$scope.AdminService = AdminService;

	$scope.orderBy = 'id';

	$scope.showCrudList = true;

	$scope.currentMenuItem = null;

	$scope.createErrors = [];

	$scope.updateErrors = [];

	$scope.init = function () {
		$scope.loadList();
		$scope.$watch(function() { return $scope.parentController.currentItem }, function(newValue) {
			$scope.currentMenuItem = newValue;
		});
	}

	$scope.changeOrder = function(field, sort) {
		$scope.orderBy = sort + field;
	}

	$scope.closeDialogs = function() {
		/*
		$scope.toggler.update = false;
		$scope.toggler.strap = false;
		$scope.toggler.create = false;
		//$scope.AdminService.bodyClass = '';
		$scope.search = '';
		*/
	}

	$scope.debug = function() {
		console.log('config', $scope.config);
		console.log('data', $scope.data);
	}

	$scope.getActiveWindow = function (activeWindowId, id, $event) {
		$http.post('admin/ngrest/render', $.param({ itemId : id, activeWindowHash : activeWindowId , ngrestConfigHash : $scope.config.ngrestConfigHash }), {
			headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
		})
		.success(function(data) {
			$scope.openActiveWindow();
			$scope.data.aw.itemId = id;
			$scope.data.aw.configCallbackUrl = $scope.config.activeWindowCallbackUrl;
			$scope.data.aw.configHash = $scope.config.ngrestConfigHash;
			$scope.data.aw.hash = activeWindowId;
			$scope.data.aw.id = activeWindowId; /* @todo: remove! BUT: equal to above, but still need in jquery accessing */
			$scope.data.aw.content = $sce.trustAsHtml(data);
			//dispatchEvent('onCrudActiveWindowLoad');
		})
	}

	$scope.getActiveWindowCallbackUrl = function(callback) {
		return $scope.data.aw.configCallbackUrl + '?activeWindowCallback=' + callback + '&ngrestConfigHash=' + $scope.data.aw.configHash + '&activeWindowHash=' + $scope.data.aw.hash;
	}

	$scope.sendActiveWindowCallback = function(callback, data) {
		$http.post($scope.getActiveWindowCallbackUrl(callback), $.param(data), {
			headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
		}).success(function(response) {
			$scope.activeWindowCallbackResponse = response;
		});
	}

	$scope.toggleUpdate = function (id, $event) {
		/*
		$scope.toggler.update = !$scope.toggler.update;
		$scope.AdminService.bodyClass = 'main-blurred';
		*/
		$scope.data.updateId = id;
		$http.get($scope.config.apiEndpoint + '/'+id+'?' + $scope.config.apiUpdateQueryString)
		.success(function(data) {
			$scope.data.update = data;
            //dispatchEvent('onCrudUpdate');
            $('#updateModal').openModal({
            	dismissible: false
            });

		})
		.error(function(data) {
			alert('ERROR LOADING UPDATE DATA');
		})
	}

	$scope.closeUpdate = function () {
		$('#updateModal').closeModal();
        //$scope.AdminService.bodyClass = '';
    }

	$scope.closeCreate = function() {
		$('#createModal').closeModal();
	}

	$scope.openActiveWindow = function() {
		$('#activeWindowModal').openModal();
	}

	$scope.closeActiveWindow = function() {
		$('#activeWindowModal').closeModal();
	}

	$scope.openCreate = function () {
		$('#createModal').openModal({
			dismissible: false
		});
		/*
		$scope.toggler.create = !$scope.toggler.create;
		if ($scope.toggler.create) {
			$scope.AdminService.bodyClass = 'main-blurred';
		} else {
			$scope.AdminService.bodyClass = '';
		}
		if ($scope.toggler.create) {
			dispatchEvent('onCrudCreate');
		}
		*/
	}

	$scope.submitUpdate = function () {

		$scope.updateErrors = [];

		console.log($scope.data.update);
		console.log(angular.toJson($scope.data.update));
		$http.put($scope.config.apiEndpoint + '/' + $scope.data.updateId, angular.toJson($scope.data.update, true))
		.success(function(data) {
			$('#updateModal').closeModal();
			$scope.loadList();
			Materialize.toast('Der Datensatz wurde erfolgreich aktualsiert.', 3000);
		})
		.error(function(data) {
			$scope.updateErrors = data;
		})
	}

	$scope.submitCreate = function() {

		$scope.createErrors = [];

		$http.post($scope.config.apiEndpoint, angular.toJson($scope.data.create, true))
		.success(function(data) {
			$('#createModal').closeModal();
			$scope.loadList();
			$scope.data.create = {};
			Materialize.toast('Der neue Datensatz wurde erfolgreich erstellt.', 3000);
		})
		.error(function(data) {
			$scope.createErrors = data;
		})
	}

	$scope.loadList = function() {
		$http.get($scope.config.apiEndpoint + '/?' + $scope.config.apiListQueryString)
		.success(function(data) {
			$scope.loading = false;
			$scope.data.list = data;
		})
	}

	/*
	$scope.toggler = {
		create : false,
		update : false
	}
	*/

	$scope.data = {
		create : {},
		update : {},
		aw : {},
		list : {},
		updateId : 0
	};

	$scope.config = {};

});<commit_msg>fixed empty sendActiveWindowCallback data argument.<commit_after>zaa.controller("CrudController", function($scope, $http, $sce, $state) {

	$scope.loading = true;

	$scope.parentController = $scope.$parent;

	//$scope.AdminService = AdminService;

	$scope.orderBy = 'id';

	$scope.showCrudList = true;

	$scope.currentMenuItem = null;

	$scope.createErrors = [];

	$scope.updateErrors = [];

	$scope.init = function () {
		$scope.loadList();
		$scope.$watch(function() { return $scope.parentController.currentItem }, function(newValue) {
			$scope.currentMenuItem = newValue;
		});
	}

	$scope.changeOrder = function(field, sort) {
		$scope.orderBy = sort + field;
	}

	$scope.closeDialogs = function() {
		/*
		$scope.toggler.update = false;
		$scope.toggler.strap = false;
		$scope.toggler.create = false;
		//$scope.AdminService.bodyClass = '';
		$scope.search = '';
		*/
	}

	$scope.debug = function() {
		console.log('config', $scope.config);
		console.log('data', $scope.data);
	}

	$scope.getActiveWindow = function (activeWindowId, id, $event) {
		$http.post('admin/ngrest/render', $.param({ itemId : id, activeWindowHash : activeWindowId , ngrestConfigHash : $scope.config.ngrestConfigHash }), {
			headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
		})
		.success(function(data) {
			$scope.openActiveWindow();
			$scope.data.aw.itemId = id;
			$scope.data.aw.configCallbackUrl = $scope.config.activeWindowCallbackUrl;
			$scope.data.aw.configHash = $scope.config.ngrestConfigHash;
			$scope.data.aw.hash = activeWindowId;
			$scope.data.aw.id = activeWindowId; /* @todo: remove! BUT: equal to above, but still need in jquery accessing */
			$scope.data.aw.content = $sce.trustAsHtml(data);
			//dispatchEvent('onCrudActiveWindowLoad');
		})
	}

	$scope.getActiveWindowCallbackUrl = function(callback) {
		return $scope.data.aw.configCallbackUrl + '?activeWindowCallback=' + callback + '&ngrestConfigHash=' + $scope.data.aw.configHash + '&activeWindowHash=' + $scope.data.aw.hash;
	}

	$scope.sendActiveWindowCallback = function(callback, data) {
		var data = data || {};
		$http.post($scope.getActiveWindowCallbackUrl(callback), $.param(data), {
			headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
		}).success(function(response) {
			$scope.activeWindowCallbackResponse = response;
		});
	}

	$scope.toggleUpdate = function (id, $event) {
		/*
		$scope.toggler.update = !$scope.toggler.update;
		$scope.AdminService.bodyClass = 'main-blurred';
		*/
		$scope.data.updateId = id;
		$http.get($scope.config.apiEndpoint + '/'+id+'?' + $scope.config.apiUpdateQueryString)
		.success(function(data) {
			$scope.data.update = data;
            //dispatchEvent('onCrudUpdate');
            $('#updateModal').openModal({
            	dismissible: false
            });

		})
		.error(function(data) {
			alert('ERROR LOADING UPDATE DATA');
		})
	}

	$scope.closeUpdate = function () {
		$('#updateModal').closeModal();
        //$scope.AdminService.bodyClass = '';
    }

	$scope.closeCreate = function() {
		$('#createModal').closeModal();
	}

	$scope.openActiveWindow = function() {
		$('#activeWindowModal').openModal();
	}

	$scope.closeActiveWindow = function() {
		$('#activeWindowModal').closeModal();
	}

	$scope.openCreate = function () {
		$('#createModal').openModal({
			dismissible: false
		});
		/*
		$scope.toggler.create = !$scope.toggler.create;
		if ($scope.toggler.create) {
			$scope.AdminService.bodyClass = 'main-blurred';
		} else {
			$scope.AdminService.bodyClass = '';
		}
		if ($scope.toggler.create) {
			dispatchEvent('onCrudCreate');
		}
		*/
	}

	$scope.submitUpdate = function () {

		$scope.updateErrors = [];

		console.log($scope.data.update);
		console.log(angular.toJson($scope.data.update));
		$http.put($scope.config.apiEndpoint + '/' + $scope.data.updateId, angular.toJson($scope.data.update, true))
		.success(function(data) {
			$('#updateModal').closeModal();
			$scope.loadList();
			Materialize.toast('Der Datensatz wurde erfolgreich aktualsiert.', 3000);
		})
		.error(function(data) {
			$scope.updateErrors = data;
		})
	}

	$scope.submitCreate = function() {

		$scope.createErrors = [];

		$http.post($scope.config.apiEndpoint, angular.toJson($scope.data.create, true))
		.success(function(data) {
			$('#createModal').closeModal();
			$scope.loadList();
			$scope.data.create = {};
			Materialize.toast('Der neue Datensatz wurde erfolgreich erstellt.', 3000);
		})
		.error(function(data) {
			$scope.createErrors = data;
		})
	}

	$scope.loadList = function() {
		$http.get($scope.config.apiEndpoint + '/?' + $scope.config.apiListQueryString)
		.success(function(data) {
			$scope.loading = false;
			$scope.data.list = data;
		})
	}

	/*
	$scope.toggler = {
		create : false,
		update : false
	}
	*/

	$scope.data = {
		create : {},
		update : {},
		aw : {},
		list : {},
		updateId : 0
	};

	$scope.config = {};

});<|endoftext|>


<commit_before>import {
  COLOR,
  FONT_SIZE,
  FONT_WEIGHT,
  FONT_FAMILY,
  LINE_HEIGHT
} from "../../consts/types";

export default {
  "label.fontSize": {
    type: FONT_SIZE,
    value: {
      ref: "density.fontSizes.small"
    }
  },
  "label.fontWeight": {
    type: FONT_WEIGHT,
    value: {
      ref: "basics.fontWeights.regular"
    }
  },
  "label.fontFamily": {
    type: FONT_FAMILY,
    value: {
      ref: "basics.fontFamilies.main"
    }
  },
  "label.fontColor": {
    type: COLOR,
    value: {
      ref: "basics.colors.charcoal900"
    },
    transform: {
      alpha: 0.9
    }
  },
  "label.lineHeight": {
    type: LINE_HEIGHT,
    value: {
      ref: "basics.lineHeights.medium"
    }
  },

  // Hover
  "label.hover.fontColor": {
    type: COLOR,
    value: {
      ref: "basics.colors.charcoal900"
    },
    transform: {
      alpha: 0.9
    }
  }
};
<commit_msg>fix: increase font size for label, matching body<commit_after>import {
  COLOR,
  FONT_SIZE,
  FONT_WEIGHT,
  FONT_FAMILY,
  LINE_HEIGHT
} from "../../consts/types";

export default {
  "label.fontSize": {
    type: FONT_SIZE,
    value: {
      ref: "density.fontSizes.medium"
    }
  },
  "label.fontWeight": {
    type: FONT_WEIGHT,
    value: {
      ref: "basics.fontWeights.regular"
    }
  },
  "label.fontFamily": {
    type: FONT_FAMILY,
    value: {
      ref: "basics.fontFamilies.main"
    }
  },
  "label.fontColor": {
    type: COLOR,
    value: {
      ref: "basics.colors.charcoal900"
    },
    transform: {
      alpha: 0.9
    }
  },
  "label.lineHeight": {
    type: LINE_HEIGHT,
    value: {
      ref: "basics.lineHeights.medium"
    }
  },

  // Hover
  "label.hover.fontColor": {
    type: COLOR,
    value: {
      ref: "basics.colors.charcoal900"
    },
    transform: {
      alpha: 0.9
    }
  }
};
<|endoftext|>


<commit_before>window.onload = function() {
    // the items in this array are the whitelisted 'QR codes'
    var validationArr = [ "appidaapi","appidaapi2"];
    var imageHolder;

    var width         = 320;    // We will scale the photo width to this
    var height        = 0;     // This will be computed based on the input stream
    var streaming     = false;
    var scanning      = false;
    var playing       = false;
    var video         = document.getElementById('video');
    var canvas        = document.getElementById('canvas');
    var photo         = document.getElementById('photo');
    var upload        = document.getElementById('upload');
    var preview       = document.getElementById('preview');
    var qr            = new QrCode();
    const constraints = {advanced: [{facingMode: "environment"}]}
    // this function takes a key and checks if it is whitelisted
    function validationKey(key){
        var validation = false;
        for(var i = 0; i < validationArr.length;i++){
            if(validationArr[i] == key){
                validation = true;
            }
        }
        return validation
    }

    // set a key in storage as owned
    function setStorageItem(key){
        if (typeof(Storage) !== "undefined") {
            if(validationKey(key)){
                // good to go
                localStorage.setItem(key,1)    // define 1 as 'true' / 'present'
                if('vibrate' in navigator){
                    navigator.vibrate([200,100,50])
                }else{
                    console.log("Should be vibrating.. but your device sucks")
                }
            }else{
                console.log("this item does not pass validation")
            }
        } else {
            alert("Browser does not support storage! git gud browser plz")
        }

    }
    // setStorageItem("appidaapi4")

    navigator.mediaDevices.getUserMedia({ video: constraints, audio: false }).then(function(stream) {
        video.srcObject = stream;
        video.play();
    }).catch(function(err) {
        console.log("An error occured initialising video element! \n error code: " + err);
    });

    qr.callback = function(err, result) {
      var span = document.querySelector('span') || document.createElement('span');
      if(result){
        var resultZ = result.result;
        setStorageItem(resultZ);
        console.error("Found QR: " +result.result);
      }
      else{
        span.textContent = 'Error! See error message in console!';
        console.error(err);
      }
      preview.appendChild(span);
    }
    /*

    */
    video.addEventListener('canplay', function(ev){
        if (!streaming) {
          height = video.videoHeight / (video.videoWidth/width);
          video.setAttribute('width', width);
          video.setAttribute('height', height);
          canvas.setAttribute('width', width);
          canvas.setAttribute('height', height);
          streaming = true;
        }
      }, false);

    upload.addEventListener('change', function() {
        for (var i = 0; i < this.files.length; i++) {
          var file = this.files[i];
          var imageType = /^image\//;
          if (!imageType.test(file.type)) {
            throw new Error('File type not valid');
          }
          // Read file
          var reader = new FileReader();
          reader.addEventListener('load', function() {
            // Show as preview image
            var img = document.querySelector('img') || document.createElement('img');
            img.src = this.result;
            preview.appendChild(img);
            // Analyse code
            qr.decode(this.result);
          }.bind(reader), false);
          reader.readAsDataURL(file);
        }
      }, false);

    /////////////////
    ////QR /////////////

    function handleFiles(f){
        var o=[];
        for(var i =0;i<f.length;i++){
          var reader = new FileReader();
          reader.onload = (function(theFile) {
            return function(e) {
              qrcode.decode(e.target.result);
            };
          })(f[i]);
          // Read in the image file as a data URL.
          reader.readAsDataURL(f[i]);
        }
    }

    function startscan(){
        scanning = true;
        video.play();
        if(!playing){
            var takeScreenCap = function(){
                if(scanning){
                    var context = canvas.getContext('2d');
                    if (width != undefined && height != undefined) {
                      canvas.width = width;
                      canvas.height = height;
                      context.drawImage(video, 0, 0, width, height);
                      var data = canvas.toDataURL('image/png');
                      qr.decode(data);
                    }
                }
            }
            setInterval(takeScreenCap , 1000)
        }
    }

    /*
        Modal controls
    */
    // Get the modal
    var modal = document.getElementById('myModal');

    // Get the button that opens the modal
    var btn = document.getElementById("myBtn");

    // Get the <span> element that closes the modal
    var span = document.getElementsByClassName("close")[0];

    // When the user clicks the button, open the modal
    btn.onclick = function() {
        startscan();
        playing = true;
        modal.style.display = "block";
    }

    // When the user clicks on <span> (x), close the modal
    span.onclick = function() {
        scanning = false;
        video.pause();
        modal.style.display = "none";
    }

    // When the user clicks anywhere outside of the modal, close it
    window.onclick = function(event) {
        if (event.target == modal) {
            scanning = false;
            video.pause();
            modal.style.display = "none";
        }
    }

};

<commit_msg>set span info<commit_after>window.onload = function() {
    // the items in this array are the whitelisted 'QR codes'
    var validationArr = [ "appidaapi","appidaapi2"];
    var imageHolder;

    var width         = 320;    // We will scale the photo width to this
    var height        = 0;     // This will be computed based on the input stream
    var streaming     = false;
    var scanning      = false;
    var playing       = false;
    var video         = document.getElementById('video');
    var canvas        = document.getElementById('canvas');
    var photo         = document.getElementById('photo');
    var upload        = document.getElementById('upload');
    var preview       = document.getElementById('preview');
    var qr            = new QrCode();
    const constraints = {advanced: [{facingMode: "environment"}]}
    // this function takes a key and checks if it is whitelisted
    function validationKey(key){
        var validation = false;
        for(var i = 0; i < validationArr.length;i++){
            if(validationArr[i] == key){
                validation = true;
            }
        }
        return validation
    }

    // set a key in storage as owned
    function setStorageItem(key){
        if (typeof(Storage) !== "undefined") {
            if(validationKey(key)){
                // good to go
                localStorage.setItem(key,1)    // define 1 as 'true' / 'present'
                if('vibrate' in navigator){
                    navigator.vibrate([200,100,50])
                }else{
                    console.log("Should be vibrating.. but your device sucks")
                }
            }else{
                console.log("this item does not pass validation")
            }
        } else {
            alert("Browser does not support storage! git gud browser plz")
        }

    }
    // setStorageItem("appidaapi4")

    navigator.mediaDevices.getUserMedia({ video: constraints, audio: false }).then(function(stream) {
        video.srcObject = stream;
        video.play();
    }).catch(function(err) {
        console.log("An error occured initialising video element! \n error code: " + err);
    });

    qr.callback = function(err, result) {
      var span = document.querySelector('span') || document.createElement('span');
      if(result){
        var resultZ = result.result;
        setStorageItem(resultZ);
        console.error("Found QR: " +result.result);
        span.textContent = result.result;
      }
      else{
        span.textContent = 'Error! See error message in console!';
        console.error(err);
      }
      preview.appendChild(span);
    }
    /*

    */
    video.addEventListener('canplay', function(ev){
        if (!streaming) {
          height = video.videoHeight / (video.videoWidth/width);
          video.setAttribute('width', width);
          video.setAttribute('height', height);
          canvas.setAttribute('width', width);
          canvas.setAttribute('height', height);
          streaming = true;
        }
      }, false);

    upload.addEventListener('change', function() {
        for (var i = 0; i < this.files.length; i++) {
          var file = this.files[i];
          var imageType = /^image\//;
          if (!imageType.test(file.type)) {
            throw new Error('File type not valid');
          }
          // Read file
          var reader = new FileReader();
          reader.addEventListener('load', function() {
            // Show as preview image
            var img = document.querySelector('img') || document.createElement('img');
            img.src = this.result;
            preview.appendChild(img);
            // Analyse code
            qr.decode(this.result);
          }.bind(reader), false);
          reader.readAsDataURL(file);
        }
      }, false);

    /////////////////
    ////QR /////////////

    function handleFiles(f){
        var o=[];
        for(var i =0;i<f.length;i++){
          var reader = new FileReader();
          reader.onload = (function(theFile) {
            return function(e) {
              qrcode.decode(e.target.result);
            };
          })(f[i]);
          // Read in the image file as a data URL.
          reader.readAsDataURL(f[i]);
        }
    }

    function startscan(){
        scanning = true;
        video.play();
        if(!playing){
            var takeScreenCap = function(){
                if(scanning){
                    var context = canvas.getContext('2d');
                    if (width != undefined && height != undefined) {
                      canvas.width = width;
                      canvas.height = height;
                      context.drawImage(video, 0, 0, width, height);
                      var data = canvas.toDataURL('image/png');
                      qr.decode(data);
                    }
                }
            }
            setInterval(takeScreenCap , 1000)
        }
    }

    /*
        Modal controls
    */
    // Get the modal
    var modal = document.getElementById('myModal');

    // Get the button that opens the modal
    var btn = document.getElementById("myBtn");

    // Get the <span> element that closes the modal
    var span = document.getElementsByClassName("close")[0];

    // When the user clicks the button, open the modal
    btn.onclick = function() {
        startscan();
        playing = true;
        modal.style.display = "block";
    }

    // When the user clicks on <span> (x), close the modal
    span.onclick = function() {
        scanning = false;
        video.pause();
        modal.style.display = "none";
    }

    // When the user clicks anywhere outside of the modal, close it
    window.onclick = function(event) {
        if (event.target == modal) {
            scanning = false;
            video.pause();
            modal.style.display = "none";
        }
    }

};

<|endoftext|>


<commit_before>'use strict';

let Application = rootRequire('app/users/application/model');
let User = rootRequire('app/users/model');
let log = rootRequire('app/helpers/logger');

module.exports = {

  /**
  * Build a line graph of registrations over time
  * GET /stats/registrations
  * Auth -> admin, staff
  */
  registrations: (req, res) => {
    User
      .find()
      .select('application')
      .populate({
        path: 'application',
        match: req.query,
        select: 'created'
      })
      .exec((err, users) => {
        if (err) return res.internalError();
        let apps = users.filter((user) => {
          return user.application;
        }).map((user) => {
          return user.application;
        });
        let months = [
          {name: 'January', count: 0},
          {name: 'February', count: 0},
          {name: 'March', count: 0},
          {name: 'April', count: 0},
          {name: 'May', count: 0},
          {name: 'June', count: 0},
          {name: 'July', count: 0},
          {name: 'August', count: 0},
          {name: 'September', count: 0},
          {name: 'October', count: 0},
          {name: 'November', count: 0},
          {name: 'December', count: 0}
        ];
        for (let i = 0; i < apps.length; ++i) {
          let index = apps[i].created.getMonth(); // int value of the month, ex 7
          months[index].count++;
        }
        return res.status(200).json({
          months: months.filter((month) => {
            return month.count;
          })
        });
      });
  },

  /**
  * Get the distribution of t-shirt sizes for all applications
  * GET /stats/shirts
  * Auth -> admin, staff
  */
  shirts: (req, res) => {
    User
      .find()
      .select('application')
      .populate({
        path: 'application',
        match: req.query,
        select: 'shirt'
      })
      .exec((err, users) => {
        if (err) return res.internalError();
        let apps = users.filter((user) => {
          return user.application;
        }).map((user) => {
          return user.application;
        });
        let small = 0;
        let medium = 0;
        let large = 0;
        let xlarge = 0;
        for (let i = 0; i < apps.length; ++i) {
          switch (apps[i].shirt) {
            case 'S':
              small++;
              break;
            case 'M':
              medium++;
              break;
            case 'L':
              large++;
              break;
            case 'XL':
              xlarge++;
              break;
          }
        }
        return res.status(200).json({
          small: small,
          medium: medium,
          large: large,
          xlarge: xlarge
        });
      });
  },

  /**
  * Get a breakdown of dietary restrictions
  * GET /stats/dietary
  * Auth -> admin, staff
  */
  dietary: (req, res) => {
    User
      .find()
      .select('application')
      .populate({
        path: 'application',
        match: req.query,
        select: 'dietary'
      })
      .exec(function (err, users) {
        if (err) return res.internalError();
        let apps = users.filter((user) => {
          return user.application;
        }).map((user) => {
          return user.application;
        });
        let restrictions = {};
        for (let i = 0; i < apps.length; ++i) {
          if (apps[i].dietary) {
            for (let j = 0; j < apps[i].dietary.length; ++j) {
              let name = apps[i].dietary[j];
              if (name in restrictions) {
                restrictions[name]++;
              } else {
                restrictions[name] = 1;
              }
            }
          }
        }
        let dietary = [];
        for (let key in restrictions) {
          if (restrictions.hasOwnProperty(key)) {
            dietary.push({
              name: key,
              count: restrictions[key]
            });
          }
        }
        return res.status(200).json({restrictions: dietary});
      });
  },

  /**
  * Gender comparison
  * GET /stats/gender
  * Auth -> admin, staff
  */
  gender: (req, res) => {
    User
      .find()
      .select('application')
      .populate({
        path: 'application',
        match: req.query,
        select: 'gender'
      })
      .exec((err, users) => {
        if (err) return res.internalError();
        let apps = users.filter((user) => {
          return user.application;
        }).map((user) => {
          return user.application;
        });
        let male = 0;
        let female = 0;
        let other = 0;
        for (let i = 0; i < apps.length; ++i) {
          if (apps[i].gender) {
            if (apps[i].gender.toLowerCase() == 'male') {
              male++;
            } else if (apps[i].gender.toLowerCase() == 'female') {
              female++;
            } else {
              other++;
            }
          }
        }
        return res.status(200).json({
          male: male,
          female: female,
          other: other
        });
      });
  },

  /**
  * Get a distribution of schools
  * GET /stats/schools
  * Auth -> admin, staff
  */
  schools: (req, res) => {
    User
      .find()
      .select('application')
      .populate({
        path: 'application',
        match: req.query,
        select: 'school'
      })
      .exec((err, users) => {
        if (err) return res.internalError();
        let apps = users.filter((user) => {
          return user.application;
        }).map((user) => {
          return user.application;
        });
        let s = {};
        for (let i = 0; i < apps.length; ++i) {
          if (apps[i].school) {
            let school = apps[i].school;
            s[school] = (s[school] || 0) + 1;
          }
        }
        let schools = [];
        for (let key in s) {
          schools.push({
            name: key,
            count: s[key]
          });
        }
        schools = schools.slice(0, 10);
        return res.status(200).json({schools: schools});
      });
  },

  /**
  * Query for numbers of applications
  * GET /stats/count?param=value
  * Auth -> admin, staff
  */
  count: (req, res) => {
    Application
      .count(req.query)
      .exec((err, count) => {
        log.info('error:');
        log.info(err);
        log.info('count:');
        log.info(count);
        if (err) return res.internalError();
        return res.status(200).json({count});
      });
  }

};
<commit_msg>Clean up stats controller<commit_after>'use strict';

let Application = rootRequire('app/users/application/model');
let User = rootRequire('app/users/model');
let log = rootRequire('app/helpers/logger');

module.exports = {

  /**
  * Build a line graph of registrations over time
  * GET /stats/registrations
  * Auth -> admin, staff
  */
  registrations: (req, res) => {
    User
      .find()
      .select('application')
      .populate({
        path: 'application',
        match: req.query,
        select: 'created'
      })
      .exec((err, users) => {
        if (err) return res.internalError();
        let apps = users.filter((user) => {
          return user.application;
        }).map((user) => {
          return user.application;
        });
        let months = [
          {name: 'January', count: 0},
          {name: 'February', count: 0},
          {name: 'March', count: 0},
          {name: 'April', count: 0},
          {name: 'May', count: 0},
          {name: 'June', count: 0},
          {name: 'July', count: 0},
          {name: 'August', count: 0},
          {name: 'September', count: 0},
          {name: 'October', count: 0},
          {name: 'November', count: 0},
          {name: 'December', count: 0}
        ];
        for (let i = 0; i < apps.length; ++i) {
          let index = apps[i].created.getMonth(); // int value of the month, ex 7
          months[index].count++;
        }
        return res.status(200).json({
          months: months.filter((month) => {
            return month.count;
          })
        });
      });
  },

  /**
  * Get the distribution of t-shirt sizes for all applications
  * GET /stats/shirts
  * Auth -> admin, staff
  */
  shirts: (req, res) => {
    User
      .find()
      .select('application')
      .populate({
        path: 'application',
        match: req.query,
        select: 'shirt'
      })
      .exec((err, users) => {
        if (err) return res.internalError();
        let apps = users.filter((user) => {
          return user.application;
        }).map((user) => {
          return user.application;
        });
        let small = 0;
        let medium = 0;
        let large = 0;
        let xlarge = 0;
        for (let i = 0; i < apps.length; ++i) {
          switch (apps[i].shirt) {
            case 'S':
              small++;
              break;
            case 'M':
              medium++;
              break;
            case 'L':
              large++;
              break;
            case 'XL':
              xlarge++;
              break;
          }
        }
        return res.status(200).json({
          small: small,
          medium: medium,
          large: large,
          xlarge: xlarge
        });
      });
  },

  /**
  * Get a breakdown of dietary restrictions
  * GET /stats/dietary
  * Auth -> admin, staff
  */
  dietary: (req, res) => {
    User
      .find()
      .select('application')
      .populate({
        path: 'application',
        match: req.query,
        select: 'dietary'
      })
      .exec(function (err, users) {
        if (err) return res.internalError();
        let apps = users.filter((user) => {
          return user.application;
        }).map((user) => {
          return user.application;
        });
        let restrictions = {};
        for (let i = 0; i < apps.length; ++i) {
          if (apps[i].dietary) {
            for (let j = 0; j < apps[i].dietary.length; ++j) {
              let name = apps[i].dietary[j];
              if (name in restrictions) {
                restrictions[name]++;
              } else {
                restrictions[name] = 1;
              }
            }
          }
        }
        let dietary = [];
        for (let key in restrictions) {
          if (restrictions.hasOwnProperty(key)) {
            dietary.push({
              name: key,
              count: restrictions[key]
            });
          }
        }
        return res.status(200).json({restrictions: dietary});
      });
  },

  /**
  * Gender comparison
  * GET /stats/gender
  * Auth -> admin, staff
  */
  gender: (req, res) => {
    User
      .find()
      .select('application')
      .populate({
        path: 'application',
        match: req.query,
        select: 'gender'
      })
      .exec((err, users) => {
        if (err) return res.internalError();
        let apps = users.filter((user) => {
          return user.application;
        }).map((user) => {
          return user.application;
        });
        let male = 0;
        let female = 0;
        let other = 0;
        for (let i = 0; i < apps.length; ++i) {
          if (apps[i].gender) {
            if (apps[i].gender.toLowerCase() == 'male') {
              male++;
            } else if (apps[i].gender.toLowerCase() == 'female') {
              female++;
            } else {
              other++;
            }
          }
        }
        return res.status(200).json({
          male: male,
          female: female,
          other: other
        });
      });
  },

  /**
  * Get a distribution of schools
  * GET /stats/schools
  * Auth -> admin, staff
  */
  schools: (req, res) => {
    User
      .find()
      .select('application')
      .populate({
        path: 'application',
        match: req.query,
        select: 'school'
      })
      .exec((err, users) => {
        if (err) return res.internalError();
        let apps = users.filter((user) => {
          return user.application;
        }).map((user) => {
          return user.application;
        });
        let s = {};
        for (let i = 0; i < apps.length; ++i) {
          if (apps[i].school) {
            let school = apps[i].school;
            s[school] = (s[school] || 0) + 1;
          }
        }
        let schools = [];
        for (let key in s) {
          schools.push({
            name: key,
            count: s[key]
          });
        }
        schools = schools.slice(0, 10);
        return res.status(200).json({schools: schools});
      });
  },

  /**
  * Query for numbers of applications
  * GET /stats/count?param=value
  * Auth -> admin, staff
  */
  count: (req, res) => {
    Application
      .count(req.query)
      .exec((err, count) => {
        if (err) return res.internalError();
        return res.status(200).json({count});
      });
  }

};
<|endoftext|>


<commit_before>import { defaults } from 'lodash';

const initialState = {
    userName: '',
    userToken: '',
    isUserLoggedIn: false,
    rooms: []
};

function appReducer(state = initialState, action) {
    switch (action.type) {
    case 'ADD_KEY':
        return {
            [action.data]: '',
            ...state
        };
    case 'SET_DEFAULT_VALUE':
        return defaults(action.data, state);
    default:
        return state;
    }
}

export default appReducer;
<commit_msg>added some app pertinent states to the reducer<commit_after>import { defaults } from 'lodash';

const initialState = {
    userName: '',
    userToken: '',
    loggingIn: false,
    showSnackbar: false,
    snackbarMessage: '',
    rooms: []
};

function appReducer(state = initialState, { type, data }) {
    switch (type) {
    case 'LOGIN_REQUESTED':
        return defaults({ loggingIn: true }, state);
    case 'LOGIN_SUCCESSFUL':
        return defaults({ loggingIn: false, userToken: data }, state);
    case 'LOGIN_FAILED':
        return defaults({ loggingIn: false, showSnackbar: true, snackbarMessage: data }, state);
    case 'TEST_ACTION':
        return defaults({ testVal: data }, state);
    default:
        return state;
    }
}

export default appReducer;
<|endoftext|>