<commit_before>/* FTUI Plugin
 * Copyright (c) 2015-2016 Mario Stephan <mstephan@shared-files.de>
 * originally created by Thomas Nesges
 * Under MIT License (http://www.opensource.org/licenses/mit-license.php)
 */

/* global ftui:true, Modul_widget:true */

"use strict";

var Modul_clock = function () {

    function init_attr(elem) {
        elem.initData('format', 'H:i:s');
        elem.initData('interval', 1000);
        elem.initData('shortday-length', 3);
        elem.initData('days', ["Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag", "Sonntag"]);
        elem.initData('shortmonth-length', 3);
        elem.initData('months', ["Januar", "Februar", "M‰rz", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"]);

        if (!$.isArray(elem.data('days'))) {
            if (elem.data('days').match(/englisc?h/)) {
                elem.data('days', ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]);
            } else {
                console.log(me.widgetname, 'init_attr', 'ERROR: data-days must be an array');
            }
        }

        if (!$.isArray(elem.data('months'))) {
            if (elem.data('months').match(/englisc?h/)) {
                elem.data('months', ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]);
            } else {
                console.log(me.widgetname, 'init_attr', 'ERROR: data-months must be an array');
            }
        }

    }

    function init_datearray(elem) {
        var d = [];
        var now = new Date();
        // Y: Jahreszahl, vierstellig
        // y: Jahreszahl, zweistellig
        // m: Monatszahl, mit f¸hrender Null
        // n: Monatszahl, ohne f¸hrende Null
        // d: Tag des Monats, mit f¸hrender Null
        // j: Tag des Monats, ohne f¸hrende Null
        // H: Stunde des Tages, mit f¸hrender Null
        // G: Stunde im 24-Stunden-Format, ohne f¸hrender Null
        // i: Minute der Stunde, mit f¸hrender Null
        // s: Sekunde der Minute, mit f¸hrender Null
        // u: Millisekunden mit f¸hrender Null
        // O: Zeitunterschied zur Greenwich time (GMT) in Stunden
        // U: Sekunden seit Beginn der UNIX-Epoche (January 1 1970 00:00:00 GMT)
        // w: Wochentagszahl (Sonntag = 0, Samstag = 6)
        // N: Wochentagszahl nach ISO-8601 (Montag = 1, Sonntag = 7)
        // l: Wochentag
        // D: Wochentag gek?rzt
        // S: Anhang der englischen Aufz?hlung f?r einen Monatstag, zwei Zeichen
        // F: Monat als ganzes Wort, wie January oder March
        // M: Monatsname gek?rzt
        // g: Stunde im 12-Stunden-Format, ohne f?hrende Nullen
        // h: Stunde im 12-Stunden-Format, mit f?hrenden Nullen
        // a: am/pm
        // A: AM/PM

        // TODO:
        // z: Der Tag des Jahres
        // W: ISO-8601 Wochennummer des Jahres

        d['Y'] = now.getFullYear();
        d['n'] = now.getMonth() + 1;
        d['j'] = now.getDate();
        d['G'] = now.getHours();
        d['i'] = now.getMinutes();
        d['s'] = now.getSeconds();
        d['w'] = now.getDay();
        d['u'] = now.getMilliseconds();
        d['O'] = now.getTimezoneOffset() / 60;
        d['U'] = Math.floor(now.getTime() / 1000);

        d['y'] = d['Y'] - 2000;
        d['d'] = d['j'] < 10 ? '0' + d['j'] : d['j'];
        d['m'] = d['n'] < 10 ? '0' + d['n'] : d['n'];
        d['H'] = d['G'] < 10 ? '0' + d['G'] : d['G'];
        d['i'] = d['i'] < 10 ? '0' + d['i'] : d['i'];
        d['s'] = d['s'] < 10 ? '0' + d['s'] : d['s'];
        d['u'] = d['u'] < 10 ? '000' + d['u'] : d['u'] < 100 ? '00' + d['u'] : d['u'] < 1000 ? '0' + d['u'] : d['u'];
        d['N'] = d['w'] === 0 ? 7 : d['w'];
        d['l'] = elem.data('days')[(Number(d['N']) - 1)];
        d['D'] = d['l'].substr(0, elem.data('shortday-length'));
        d['S'] = String(d['j']).match(/[23]?1$/) ? 'st' : String(d['j']).match(/[23]?2$/) ? 'nd' : String(d['j']).match(/[23]?3$/) ? 'rd' : 'th';
        d['F'] = elem.data('months')[(Number(d['n']) - 1)];
        d['M'] = d['F'].substr(0, elem.data('shortmonth-length'));
        d['g'] = d['G'] <= 12 ? d['G'] : d['G'] - 12;
        d['h'] = d['g'] < 10 ? '0' + d['g'] : d['g'];
        d['a'] = d['G'] <= 12 ? 'am' : 'pm';
        d['A'] = d['a'].toUpperCase();
        // 'W' by mc-hollin http://forum.fhem.de/index.php/topic,34233.msg304630.html#msg304630
        var onejan = new Date(now.getFullYear(), 0, 1);
        var kw = Math.ceil((((now - onejan) / 86400000) + onejan.getDay() + 1) / 7);
        d['W'] = kw < 10 ? '0' + kw : kw;

        return d;
    }

    function init_datetext(format, d) {
        // split formatstring into it's letters and replace one after the other
        var datearr = format.split('');
        for (var l = 0; l < datearr.length; l++) {
            for (var key in d) {
                if (datearr[l] == key) {
                    datearr[l] = d[key];
                    // stop replacing after a match
                    break;
                }
            }
        }
        return datearr.join('');
    }

    function init_ui(elem) {

        var tid = setInterval(function () {
            if (elem && elem.data('days')) {

                var d = init_datearray(elem);
                var text = init_datetext(elem.data('format'), d);
                elem.text(text);

            } else {
                clearInterval(tid);
            }
        }, elem.data('interval'));
    }

    function update(dev, par) {}

    // public
    // inherit members from base class
    var me = $.extend(new Modul_widget(), {
        //override members
        widgetname: 'clock',
        init_ui: init_ui,
        init_attr: init_attr,
        update: update,
    });

    return me;
};<commit_msg>Fixed typo in clock widget<commit_after>/* FTUI Plugin
 * Copyright (c) 2015-2016 Mario Stephan <mstephan@shared-files.de>
 * originally created by Thomas Nesges
 * Under MIT License (http://www.opensource.org/licenses/mit-license.php)
 */

/* global ftui:true, Modul_widget:true */

"use strict";

var Modul_clock = function () {

    function init_attr(elem) {
        elem.initData('format', 'H:i:s');
        elem.initData('interval', 1000);
        elem.initData('shortday-length', 3);
        elem.initData('days', ["Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag", "Sonntag"]);
        elem.initData('shortmonth-length', 3);
        elem.initData('months', ["Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"]);

        if (!$.isArray(elem.data('days'))) {
            if (elem.data('days').match(/englisc?h/)) {
                elem.data('days', ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]);
            } else {
                console.log(me.widgetname, 'init_attr', 'ERROR: data-days must be an array');
            }
        }

        if (!$.isArray(elem.data('months'))) {
            if (elem.data('months').match(/englisc?h/)) {
                elem.data('months', ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]);
            } else {
                console.log(me.widgetname, 'init_attr', 'ERROR: data-months must be an array');
            }
        }

    }

    function init_datearray(elem) {
        var d = [];
        var now = new Date();
        // Y: Jahreszahl, vierstellig
        // y: Jahreszahl, zweistellig
        // m: Monatszahl, mit f¸hrender Null
        // n: Monatszahl, ohne f¸hrende Null
        // d: Tag des Monats, mit f¸hrender Null
        // j: Tag des Monats, ohne f¸hrende Null
        // H: Stunde des Tages, mit f¸hrender Null
        // G: Stunde im 24-Stunden-Format, ohne f¸hrender Null
        // i: Minute der Stunde, mit f¸hrender Null
        // s: Sekunde der Minute, mit f¸hrender Null
        // u: Millisekunden mit f¸hrender Null
        // O: Zeitunterschied zur Greenwich time (GMT) in Stunden
        // U: Sekunden seit Beginn der UNIX-Epoche (January 1 1970 00:00:00 GMT)
        // w: Wochentagszahl (Sonntag = 0, Samstag = 6)
        // N: Wochentagszahl nach ISO-8601 (Montag = 1, Sonntag = 7)
        // l: Wochentag
        // D: Wochentag gek?rzt
        // S: Anhang der englischen Aufz?hlung f?r einen Monatstag, zwei Zeichen
        // F: Monat als ganzes Wort, wie January oder March
        // M: Monatsname gek?rzt
        // g: Stunde im 12-Stunden-Format, ohne f?hrende Nullen
        // h: Stunde im 12-Stunden-Format, mit f?hrenden Nullen
        // a: am/pm
        // A: AM/PM

        // TODO:
        // z: Der Tag des Jahres
        // W: ISO-8601 Wochennummer des Jahres

        d['Y'] = now.getFullYear();
        d['n'] = now.getMonth() + 1;
        d['j'] = now.getDate();
        d['G'] = now.getHours();
        d['i'] = now.getMinutes();
        d['s'] = now.getSeconds();
        d['w'] = now.getDay();
        d['u'] = now.getMilliseconds();
        d['O'] = now.getTimezoneOffset() / 60;
        d['U'] = Math.floor(now.getTime() / 1000);

        d['y'] = d['Y'] - 2000;
        d['d'] = d['j'] < 10 ? '0' + d['j'] : d['j'];
        d['m'] = d['n'] < 10 ? '0' + d['n'] : d['n'];
        d['H'] = d['G'] < 10 ? '0' + d['G'] : d['G'];
        d['i'] = d['i'] < 10 ? '0' + d['i'] : d['i'];
        d['s'] = d['s'] < 10 ? '0' + d['s'] : d['s'];
        d['u'] = d['u'] < 10 ? '000' + d['u'] : d['u'] < 100 ? '00' + d['u'] : d['u'] < 1000 ? '0' + d['u'] : d['u'];
        d['N'] = d['w'] === 0 ? 7 : d['w'];
        d['l'] = elem.data('days')[(Number(d['N']) - 1)];
        d['D'] = d['l'].substr(0, elem.data('shortday-length'));
        d['S'] = String(d['j']).match(/[23]?1$/) ? 'st' : String(d['j']).match(/[23]?2$/) ? 'nd' : String(d['j']).match(/[23]?3$/) ? 'rd' : 'th';
        d['F'] = elem.data('months')[(Number(d['n']) - 1)];
        d['M'] = d['F'].substr(0, elem.data('shortmonth-length'));
        d['g'] = d['G'] <= 12 ? d['G'] : d['G'] - 12;
        d['h'] = d['g'] < 10 ? '0' + d['g'] : d['g'];
        d['a'] = d['G'] <= 12 ? 'am' : 'pm';
        d['A'] = d['a'].toUpperCase();
        // 'W' by mc-hollin http://forum.fhem.de/index.php/topic,34233.msg304630.html#msg304630
        var onejan = new Date(now.getFullYear(), 0, 1);
        var kw = Math.ceil((((now - onejan) / 86400000) + onejan.getDay() + 1) / 7);
        d['W'] = kw < 10 ? '0' + kw : kw;

        return d;
    }

    function init_datetext(format, d) {
        // split formatstring into it's letters and replace one after the other
        var datearr = format.split('');
        for (var l = 0; l < datearr.length; l++) {
            for (var key in d) {
                if (datearr[l] == key) {
                    datearr[l] = d[key];
                    // stop replacing after a match
                    break;
                }
            }
        }
        return datearr.join('');
    }

    function init_ui(elem) {

        var tid = setInterval(function () {
            if (elem && elem.data('days')) {

                var d = init_datearray(elem);
                var text = init_datetext(elem.data('format'), d);
                elem.text(text);

            } else {
                clearInterval(tid);
            }
        }, elem.data('interval'));
    }

    function update(dev, par) {}

    // public
    // inherit members from base class
    var me = $.extend(new Modul_widget(), {
        //override members
        widgetname: 'clock',
        init_ui: init_ui,
        init_attr: init_attr,
        update: update,
    });

    return me;
};<|endoftext|>


<commit_before>// Load packages
var path = require('path')
var run = require('./run')
var cmd = require('interactive-command')
var showOnly = require('./show-only')
var write = require('write')
var saveJSON = require('jsonfile')
var isThere = require('is-there')
saveJSON.spaces = 2

// Load configuration
var cfg = require('./config.js')

showOnly('Preparing Firebase backup - please wait ...')
run('node "' + path.resolve(cfg.packageRoot, 'scripts/prepare-firebase') + '"', function () {
  showOnly('Login to Firebase - please wait ...')

  cmd('./node_modules/.bin/firebase', ['login'], {cwd: cfg.projectRoot}, function () {
    showOnly('Backup Firebase database - please wait ...')
    cmd('firebase', ['database:get', '/'], {cwd: path.resolve(cfg.projectRoot, 'node_modules/firebase-tools/bin')}, function (res) {
      if (!isThere(cfg.appRoot + 'database-backup.json')) {
        write.sync(cfg.appRoot + 'database-backup.json', '{}')
      }
      saveJSON.writeFileSync(cfg.appRoot + 'database-backup.json', JSON.parse(res))
      showOnly('Clean up - please wait ...')
      run('node "' + path.resolve(cfg.packageRoot, 'scripts/cleanup-firebase') + '"', function () {
        showOnly('Firebase database backup done!')
      }, 'Firebase clean up failed')
    }, 'Firebase database backup failed')
  }, 'Firebase login failed')
}, 'Cannot prepare Firebase backup')
<commit_msg>adaption<commit_after>// Load packages
var path = require('path')
var run = require('./run')
var cmd = require('interactive-command')
var showOnly = require('./show-only')
//var write = require('write')
//var saveJSON = require('jsonfile')
var isThere = require('is-there')
//saveJSON.spaces = 2

// Load configuration
var cfg = require('./config.js')

showOnly('Preparing Firebase backup - please wait ...')
run('node "' + path.resolve(cfg.packageRoot, 'scripts/prepare-firebase') + '"', function () {
  showOnly('Login to Firebase - please wait ...')

  cmd('./node_modules/.bin/firebase', ['login'], {cwd: cfg.projectRoot}, function () {
    showOnly('Backup Firebase database - please wait ...')
    cmd('firebase', ['database:get', '/', '>../../../database-backup.json'], {cwd: path.resolve(cfg.projectRoot, 'node_modules/firebase-tools/bin')}, function (res) {
      /*
      if (!isThere(cfg.appRoot + 'database-backup.json')) {
        write.sync(cfg.appRoot + 'database-backup.json', '{}')
      }
      console.log("###", res, "###")
      saveJSON.writeFileSync(cfg.appRoot + 'database-backup.json', JSON.parse(res))
      */
      showOnly('Clean up - please wait ...')
      run('node "' + path.resolve(cfg.packageRoot, 'scripts/cleanup-firebase') + '"', function () {
        showOnly('Firebase database backup done!')
      }, 'Firebase clean up failed')
    }, 'Firebase database backup failed')
  }, 'Firebase login failed')
}, 'Cannot prepare Firebase backup')
<|endoftext|>


<commit_before>'use strict'

const Sequelize = require('sequelize')

module.exports = db => db.define('products', {
  title: {
    type: Sequelize.STRING,
    allowNull: false
  },
  description: {
    type: Sequelize.TEXT,
    allowNull: false
  },
  photos: {
    type: Sequelize.ARRAY(Sequelize.TEXT),
    defaultValue: ['http://via.placeholder.com/200x200']
  },
  price: {
    type: Sequelize.FLOAT,
    allowNull: false
  },
  quantity: {
    type: Sequelize.INTEGER,
    allowNull: false
  }
})

module.exports.associations = (Product, {Review, Category}) => {
  Product.hasMany(Review)
  Product.belongsToMany(Category)
}
<commit_msg>commented out associations to prevent push errors<commit_after>'use strict'

const Sequelize = require('sequelize')

module.exports = db => db.define('products', {
  title: {
    type: Sequelize.STRING,
    allowNull: false
  },
  description: {
    type: Sequelize.TEXT,
    allowNull: false
  },
  photos: {
    type: Sequelize.ARRAY(Sequelize.TEXT),
    defaultValue: ['http://via.placeholder.com/200x200']
  },
  price: {
    type: Sequelize.FLOAT,
    allowNull: false
  },
  quantity: {
    type: Sequelize.INTEGER,
    allowNull: false
  }
})

// module.exports.associations = (Product, {Review, Category}) => {
//   Product.hasMany(Review)
//   Product.belongsToMany(Category)
// }
<|endoftext|>


<commit_before>// ==UserScript==
// @name		Torrentz magnet
// @namespace		memmie.lenglet.name
// @author		mems <memmie@lenglet.name>
// @homepageURL 	https://github.com/mems/torrentz-magnet
// @description		Add magnet link to torrentz download page.
// @match		*://torrentz.unblocked.srl/*
// @match		*://*.torrentz2.eu/*
// @match		*://*.torrentz.com/*
// @match		*://*.torrentz.eu/*
// @match		*://*.torrentz.ch/*
// @match		*://*.torrentz.ph/*
// @match		*://*.torrentz.me/*
// @match		*://*.torrentz.in/*
// @match		*://*.torrentz.hk/*
// @match		*://*.torrentz.de/*
// @match		*://*.tz.ai/*
// @match		*://*.torrentz-proxy.com/*
// @match		*://*.torrentsmirror.com/*
// @match		*://*.torrentzeu.to/*
// @updateURL   	https://openuserjs.org/install/mems/Torrentz_magnet.user.js
// @version		1.1.6
// @grant		none
// ==/UserScript==

var list = document.querySelector(".download");
// Default list of track will be used in addition to trackers provided by torrentz
// Lists available (could be used to customize the following list):
// https://newtrackon.com/
// https://github.com/ngosang/trackerslist/blob/master/trackers_best.txt
var defaultTrackers = [
	"http://tracker.tfile.me/announce",
	"udp://tracker.openbittorrent.com:80/announce",
	"udp://tracker.internetwarriors.net:1337/announce",
	"udp://tracker.sktorrent.net:6969/announce",
	"udp://tracker.opentrackr.org:1337/announce",
	"udp://tracker.coppersurfer.tk:6969/announce",// http://tracker.coppersurfer.tk/
	"udp://tracker.leechers-paradise.org:6969/announce",
	"udp://tracker.zer0day.to:1337/announce",// http://zer0day.to/
	"udp://explodie.org:6969/announce",
	"udp://exodus.desync.com:6969/announce",
	"udp://tracker.pirateparty.gr:6969/announce",
	"udp://public.popcorn-tracker.org:6969/announce",
	"udp://tracker1.wasabii.com.tw:6969/announce",
	"udp://tracker2.wasabii.com.tw:6969/announce"
];
if(list){
	let name = list.querySelector("h2 span").textContent.trim();
	let hash = document.querySelector(".trackers > div, .trackers h2").textContent.trim().split(/:\s+|hash\s+/, 2)[1];
	let trackers = Array.from(document.querySelectorAll(".trackers dl a")).map(node => node.textContent.trim()).concat(defaultTrackers);
	let trackersCmps = trackers.reduce((result, uri) => result + "&tr=" + encodeURIComponent(uri), "");
	let uri = `magnet:?xt=urn:btih:${hash}&dn=${encodeURIComponent(name)}${trackersCmps}`;
	let v2 = /(^|\.)(torrentz2\.eu|torrentz\.unblocked\.srl)$/.test(location.hostname);
	let magnetIcon = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAOCAYAAAAfSC3RAAAAZUlEQVQokc2RQQrAMAgE9+g/99/5yvaSWDUV0lMrDATMiIsAoIZVbV9jjEQVu/4HohZmAiCSLs63ZOa0Ivb6nThv9D5jkCNRcpHkJqqsXyGpe5VDMUVZ8uOAnCvl9yKpOCR+rsIFGyA1+Hqs6JoAAAAASUVORK5CYII=";// from https://commons.wikimedia.org/wiki/File:Magnet-icon.gif
	list.querySelector("dl:first-of-type").insertAdjacentHTML("beforebegin", `

<span class="${v2 ? `j z s197"></span><span class="u"` : `u" style="background: transparent url('${magnetIcon}') no-repeat 5px center; color: red;"`}>Magnet ${name}

Magnet

	`);
}
<commit_msg>Fix main element selector<commit_after>// ==UserScript==
// @name		Torrentz magnet
// @namespace		memmie.lenglet.name
// @author		mems <memmie@lenglet.name>
// @homepageURL 	https://github.com/mems/torrentz-magnet
// @description		Add magnet link to torrentz download page.
// @match		*://torrentz.unblocked.srl/*
// @match		*://*.torrentz2.eu/*
// @match		*://*.torrentz.com/*
// @match		*://*.torrentz.eu/*
// @match		*://*.torrentz.ch/*
// @match		*://*.torrentz.ph/*
// @match		*://*.torrentz.me/*
// @match		*://*.torrentz.in/*
// @match		*://*.torrentz.hk/*
// @match		*://*.torrentz.de/*
// @match		*://*.tz.ai/*
// @match		*://*.torrentz-proxy.com/*
// @match		*://*.torrentsmirror.com/*
// @match		*://*.torrentzeu.to/*
// @updateURL   	https://openuserjs.org/install/mems/Torrentz_magnet.user.js
// @version		1.1.7
// @grant		none
// ==/UserScript==

let list = document.querySelector(".download,.downlinks");
// Default list of track will be used in addition to trackers provided by torrentz
// Lists available (could be used to customize the following list):
// https://newtrackon.com/
// https://github.com/ngosang/trackerslist/blob/master/trackers_best.txt
let defaultTrackers = [
	"http://tracker.tfile.me/announce",
	"udp://tracker.openbittorrent.com:80/announce",
	"udp://tracker.internetwarriors.net:1337/announce",
	"udp://tracker.sktorrent.net:6969/announce",
	"udp://tracker.opentrackr.org:1337/announce",
	"udp://tracker.coppersurfer.tk:6969/announce",// http://tracker.coppersurfer.tk/
	"udp://tracker.leechers-paradise.org:6969/announce",
	"udp://tracker.zer0day.to:1337/announce",// http://zer0day.to/
	"udp://explodie.org:6969/announce",
	"udp://exodus.desync.com:6969/announce",
	"udp://tracker.pirateparty.gr:6969/announce",
	"udp://public.popcorn-tracker.org:6969/announce",
	"udp://tracker1.wasabii.com.tw:6969/announce",
	"udp://tracker2.wasabii.com.tw:6969/announce"
];
if(list){
	let name = list.querySelector("h2 span").textContent.trim();
	let hash = document.querySelector(".trackers > div, .trackers h2").textContent.trim().split(/:\s+|hash\s+/, 2)[1];
	let trackers = Array.from(document.querySelectorAll(".trackers dl a")).map(node => node.textContent.trim()).concat(defaultTrackers);
	let trackersCmps = trackers.reduce((result, uri) => result + "&tr=" + encodeURIComponent(uri), "");
	let uri = `magnet:?xt=urn:btih:${hash}&dn=${encodeURIComponent(name)}${trackersCmps}`;
	let v2 = /(^|\.)(torrentz2\.eu|torrentz\.unblocked\.srl)$/.test(location.hostname);
	let magnetIcon = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAOCAYAAAAfSC3RAAAAZUlEQVQokc2RQQrAMAgE9+g/99/5yvaSWDUV0lMrDATMiIsAoIZVbV9jjEQVu/4HohZmAiCSLs63ZOa0Ivb6nThv9D5jkCNRcpHkJqqsXyGpe5VDMUVZ8uOAnCvl9yKpOCR+rsIFGyA1+Hqs6JoAAAAASUVORK5CYII=";// from https://commons.wikimedia.org/wiki/File:Magnet-icon.gif
	list.querySelector("dl:first-of-type").insertAdjacentHTML("beforebegin", `

<span class="${v2 ? `j z s197"></span><span class="u"` : `u" style="background: transparent url('${magnetIcon}') no-repeat 5px center; color: red;"`}>Magnet ${name}

Magnet

	`);
}
<|endoftext|>


<commit_before>'use strict';

var expect = require('expect.js'),
    KeyEncryptorKdf = require('../../lib/crypto/key-encryptor-kdf'),
    CryptoEngine = require('../../lib/crypto/crypto-engine'),
    Consts = require('../../lib/defs/consts'),
    ByteUtils = require('../../lib/utils/byte-utils'),
    Int64 = require('../../lib/utils/int64'),
    VarDictionary = require('../../lib/utils/var-dictionary');

describe('KeyEncryptorKdf', function() {
    var data = ByteUtils.hexToBytes('5d18f8a5ae0e7ea86f0ad817f0c0d40656ef1da6367d8a88508b3c13cec0d7af');
    var exp = '5d00000401200200130000000000000000000000000000000000000000000000';

    var cryptoEngineArgon2 = CryptoEngine.argon2;

    before(function() {
        CryptoEngine.argon2 = function(password, salt, memory, iterations, length, parallelism, type, version) {
            var res = new ArrayBuffer(32);
            var view = new DataView(res);
            view.setUint8(0, password[0]);
            view.setUint8(1, salt[0]);
            view.setInt16(2, memory);
            view.setInt8(4, iterations);
            view.setInt8(5, length);
            view.setInt8(6, parallelism);
            view.setInt8(7, type);
            view.setInt8(8, version);
            return Promise.resolve(res);
        };
    });

    after(function() {
        CryptoEngine.argon2 = cryptoEngineArgon2;
    });

    it('calls argon2 function', function() {
        var params = new VarDictionary();
        params.set('$UUID', VarDictionary.ValueType.Bytes, ByteUtils.base64ToBytes(Consts.KdfId.Argon2));
        var salt = new Uint8Array(32);
        salt[0] = 42;
        params.set('S', VarDictionary.ValueType.Bytes, salt);
        params.set('P', VarDictionary.ValueType.UInt32, 2);
        params.set('I', VarDictionary.ValueType.UInt64, new Int64(1));
        params.set('M', VarDictionary.ValueType.UInt64, new Int64(1024 * 4));
        params.set('V', VarDictionary.ValueType.UInt32, 0x13);
        return KeyEncryptorKdf.encrypt(data, params).then(function(res) {
            expect(ByteUtils.bytesToHex(res)).to.be(exp);
        });
    });

    it('throws error for no uuid', function() {
        var params = new VarDictionary();
        return KeyEncryptorKdf.encrypt(data, params).then(function() { throw 'Not expected'; })
            .catch(function(e) {
                expect(e.message).to.contain('FileCorrupt: no kdf uuid');
            });
    });

    it('throws error for invalid uuid', function() {
        var params = new VarDictionary();
        params.set('$UUID', VarDictionary.ValueType.Bytes, new ArrayBuffer(32));
        return KeyEncryptorKdf.encrypt(data, params).then(function() { throw 'Not expected'; })
            .catch(function(e) {
                expect(e.message).to.contain('Unsupported: bad kdf');
            });
    });

    it('throws error for bad salt', function() {
        var params = new VarDictionary();
        params.set('$UUID', VarDictionary.ValueType.Bytes, ByteUtils.base64ToBytes(Consts.KdfId.Argon2));
        params.set('S', VarDictionary.ValueType.Bytes, new ArrayBuffer(10));
        return KeyEncryptorKdf.encrypt(data, params).then(function() { throw 'Not expected'; })
            .catch(function(e) {
                expect(e.message).to.contain('FileCorrupt: bad argon2 salt');
            });
    });

    it('throws error for bad parallelism', function() {
        var params = new VarDictionary();
        params.set('$UUID', VarDictionary.ValueType.Bytes, ByteUtils.base64ToBytes(Consts.KdfId.Argon2));
        params.set('S', VarDictionary.ValueType.Bytes, new ArrayBuffer(32));
        params.set('P', VarDictionary.ValueType.Int32, -1);
        return KeyEncryptorKdf.encrypt(data, params).then(function() { throw 'Not expected'; })
            .catch(function(e) {
                expect(e.message).to.contain('FileCorrupt: bad argon2 parallelism');
            });
    });

    it('throws error for bad iterations', function() {
        var params = new VarDictionary();
        params.set('$UUID', VarDictionary.ValueType.Bytes, ByteUtils.base64ToBytes(Consts.KdfId.Argon2));
        params.set('S', VarDictionary.ValueType.Bytes, new ArrayBuffer(32));
        params.set('P', VarDictionary.ValueType.Int32, 1);
        params.set('I', VarDictionary.ValueType.Int32, -1);
        return KeyEncryptorKdf.encrypt(data, params).then(function() { throw 'Not expected'; })
            .catch(function(e) {
                expect(e.message).to.contain('FileCorrupt: bad argon2 iterations');
            });
    });

    it('throws error for bad memory', function() {
        var params = new VarDictionary();
        params.set('$UUID', VarDictionary.ValueType.Bytes, ByteUtils.base64ToBytes(Consts.KdfId.Argon2));
        params.set('S', VarDictionary.ValueType.Bytes, new ArrayBuffer(32));
        params.set('P', VarDictionary.ValueType.Int32, 1);
        params.set('I', VarDictionary.ValueType.Int32, 1);
        params.set('M', VarDictionary.ValueType.Int32, 123);
        return KeyEncryptorKdf.encrypt(data, params).then(function() { throw 'Not expected'; })
            .catch(function(e) {
                expect(e.message).to.contain('FileCorrupt: bad argon2 memory');
            });
    });

    it('throws error for bad version', function() {
        var params = new VarDictionary();
        params.set('$UUID', VarDictionary.ValueType.Bytes, ByteUtils.base64ToBytes(Consts.KdfId.Argon2));
        params.set('S', VarDictionary.ValueType.Bytes, new ArrayBuffer(32));
        params.set('P', VarDictionary.ValueType.Int32, 1);
        params.set('I', VarDictionary.ValueType.Int32, 1);
        params.set('M', VarDictionary.ValueType.Int32, 1024);
        params.set('V', VarDictionary.ValueType.Int32, 5);
        return KeyEncryptorKdf.encrypt(data, params).then(function() { throw 'Not expected'; })
            .catch(function(e) {
                expect(e.message).to.contain('FileCorrupt: bad argon2 version');
            });
    });

    it('throws error for secret key', function() {
        var params = new VarDictionary();
        params.set('$UUID', VarDictionary.ValueType.Bytes, ByteUtils.base64ToBytes(Consts.KdfId.Argon2));
        params.set('S', VarDictionary.ValueType.Bytes, new ArrayBuffer(32));
        params.set('P', VarDictionary.ValueType.Int32, 1);
        params.set('I', VarDictionary.ValueType.Int32, 1);
        params.set('M', VarDictionary.ValueType.Int32, 1024);
        params.set('V', VarDictionary.ValueType.Int32, 0x10);
        params.set('K', VarDictionary.ValueType.Bytes, new ArrayBuffer(32));
        return KeyEncryptorKdf.encrypt(data, params).then(function() { throw 'Not expected'; })
            .catch(function(e) {
                expect(e.message).to.contain('Unsupported: argon2 secret key');
            });
    });

    it('throws error for assoc data', function() {
        var params = new VarDictionary();
        params.set('$UUID', VarDictionary.ValueType.Bytes, ByteUtils.base64ToBytes(Consts.KdfId.Argon2));
        params.set('S', VarDictionary.ValueType.Bytes, new ArrayBuffer(32));
        params.set('P', VarDictionary.ValueType.Int32, 1);
        params.set('I', VarDictionary.ValueType.Int32, 1);
        params.set('M', VarDictionary.ValueType.Int32, 1024);
        params.set('V', VarDictionary.ValueType.Int32, 0x13);
        params.set('A', VarDictionary.ValueType.Bytes, new ArrayBuffer(32));
        return KeyEncryptorKdf.encrypt(data, params).then(function() { throw 'Not expected'; })
            .catch(function(e) {
                expect(e.message).to.contain('Unsupported: argon2 assoc data');
            });
    });

    it('calls aes function', function() {
        var params = new VarDictionary();
        params.set('$UUID', VarDictionary.ValueType.Bytes, ByteUtils.base64ToBytes(Consts.KdfId.Aes));
        var key = ByteUtils.hexToBytes('ee66af917de0b0336e659fe6bd40a337d04e3c2b3635210fa16f28fb24d563ac');
        var salt = ByteUtils.hexToBytes('5d18f8a5ae0e7ea86f0ad817f0c0d40656ef1da6367d8a88508b3c13cec0d7af');
        var result = 'af0be2c639224ad37bd2bc7967d6c3303a8a6d4b7813718918a66bde96dc3132';
        params.set('S', VarDictionary.ValueType.Bytes, salt);
        params.set('R', VarDictionary.ValueType.UInt32, 2);
        return KeyEncryptorKdf.encrypt(key, params).then(function(res) {
            expect(ByteUtils.bytesToHex(res)).to.be(result);
        });
    });

    it('throws error for bad aes salt', function() {
        var params = new VarDictionary();
        params.set('$UUID', VarDictionary.ValueType.Bytes, ByteUtils.base64ToBytes(Consts.KdfId.Aes));
        params.set('S', VarDictionary.ValueType.Bytes, new ArrayBuffer(10));
        return KeyEncryptorKdf.encrypt(data, params).then(function() { throw 'Not expected'; })
            .catch(function(e) {
                expect(e.message).to.contain('FileCorrupt: bad aes salt');
            });
    });

    it('throws error for bad aes rounds', function() {
        var params = new VarDictionary();
        params.set('$UUID', VarDictionary.ValueType.Bytes, ByteUtils.base64ToBytes(Consts.KdfId.Aes));
        params.set('S', VarDictionary.ValueType.Bytes, new ArrayBuffer(32));
        params.set('R', VarDictionary.ValueType.Int32, -1);
        return KeyEncryptorKdf.encrypt(data, params).then(function() { throw 'Not expected'; })
            .catch(function(e) {
                expect(e.message).to.contain('FileCorrupt: bad aes rounds');
            });
    });
});
<commit_msg>fixed types in tests<commit_after>'use strict';

var expect = require('expect.js'),
    KeyEncryptorKdf = require('../../lib/crypto/key-encryptor-kdf'),
    CryptoEngine = require('../../lib/crypto/crypto-engine'),
    Consts = require('../../lib/defs/consts'),
    ByteUtils = require('../../lib/utils/byte-utils'),
    Int64 = require('../../lib/utils/int64'),
    VarDictionary = require('../../lib/utils/var-dictionary');

describe('KeyEncryptorKdf', function() {
    var data = ByteUtils.hexToBytes('5d18f8a5ae0e7ea86f0ad817f0c0d40656ef1da6367d8a88508b3c13cec0d7af');
    var exp = '5d00000401200200130000000000000000000000000000000000000000000000';

    var cryptoEngineArgon2 = CryptoEngine.argon2;

    before(function() {
        CryptoEngine.argon2 = function(password, salt, memory, iterations, length, parallelism, type, version) {
            var res = new ArrayBuffer(32);
            var view = new DataView(res);
            view.setUint8(0, password[0]);
            view.setUint8(1, salt[0]);
            view.setInt16(2, memory);
            view.setInt8(4, iterations);
            view.setInt8(5, length);
            view.setInt8(6, parallelism);
            view.setInt8(7, type);
            view.setInt8(8, version);
            return Promise.resolve(res);
        };
    });

    after(function() {
        CryptoEngine.argon2 = cryptoEngineArgon2;
    });

    it('calls argon2 function', function() {
        var params = new VarDictionary();
        params.set('$UUID', VarDictionary.ValueType.Bytes, ByteUtils.base64ToBytes(Consts.KdfId.Argon2));
        var salt = new Uint8Array(32);
        salt[0] = 42;
        params.set('S', VarDictionary.ValueType.Bytes, salt);
        params.set('P', VarDictionary.ValueType.UInt32, 2);
        params.set('I', VarDictionary.ValueType.UInt64, new Int64(1));
        params.set('M', VarDictionary.ValueType.UInt64, new Int64(1024 * 4));
        params.set('V', VarDictionary.ValueType.UInt32, 0x13);
        return KeyEncryptorKdf.encrypt(data, params).then(function(res) {
            expect(ByteUtils.bytesToHex(res)).to.be(exp);
        });
    });

    it('throws error for no uuid', function() {
        var params = new VarDictionary();
        return KeyEncryptorKdf.encrypt(data, params).then(function() { throw 'Not expected'; })
            .catch(function(e) {
                expect(e.message).to.contain('FileCorrupt: no kdf uuid');
            });
    });

    it('throws error for invalid uuid', function() {
        var params = new VarDictionary();
        params.set('$UUID', VarDictionary.ValueType.Bytes, new ArrayBuffer(32));
        return KeyEncryptorKdf.encrypt(data, params).then(function() { throw 'Not expected'; })
            .catch(function(e) {
                expect(e.message).to.contain('Unsupported: bad kdf');
            });
    });

    it('throws error for bad salt', function() {
        var params = new VarDictionary();
        params.set('$UUID', VarDictionary.ValueType.Bytes, ByteUtils.base64ToBytes(Consts.KdfId.Argon2));
        params.set('S', VarDictionary.ValueType.Bytes, new ArrayBuffer(10));
        return KeyEncryptorKdf.encrypt(data, params).then(function() { throw 'Not expected'; })
            .catch(function(e) {
                expect(e.message).to.contain('FileCorrupt: bad argon2 salt');
            });
    });

    it('throws error for bad parallelism', function() {
        var params = new VarDictionary();
        params.set('$UUID', VarDictionary.ValueType.Bytes, ByteUtils.base64ToBytes(Consts.KdfId.Argon2));
        params.set('S', VarDictionary.ValueType.Bytes, new ArrayBuffer(32));
        params.set('P', VarDictionary.ValueType.Int32, -1);
        return KeyEncryptorKdf.encrypt(data, params).then(function() { throw 'Not expected'; })
            .catch(function(e) {
                expect(e.message).to.contain('FileCorrupt: bad argon2 parallelism');
            });
    });

    it('throws error for bad iterations', function() {
        var params = new VarDictionary();
        params.set('$UUID', VarDictionary.ValueType.Bytes, ByteUtils.base64ToBytes(Consts.KdfId.Argon2));
        params.set('S', VarDictionary.ValueType.Bytes, new ArrayBuffer(32));
        params.set('P', VarDictionary.ValueType.Int32, 1);
        params.set('I', VarDictionary.ValueType.Int32, -1);
        return KeyEncryptorKdf.encrypt(data, params).then(function() { throw 'Not expected'; })
            .catch(function(e) {
                expect(e.message).to.contain('FileCorrupt: bad argon2 iterations');
            });
    });

    it('throws error for bad memory', function() {
        var params = new VarDictionary();
        params.set('$UUID', VarDictionary.ValueType.Bytes, ByteUtils.base64ToBytes(Consts.KdfId.Argon2));
        params.set('S', VarDictionary.ValueType.Bytes, new ArrayBuffer(32));
        params.set('P', VarDictionary.ValueType.Int32, 1);
        params.set('I', VarDictionary.ValueType.Int32, 1);
        params.set('M', VarDictionary.ValueType.Int32, 123);
        return KeyEncryptorKdf.encrypt(data, params).then(function() { throw 'Not expected'; })
            .catch(function(e) {
                expect(e.message).to.contain('FileCorrupt: bad argon2 memory');
            });
    });

    it('throws error for bad version', function() {
        var params = new VarDictionary();
        params.set('$UUID', VarDictionary.ValueType.Bytes, ByteUtils.base64ToBytes(Consts.KdfId.Argon2));
        params.set('S', VarDictionary.ValueType.Bytes, new ArrayBuffer(32));
        params.set('P', VarDictionary.ValueType.Int32, 1);
        params.set('I', VarDictionary.ValueType.Int32, 1);
        params.set('M', VarDictionary.ValueType.Int32, 1024);
        params.set('V', VarDictionary.ValueType.Int32, 5);
        return KeyEncryptorKdf.encrypt(data, params).then(function() { throw 'Not expected'; })
            .catch(function(e) {
                expect(e.message).to.contain('FileCorrupt: bad argon2 version');
            });
    });

    it('throws error for secret key', function() {
        var params = new VarDictionary();
        params.set('$UUID', VarDictionary.ValueType.Bytes, ByteUtils.base64ToBytes(Consts.KdfId.Argon2));
        params.set('S', VarDictionary.ValueType.Bytes, new ArrayBuffer(32));
        params.set('P', VarDictionary.ValueType.Int32, 1);
        params.set('I', VarDictionary.ValueType.Int32, 1);
        params.set('M', VarDictionary.ValueType.Int32, 1024);
        params.set('V', VarDictionary.ValueType.Int32, 0x10);
        params.set('K', VarDictionary.ValueType.Bytes, new ArrayBuffer(32));
        return KeyEncryptorKdf.encrypt(data, params).then(function() { throw 'Not expected'; })
            .catch(function(e) {
                expect(e.message).to.contain('Unsupported: argon2 secret key');
            });
    });

    it('throws error for assoc data', function() {
        var params = new VarDictionary();
        params.set('$UUID', VarDictionary.ValueType.Bytes, ByteUtils.base64ToBytes(Consts.KdfId.Argon2));
        params.set('S', VarDictionary.ValueType.Bytes, new ArrayBuffer(32));
        params.set('P', VarDictionary.ValueType.Int32, 1);
        params.set('I', VarDictionary.ValueType.Int32, 1);
        params.set('M', VarDictionary.ValueType.Int32, 1024);
        params.set('V', VarDictionary.ValueType.Int32, 0x13);
        params.set('A', VarDictionary.ValueType.Bytes, new ArrayBuffer(32));
        return KeyEncryptorKdf.encrypt(data, params).then(function() { throw 'Not expected'; })
            .catch(function(e) {
                expect(e.message).to.contain('Unsupported: argon2 assoc data');
            });
    });

    it('calls aes function', function() {
        var params = new VarDictionary();
        params.set('$UUID', VarDictionary.ValueType.Bytes, ByteUtils.base64ToBytes(Consts.KdfId.Aes));
        var key = ByteUtils.hexToBytes('ee66af917de0b0336e659fe6bd40a337d04e3c2b3635210fa16f28fb24d563ac');
        var salt = ByteUtils.hexToBytes('5d18f8a5ae0e7ea86f0ad817f0c0d40656ef1da6367d8a88508b3c13cec0d7af');
        var result = 'af0be2c639224ad37bd2bc7967d6c3303a8a6d4b7813718918a66bde96dc3132';
        params.set('S', VarDictionary.ValueType.Bytes, salt);
        params.set('R', VarDictionary.ValueType.Int64, new Int64(2));
        return KeyEncryptorKdf.encrypt(key, params).then(function(res) {
            expect(ByteUtils.bytesToHex(res)).to.be(result);
        });
    });

    it('throws error for bad aes salt', function() {
        var params = new VarDictionary();
        params.set('$UUID', VarDictionary.ValueType.Bytes, ByteUtils.base64ToBytes(Consts.KdfId.Aes));
        params.set('S', VarDictionary.ValueType.Bytes, new ArrayBuffer(10));
        return KeyEncryptorKdf.encrypt(data, params).then(function() { throw 'Not expected'; })
            .catch(function(e) {
                expect(e.message).to.contain('FileCorrupt: bad aes salt');
            });
    });

    it('throws error for bad aes rounds', function() {
        var params = new VarDictionary();
        params.set('$UUID', VarDictionary.ValueType.Bytes, ByteUtils.base64ToBytes(Consts.KdfId.Aes));
        params.set('S', VarDictionary.ValueType.Bytes, new ArrayBuffer(32));
        params.set('R', VarDictionary.ValueType.Int64, new Int64(-1));
        return KeyEncryptorKdf.encrypt(data, params).then(function() { throw 'Not expected'; })
            .catch(function(e) {
                expect(e.message).to.contain('FileCorrupt: bad aes rounds');
            });
    });
});
<|endoftext|>


<commit_before>const expect = require('chai').expect
const authenticationHelper = require('../helpers/routes/authentication-helper')

let pageTitle, pageSubtitle

describe('View archive data', () => {
  before(async function () {
    await authenticationHelper.login(authenticationHelper.users.DataAdmin)
  })
  describe('should navigate to the archive page', () => {
    it('with the correct breadcrumbs and heading title', async () => {
      const link = await $('[href="/admin"]')
      await link.click()
      const archiveDataLink = await $('[href="/archive-options"]')
      await archiveDataLink.click()

      const dailyCaseloadLink = await $('[href="/archive-data/average-caseload-data"]')
      await dailyCaseloadLink.click()
      pageTitle = await $('.govuk-heading-xl')
      pageTitle = await pageTitle.getText()
      pageSubtitle = await $('.govuk-caption-xl')
      pageSubtitle = await pageSubtitle.getText()

      expect(pageTitle).to.equal('Averaged Caseload Data')
      expect(pageSubtitle).to.equal('Archive Data')

      const archiveFromDay = await $('#archive-from-day')
      const archiveFromMonth = await $('#archive-from-month')
      const archiveFromYear = await $('#archive-from-year')
      const archiveToDay = await $('#archive-to-day')
      const archiveToMonth = await $('#archive-to-month')
      const archiveToYear = await $('#archive-to-year')
      const extraSearchCritera = await $('.select2-search__field')

      await archiveFromDay.setValue('31')
      await archiveFromMonth.setValue('12')
      await archiveFromYear.setValue('2014')
      await archiveToDay.setValue('6')
      await archiveToMonth.setValue('1')
      await archiveToYear.setValue('2015')
      await browser.saveScreenshot('./test_results/e2e/screenshots/averageArchiveData.png')
      await extraSearchCritera.waitForExist({ timeout: 5000 })
      await extraSearchCritera.setValue('t')

      const criteriaName = await $('#select2-multi-search-field-results li[data-select2-id="5"]')
      await criteriaName.waitForExist({ timeout: 5000 })
      await criteriaName.click()

      const searchButton = await $('#archive-average-filter-submit')

      await searchButton.click()

      const tableData = await browser.findElements('xpath', '//*[@id="average-caseload-table"]/tbody/tr/td[position()=6]')

      const nameElement = await $(tableData[0])
      const nameElementValue = await nameElement.getText()
      expect(nameElementValue).to.equal('Test_forename Test_surname')
    })
  })

  after(function () {
    authenticationHelper.logout()
  })
})
<commit_msg>added log of html to debug<commit_after>const expect = require('chai').expect
const authenticationHelper = require('../helpers/routes/authentication-helper')

let pageTitle, pageSubtitle

describe('View archive data', () => {
  before(async function () {
    await authenticationHelper.login(authenticationHelper.users.DataAdmin)
  })
  describe('should navigate to the archive page', () => {
    it('with the correct breadcrumbs and heading title', async () => {
      const link = await $('[href="/admin"]')
      await link.click()
      const archiveDataLink = await $('[href="/archive-options"]')
      await archiveDataLink.click()

      const dailyCaseloadLink = await $('[href="/archive-data/average-caseload-data"]')
      await dailyCaseloadLink.click()
      pageTitle = await $('.govuk-heading-xl')
      pageTitle = await pageTitle.getText()
      pageSubtitle = await $('.govuk-caption-xl')
      pageSubtitle = await pageSubtitle.getText()

      expect(pageTitle).to.equal('Averaged Caseload Data')
      expect(pageSubtitle).to.equal('Archive Data')

      const archiveFromDay = await $('#archive-from-day')
      const archiveFromMonth = await $('#archive-from-month')
      const archiveFromYear = await $('#archive-from-year')
      const archiveToDay = await $('#archive-to-day')
      const archiveToMonth = await $('#archive-to-month')
      const archiveToYear = await $('#archive-to-year')
      const extraSearchCritera = await $('#multiSearchField').getHTML()
      console.log(extraSearchCritera)

      await archiveFromDay.setValue('31')
      await archiveFromMonth.setValue('12')
      await archiveFromYear.setValue('2014')
      await archiveToDay.setValue('6')
      await archiveToMonth.setValue('1')
      await archiveToYear.setValue('2015')
      await browser.saveScreenshot('./test_results/e2e/screenshots/averageArchiveData.png')
      await extraSearchCritera.waitForExist({ timeout: 5000 })
      await extraSearchCritera.setValue('t')

      const criteriaName = await $('#select2-multi-search-field-results li[data-select2-id="5"]')
      await criteriaName.waitForExist({ timeout: 5000 })
      await criteriaName.click()

      const searchButton = await $('#archive-average-filter-submit')

      await searchButton.click()

      const tableData = await browser.findElements('xpath', '//*[@id="average-caseload-table"]/tbody/tr/td[position()=6]')

      const nameElement = await $(tableData[0])
      const nameElementValue = await nameElement.getText()
      expect(nameElementValue).to.equal('Test_forename Test_surname')
    })
  })

  after(function () {
    authenticationHelper.logout()
  })
})
<|endoftext|>


<commit_before>import leapjs from "leapjs";

import Signal from "../utils/Signal.js";

import Matrix3 from "../math/Matrix3.js";
import Matrix4 from "../math/Matrix4.js";
import Vector3 from "../math/Vector3.js";
import Quaternion from "../math/Quaternion.js";

const BONE_PREFIXES = [
  "carp",
  "mcp",
  "pip",
  "dip"
];

class Hand {
  constructor() {
    this._bones = new Array(5).fill().map(value => new Array(4).fill().map(value => new Quaternion()));
    this._boneMatrices = new Array(5).fill().map(value => new Array(4).fill().map(value => new Matrix4()));

    this._position = new Vector3();
    this._rotation = new Quaternion();

    this._vector3A = new Vector3();
    this._vector3B = new Vector3();
    this._vector3C = new Vector3();

    this._matrix3 = new Matrix3();

    this._quaternion = new Quaternion();
  }

  get position() {
    return this._position;
  }

  get rotation() {
    return this._rotation;
  }

  get bones() {
    return this._bones;
  }

  update(handData, pointablesData) {
    this.position.set(handData.palmPosition[0], handData.palmPosition[1], handData.palmPosition[2]);

    this._vector3A.copy(handData.direction);
    this._vector3A.negate();
    this._vector3B.copy(handData.palmNormal);
    this._vector3B.negate();
    this._vector3C.cross(this._vector3B, this._vector3A);

    this._matrix3.fromBasis(this._vector3C, this._vector3B, this._vector3A);

    this.rotation.fromMatrix3(this._matrix3);

    for (let pointableData of pointablesData) {
      if (pointableData.handId !== handData.id) {
        continue;
      }

      this._quaternion.copy(this.rotation);

      for (let i = 0; i < 4; i++) {
        let bone = this.bones[pointableData.type][i];

        let basis = pointableData.bones[i].basis;

        // Global
        let position = pointableData[`${BONE_PREFIXES[i]}Position`];
        this._boneMatrices[pointableData.type][i].set(
          basis[0][0], basis[0][1], basis[0][2], 0,
          basis[1][0], basis[1][1], basis[1][2], 0,
          basis[2][0], basis[2][1], basis[2][2], 0,
          position[0] * .02, (position[1] - 100) * .02, position[2] * .02, 1
        );

        // Local
        this._matrix3.fromBasis(basis[0], basis[1], basis[2]);

        bone.fromMatrix3(this._matrix3);

        this._quaternion.invert();

        bone.multiply(this._quaternion, bone);

        this._quaternion.invert();
        this._quaternion.multiply(bone);
      }
    }
  }
}

class HandTracker {
  constructor() {
      let controller = new leapjs.Controller({
        host: "127.0.0.1"
      });

      this.hands = new Map();

      this.frame = null;

      this.onHandAdd = new Signal();

      controller.on("frame", this.onFrame.bind(this));

      controller.connect();
  }

  onFrame(frame) {
    this.frame = frame.data;

    if(!this.frame) {
      return;
    }

    for(let handData of this.frame.hands) {
      let hand = this.hands.get(handData.id);
      if(!hand) {
        hand = new Hand();
        this.hands.set(handData.id, hand);
        this.onHandAdd.dispatch(hand);
      }
      hand.update(handData, frame.pointables);
    }
  }
}

export default new HandTracker();
<commit_msg>clean HandTracker<commit_after>import leapjs from "leapjs";

import Signal from "../utils/Signal.js";

import Matrix3 from "../math/Matrix3.js";
import Matrix4 from "../math/Matrix4.js";
import Vector3 from "../math/Vector3.js";
import Quaternion from "../math/Quaternion.js";

class Hand {
  constructor() {
    this._bones = new Array(5).fill().map(value => new Array(4).fill().map(value => new Quaternion()));

    this._position = new Vector3();
    this._rotation = new Quaternion();

    this._vector3A = new Vector3();
    this._vector3B = new Vector3();
    this._vector3C = new Vector3();

    this._matrix3 = new Matrix3();

    this._quaternion = new Quaternion();
  }

  get position() {
    return this._position;
  }

  get rotation() {
    return this._rotation;
  }

  get bones() {
    return this._bones;
  }

  update(handData, pointablesData) {
    this.position.set(handData.palmPosition[0], handData.palmPosition[1], handData.palmPosition[2]);

    this._vector3A.copy(handData.direction);
    this._vector3A.negate();
    this._vector3B.copy(handData.palmNormal);
    this._vector3B.negate();
    this._vector3C.cross(this._vector3B, this._vector3A);

    this._matrix3.fromBasis(this._vector3C, this._vector3B, this._vector3A);

    this.rotation.fromMatrix3(this._matrix3);

    for (let pointableData of pointablesData) {
      if (pointableData.handId !== handData.id) {
        continue;
      }

      this._quaternion.copy(this.rotation);

      for (let i = 0; i < 4; i++) {
        let bone = this.bones[pointableData.type][i];

        let basis = pointableData.bones[i].basis;

        this._matrix3.fromBasis(basis[0], basis[1], basis[2]);

        bone.fromMatrix3(this._matrix3);

        this._quaternion.invert();
        bone.multiply(this._quaternion, bone);

        this._quaternion.invert();
        this._quaternion.multiply(bone);
      }
    }
  }
}

class HandTracker {
  constructor() {
      let controller = new leapjs.Controller({
        host: "127.0.0.1"
      });

      this.hands = new Map();

      this.frame = null;

      this.onHandAdd = new Signal();

      controller.on("frame", this.onFrame.bind(this));

      controller.connect();
  }

  onFrame(frame) {
    this.frame = frame.data;

    if(!this.frame) {
      return;
    }

    for(let handData of this.frame.hands) {
      let hand = this.hands.get(handData.id);
      if(!hand) {
        hand = new Hand();
        this.hands.set(handData.id, hand);
        this.onHandAdd.dispatch(hand);
      }
      hand.update(handData, frame.pointables);
    }
  }
}

export default new HandTracker();
<|endoftext|>


<commit_before>var init = function (initialise_callback) {
		var lisp_fns = {
				"+": {
					"minArity": 0,
					"maxArity": Infinity,
					"dataType": "number",
					"fn": function (args) {
						var rtn = 0; // CLISP returns 0 if `+` is given no arguments.
						while (args.length) {
							rtn += args.shift();
						};
						return rtn;
					}
				},
				"-": function (args) {
					var rtn = args.shift();
					while (args.length) {
						rtn -= args.shift();
					};
					return rtn;
				},
				"*": function (args) {
					var rtn = 1; // CLISP returns 1 if `*` is given no arguments.
					while (args.length) {
						rtn *= args.shift();
					};
					return rtn;
				},
				"/": function (args) {
					var rtn = args.shift();
					while (args.length) {
						rtn /= args.shift();
					}
					return rtn;
				}
			},

			wrap_function = function (fn_object) {

				// Decide on how the function should be accessed.
				var fn = fn_object.fn || fn_object,
					maxArity = fn_object.maxArity || Infinity,
					minArity = fn_object.minArity || 0,
					dataType = fn_object.dataType || [ "number", "string" ],
					checkType = function (arg) {
						var rtn = false,
							d;
						if (dataType instanceof Array) {
							for (d = dataType.length - 1; (d + 1) && !rtn; d -= 1) {
								rtn = (typeof arg === dataType[d]);
							}
						} else if (typeof dataType === "string") {
							rtn = typeof arg === dataType;
						}
						return rtn;
					};

				return function (args) {
					var rtn = {},
						func_rtn,
						a,
						unpacked = [];

					if (args instanceof Array) {
						a = args.length;

						if (a > maxArity) {
							rtn.error = "too many arguments";
						} else if (a < minArity) {
							rtn.error = "too few arguments";
						}

						// Search for any one argument that goes against type, whilst unpacking.
						for (; a && checkType(unpacked[a - 1] = (args[a - 1].value || args[a - 1])); a -= 1); // no body

						// When a is falsy, the arguments are type-safe.
						if (!a) {
							func_rtn = fn(unpacked);
							if (typeof func_rtn === "object" && (func_rtn.hasOwnProperty("value") || func_rtn.hasOwnProperty("error"))) {
								rtn = func_rtn;
							} else {
								rtn.value = func_rtn;
							}
						} else {
							rtn.error = "The argument " + (args[a - 1].value || args[a - 1]) + " was the wrong type.";
						}
					} else {
						rtn.error = "Fault with Lijst. Arguments not passed as array.";
					}
					return rtn;
				}
			},

			separate_terms = function (input) {
				var str = input,
					arr = [],
					rst = "",
					rex = /(\s+)|(")|(\()|(\))|(.$)/g,
					begin_term = 0,
					end_term = 0,
					paren_level = 0,
					quote_level = false,
					rfn = function ($m, $1, $2, $3, $4, $5, offset, whole_string) {
						var out;
						if ($2 && !paren_level) {
							console.log(quote_level);
							quote_level = !quote_level;
							if (quote_level) {
								begin_term = offset;
							} else {
								end_term = offset + $m.length;
								out = whole_string.slice(begin_term, end_term);
								begin_term = end_term;
							}
						} else if ($3 && !quote_level) {
							paren_level += 1;
							if (!paren_level) {
								begin_term = offset;
							}
						} else if ($4 && !quote_level) {
							paren_level -= 1;
							if (!paren_level) {
								end_term = offset + $m.length;
								out = whole_string.slice(begin_term, end_term);
								begin_term = end_term;
							}
						} else if ($1 && !paren_level && !quote_level) {
							end_term = offset;
							out = whole_string.slice(begin_term, end_term);
							begin_term = end_term + $m.length;
						} else if ($5 && !quote_level) {
							end_term = whole_string.length;
							out = whole_string.slice(begin_term, end_term);
							begin_term = end_term + $m.length;
						}

						if (out) { arr.push(out); };
						return $m;
					};

				rst = str.replace(rex, rfn);
				return arr;
			},

			evaluate_term = function (term) {
				var rtn,
					arr,
					fun,
					arg = [],
					term = term[0];
				if (/\D/g.test(term)) {
					if (/^\(.*\)$/.test(term)) {
						if (term.slice(1, -1)) {
							arr = separate_terms(term.slice(1, -1));
							fun = arr.shift();
							while (arr.length) {
								arg.push(evaluate_term(arr.splice(0, 1)));
							}
							if (lisp_fns.hasOwnProperty(fun)) {
								rtn = lisp_fns[fun](arg);
							} else {
								// TODO: What if there is no such function?
							}
						} else {
							// If parentheses are empty.
							rtn = "NIL";
						}
					} else if (/^".*"$/g.test(term)) {
						console.log(term);
						rtn = term;
					}
				} else {
					rtn = +term;
				}
				return rtn;
			},

			// Top-level processing of input.
			process_input = function (input, callback_each_term) {
				var rtn,
					arr = separate_terms(input),
					rst;

				while (arr.length) {
					// Extract first term from array and evaluate.
					rst = evaluate_term(arr.splice(0, 1));
					// Do something with the input and results.
					callback_each_term(input, print_result(rst));
					// Reset the input. We have already done something with it once.
					input = "";
				}

				return rtn;
			},

			print_result = function (result) {
				var rtn;
				if (result.hasOwnProperty("value")) {
					if (typeof result.value === "number") {
						rtn = "" + result.value;
					} else {
						rtn = result.value;
					}
				} else if (result.hasOwnProperty("error")) {
					rtn = "*** - " + result.error;
				} else {
					rtn = "Error at printing stage. No value or processing error found.";
				}
				return rtn;
			},

			f;

		// Wrap predefined lisp functions in error-checking function.
		for (f in lisp_fns) {
			if (lisp_fns.hasOwnProperty(f)) {
				lisp_fns[f] = wrap_function(lisp_fns[f]);
			}
		}

		evaluate_term = wrap_function(evaluate_term);

		initialise_callback();

		return {
			process_input: process_input
		};

	};

// Node JS compatibility
if (typeof exports !== "undefined") {
	exports.init = init;
}<commit_msg>Added information about parameters for the - lisp_fn.<commit_after>var init = function (initialise_callback) {
		var lisp_fns = {
				"+": {
					"minArity": 0,
					"maxArity": Infinity,
					"dataType": "number",
					"fn": function (args) {
						var rtn = 0; // CLISP returns 0 if `+` is given no arguments.
						while (args.length) {
							rtn += args.shift();
						};
						return rtn;
					}
				},
				"-": {
					"minArity": 1,
					"maxArity": Infinity,
					"dataType": "number",
					"fn": function (args) {
						var rtn = args.shift();
						while (args.length) {
							rtn -= args.shift();
						};
						return rtn;
					}
				},
				"*": function (args) {
					var rtn = 1; // CLISP returns 1 if `*` is given no arguments.
					while (args.length) {
						rtn *= args.shift();
					};
					return rtn;
				},
				"/": function (args) {
					var rtn = args.shift();
					while (args.length) {
						rtn /= args.shift();
					}
					return rtn;
				}
			},

			wrap_function = function (fn_object) {

				// Decide on how the function should be accessed.
				var fn = fn_object.fn || fn_object,
					maxArity = fn_object.maxArity || Infinity,
					minArity = fn_object.minArity || 0,
					dataType = fn_object.dataType || [ "number", "string" ],
					checkType = function (arg) {
						var rtn = false,
							d;
						if (dataType instanceof Array) {
							for (d = dataType.length - 1; (d + 1) && !rtn; d -= 1) {
								rtn = (typeof arg === dataType[d]);
							}
						} else if (typeof dataType === "string") {
							rtn = typeof arg === dataType;
						}
						return rtn;
					};

				return function (args) {
					var rtn = {},
						func_rtn,
						a,
						unpacked = [];

					if (args instanceof Array) {
						a = args.length;

						if (a > maxArity) {
							rtn.error = "too many arguments";
						} else if (a < minArity) {
							rtn.error = "too few arguments";
						}

						// Search for any one argument that goes against type, whilst unpacking.
						for (; a && checkType(unpacked[a - 1] = (args[a - 1].value || args[a - 1])); a -= 1); // no body

						// When a is falsy, the arguments are type-safe.
						if (!a) {
							func_rtn = fn(unpacked);
							if (typeof func_rtn === "object" && (func_rtn.hasOwnProperty("value") || func_rtn.hasOwnProperty("error"))) {
								rtn = func_rtn;
							} else {
								rtn.value = func_rtn;
							}
						} else {
							rtn.error = "The argument " + (args[a - 1].value || args[a - 1]) + " was the wrong type.";
						}
					} else {
						rtn.error = "Fault with Lijst. Arguments not passed as array.";
					}
					return rtn;
				}
			},

			separate_terms = function (input) {
				var str = input,
					arr = [],
					rst = "",
					rex = /(\s+)|(")|(\()|(\))|(.$)/g,
					begin_term = 0,
					end_term = 0,
					paren_level = 0,
					quote_level = false,
					rfn = function ($m, $1, $2, $3, $4, $5, offset, whole_string) {
						var out;
						if ($2 && !paren_level) {
							console.log(quote_level);
							quote_level = !quote_level;
							if (quote_level) {
								begin_term = offset;
							} else {
								end_term = offset + $m.length;
								out = whole_string.slice(begin_term, end_term);
								begin_term = end_term;
							}
						} else if ($3 && !quote_level) {
							paren_level += 1;
							if (!paren_level) {
								begin_term = offset;
							}
						} else if ($4 && !quote_level) {
							paren_level -= 1;
							if (!paren_level) {
								end_term = offset + $m.length;
								out = whole_string.slice(begin_term, end_term);
								begin_term = end_term;
							}
						} else if ($1 && !paren_level && !quote_level) {
							end_term = offset;
							out = whole_string.slice(begin_term, end_term);
							begin_term = end_term + $m.length;
						} else if ($5 && !quote_level) {
							end_term = whole_string.length;
							out = whole_string.slice(begin_term, end_term);
							begin_term = end_term + $m.length;
						}

						if (out) { arr.push(out); };
						return $m;
					};

				rst = str.replace(rex, rfn);
				return arr;
			},

			evaluate_term = function (term) {
				var rtn,
					arr,
					fun,
					arg = [],
					term = term[0];
				if (/\D/g.test(term)) {
					if (/^\(.*\)$/.test(term)) {
						if (term.slice(1, -1)) {
							arr = separate_terms(term.slice(1, -1));
							fun = arr.shift();
							while (arr.length) {
								arg.push(evaluate_term(arr.splice(0, 1)));
							}
							if (lisp_fns.hasOwnProperty(fun)) {
								rtn = lisp_fns[fun](arg);
							} else {
								// TODO: What if there is no such function?
							}
						} else {
							// If parentheses are empty.
							rtn = "NIL";
						}
					} else if (/^".*"$/g.test(term)) {
						console.log(term);
						rtn = term;
					}
				} else {
					rtn = +term;
				}
				return rtn;
			},

			// Top-level processing of input.
			process_input = function (input, callback_each_term) {
				var rtn,
					arr = separate_terms(input),
					rst;

				while (arr.length) {
					// Extract first term from array and evaluate.
					rst = evaluate_term(arr.splice(0, 1));
					// Do something with the input and results.
					callback_each_term(input, print_result(rst));
					// Reset the input. We have already done something with it once.
					input = "";
				}

				return rtn;
			},

			print_result = function (result) {
				var rtn;
				if (result.hasOwnProperty("value")) {
					if (typeof result.value === "number") {
						rtn = "" + result.value;
					} else {
						rtn = result.value;
					}
				} else if (result.hasOwnProperty("error")) {
					rtn = "*** - " + result.error;
				} else {
					rtn = "Error at printing stage. No value or processing error found.";
				}
				return rtn;
			},

			f;

		// Wrap predefined lisp functions in error-checking function.
		for (f in lisp_fns) {
			if (lisp_fns.hasOwnProperty(f)) {
				lisp_fns[f] = wrap_function(lisp_fns[f]);
			}
		}

		evaluate_term = wrap_function(evaluate_term);

		initialise_callback();

		return {
			process_input: process_input
		};

	};

// Node JS compatibility
if (typeof exports !== "undefined") {
	exports.init = init;
}<|endoftext|>


<commit_before>function(head, req) {
  var row;
  var headerNeeded = true;
  var pairName = [];
  var pairFirstName = "";
  var pairLastName = "";
  var training = "";
  var paid = "";
  var conflict = "";
  var medNotesExp = "";

  start({
    "headers": {
      "Content-Type": "text/csv",
      "Content-disposition": "attachment;filename=FlightInfo.csv"
     }
  });

  while(row = getRow()) {
    pairName = [];
    pairFirstName = "";
    pairLastName = "";
    training = "";
    paid = "";
    r = row.doc;
    if (r.type === "Veteran") {
      pairName = r.guardian.name.split(" ");
      conflict = (r.vet_type || "WWII");
      medNotesExp = (r.medical.review || "");
    } else if (r.type === "Guardian") {
      if ((r.veteran) && (r.veteran.pairings) && (r.veteran.pairings.length > 0)) {
        pairName = r.veteran.pairings[0].name.split(" ");
      }

      // Training status
      if (r.flight.training) {
        if (r.flight.training_complete) {
          training = "* ";
        }
        training += r.flight.training;
      }
      // Paid status
      if (r.flight.paid) {
        paid = "Y";
      } else {
        paid = "N";
      }
      medNotesExp = (r.medical.experience || "");
    }

    // Split the pair name.
    if (pairName.length > 1) {
      pairFirstName = pairName.slice(0,1);
      pairLastName = pairName.slice(1).join(" ");
    } else if (pairName.length === 1) {
      pairLastName = pairName.slice(0,1);
    }

    if (!r.apparel) {
      r.apparel = {};
    }

    result = {
        flight_id:                     r.flight.id,
        type:                          r.type,
        app_date:                      r.app_date,
        conflict:                      conflict,
        first_name:                    r.name.first,
        middle_name:                   r.name.middle,
        last_name:                     r.name.last,
        nick_name:                     r.name.nickname,
        addr_street:                   r.address.street,
        addr_city:                     r.address.city,
        addr_county:                   r.address.county,
        addr_state:                    r.address.state,
        addr_zip:                      r.address.zip,
        addr_phone_day:                r.address.phone_day,
        addr_phone_eve:                r.address.phone_eve,
        addr_phone_mbl:                r.address.phone_mbl,
        addr_email:                    r.address.email,
        birth_date:                    r.birth_date,
        gender:                        r.gender,
        shirt_size:                    r.shirt.size,
        flight_status:                 r.flight.status,
        flight_status_note:            r.flight.status_note,
        flight_confirmed_date:         r.flight.confirmed_date,
        flight_confirmed_by:           r.flight.confirmed_by,
        flight_training:               training,
        flight_training_notes:         r.flight.training_notes,
        flight_paid:                   paid,
        flight_seat:                   r.flight.seat,
        flight_group:                  (r.flight.group || ""),
        flight_waiver:                 (r.flight.waiver || ""),
        flight_books_ordered:          (r.flight.booksOrdered || ""),
        media_ok:                      (r.media_ok || ""),
        medical_release:               (r.medical.release || ""),
        medical_level:                 (r.medical.level || ""),
        medical_limitations:           (r.medical.limitations || ""),
        medical_notes_exp:             medNotesExp,
        medical_uses_cane:             (r.medical.usesCane || 0),
        medical_uses_walker:           (r.medical.usesWalker || 0),
        medical_uses_wheelchair:       (r.medical.usesWheelchair || 0),
        medical_uses_scooter:          (r.medical.usesScooter || 0),
        medical_is_wheelchair_bound:   (r.medical.isWheelchairBound || 0),
        medical_requires_oxygen:       (r.medical.requiresOxygen || 0),
        service_branch:                ((r.service && r.service.branch) || ""),
        service_rank:                  ((r.service && r.service.rank) || ""),
        mail_call_name:                ((r.alt_contact && r.alt_contact.name) || ""),
        mail_call_phone:               ((r.alt_contact && r.alt_contact.address.phone) || ""),
        mail_call_email:               ((r.alt_contact && r.alt_contact.address.email) || ""),
        pair_first_name:               pairFirstName,
        pair_last_name:                pairLastName,
        flight_bus:                    r.flight.bus.replace("Alpha", "Alpha ").replace("Bravo", "Bravo "),
        apparel_item:                  (r.apparel.item || ""),
        apparel_date:                  (r.apparel.date || ""),
        apparel_delivery:              (r.apparel.delivery || ""),
        apparel_notes:                 (r.apparel.notes || ""),
        apparel_by:                    (r.apparel.by || ""),
        id:                            r._id,
        rev:                           r._rev,
        created_at:                    r.metadata.created_at,
        updated_at:                    r.metadata.updated_at,
        created_by:                    r.metadata.created_by,
        updated_by:                    r.metadata.updated_by
    }

    if (headerNeeded) {
      for (key in result) {
        send("\"");
        send(key);
        send("\",");
      }
      send("\n");
      headerNeeded = false;
    }

    for (key in result) {
      if (result[key]) {
        if (result[key].length > 0) {
          send("\"");
          send(result[key]);
          send("\"");
        } else {
          if (!isNaN(result[key])) {
            send(result[key].toString());
          }
        }
      }
      send(",");
    }
    send("\n");
  }
}

<commit_msg>Add new call center fields to flight export.<commit_after>function(head, req) {
  var row;
  var headerNeeded = true;
  var pairName = [];
  var pairFirstName = "";
  var pairLastName = "";
  var training = "";
  var paid = "";
  var conflict = "";
  var medNotesExp = "";

  start({
    "headers": {
      "Content-Type": "text/csv",
      "Content-disposition": "attachment;filename=FlightInfo.csv"
     }
  });

  while(row = getRow()) {
    pairName = [];
    pairFirstName = "";
    pairLastName = "";
    training = "";
    paid = "";
    r = row.doc;
    if (r.type === "Veteran") {
      pairName = r.guardian.name.split(" ");
      conflict = (r.vet_type || "WWII");
      medNotesExp = (r.medical.review || "");
    } else if (r.type === "Guardian") {
      if ((r.veteran) && (r.veteran.pairings) && (r.veteran.pairings.length > 0)) {
        pairName = r.veteran.pairings[0].name.split(" ");
      }

      // Training status
      if (r.flight.training) {
        if (r.flight.training_complete) {
          training = "* ";
        }
        training += r.flight.training;
      }
      // Paid status
      if (r.flight.paid) {
        paid = "Y";
      } else {
        paid = "N";
      }
      medNotesExp = (r.medical.experience || "");
    }

    // Split the pair name.
    if (pairName.length > 1) {
      pairFirstName = pairName.slice(0,1);
      pairLastName = pairName.slice(1).join(" ");
    } else if (pairName.length === 1) {
      pairLastName = pairName.slice(0,1);
    }

    if (!r.apparel) {
      r.apparel = {};
    }

    if (!r.call) {
      r.call = {};
    }

    result = {
        flight_id:                     r.flight.id,
        type:                          r.type,
        app_date:                      r.app_date,
        conflict:                      conflict,
        first_name:                    r.name.first,
        middle_name:                   r.name.middle,
        last_name:                     r.name.last,
        nick_name:                     r.name.nickname,
        addr_street:                   r.address.street,
        addr_city:                     r.address.city,
        addr_county:                   r.address.county,
        addr_state:                    r.address.state,
        addr_zip:                      r.address.zip,
        addr_phone_day:                r.address.phone_day,
        addr_phone_eve:                r.address.phone_eve,
        addr_phone_mbl:                r.address.phone_mbl,
        addr_email:                    r.address.email,
        birth_date:                    r.birth_date,
        gender:                        r.gender,
        shirt_size:                    r.shirt.size,
        call_assigned_to:              (r.call.assigned_to || ""),
        call_fm_number:                (r.call.fm_number || ""),
        call_mail_sent:                (r.call.mail_sent  || false),
        call_email_sent:               (r.call.email_sent || false),
        flight_status:                 r.flight.status,
        flight_status_note:            r.flight.status_note,
        flight_confirmed_date:         r.flight.confirmed_date,
        flight_confirmed_by:           r.flight.confirmed_by,
        flight_training:               training,
        flight_training_notes:         r.flight.training_notes,
        flight_paid:                   paid,
        flight_seat:                   r.flight.seat,
        flight_group:                  (r.flight.group || ""),
        flight_waiver:                 (r.flight.waiver || ""),
        flight_books_ordered:          (r.flight.booksOrdered || ""),
        media_ok:                      (r.media_ok || ""),
        medical_release:               (r.medical.release || ""),
        medical_level:                 (r.medical.level || ""),
        medical_limitations:           (r.medical.limitations || ""),
        medical_notes_exp:             medNotesExp,
        medical_uses_cane:             (r.medical.usesCane || 0),
        medical_uses_walker:           (r.medical.usesWalker || 0),
        medical_uses_wheelchair:       (r.medical.usesWheelchair || 0),
        medical_uses_scooter:          (r.medical.usesScooter || 0),
        medical_is_wheelchair_bound:   (r.medical.isWheelchairBound || 0),
        medical_requires_oxygen:       (r.medical.requiresOxygen || 0),
        service_branch:                ((r.service && r.service.branch) || ""),
        service_rank:                  ((r.service && r.service.rank) || ""),
        mail_call_name:                ((r.alt_contact && r.alt_contact.name) || ""),
        mail_call_phone:               ((r.alt_contact && r.alt_contact.address.phone) || ""),
        mail_call_email:               ((r.alt_contact && r.alt_contact.address.email) || ""),
        pair_first_name:               pairFirstName,
        pair_last_name:                pairLastName,
        flight_bus:                    r.flight.bus.replace("Alpha", "Alpha ").replace("Bravo", "Bravo "),
        apparel_item:                  (r.apparel.item || ""),
        apparel_date:                  (r.apparel.date || ""),
        apparel_delivery:              (r.apparel.delivery || ""),
        apparel_notes:                 (r.apparel.notes || ""),
        apparel_by:                    (r.apparel.by || ""),
        id:                            r._id,
        rev:                           r._rev,
        created_at:                    r.metadata.created_at,
        updated_at:                    r.metadata.updated_at,
        created_by:                    r.metadata.created_by,
        updated_by:                    r.metadata.updated_by
    }

    if (headerNeeded) {
      for (key in result) {
        send("\"");
        send(key);
        send("\",");
      }
      send("\n");
      headerNeeded = false;
    }

    for (key in result) {
      if (result[key]) {
        if (result[key].length > 0) {
          send("\"");
          send(result[key]);
          send("\"");
        } else {
          if (!isNaN(result[key])) {
            send(result[key].toString());
          }
        }
      }
      send(",");
    }
    send("\n");
  }
}

<|endoftext|>


<commit_before>exports.description = 'Displays general help info or info about a specific command.';

exports.usage = '[command]';

exports.options = {
    command: {
        noName: true,
        description: 'Get more information about a specific command.'
    }
};

exports.invoke = function (shell, options) {
    var cmdNames = [];

    // Populate cmdNames with all command module names and sort the array alphabetically.
    for (var key in shell.cmds) {
        var cmd = shell.cmds[key];
        if (cmd && cmd.access(shell, key))
            cmdNames.push(key);
    }
    cmdNames.sort();

    shell.log();

    // If no command was passed in as an argument to the help command then display the generic help menu listing all available commands.
    if (!options.command) {

        // Calculate the length of the largest command name for formatting purposes.
        var maxLength = 0;
        for (var index = 0; index < cmdNames.length; index++) {
            var cmdName = cmdNames[index];
            maxLength = cmdName.length > maxLength ? cmdName.length : maxLength;
        }

        // Iterate over all command modules and add a line of text with the command name and description.
        var inverted = false;
        for (var index = 0; index < cmdNames.length; index++) {
            var cmdName = cmdNames[index],
                cmd = shell.cmds[cmdName],
                helpStr = cmdName;
            if (cmd.description) {
                helpStr += new Array((maxLength - cmdName.length) + 7).join(' ');
                helpStr += cmd.description;
            }

            // If the command is not hidden then add the line.
            // If there are 5 commands or less then type the lines character by character.
            // If there are more than 5 commands then do not type them out as it takes too long and the effect isn't worth the wait.
            if (!cmd.hidden) {
                var lineOptions = { dontType: cmdNames.length > 5, inverted: inverted };
                inverted = !inverted;
                shell.log(helpStr, lineOptions);
            }
        }
        shell.log();
    }
    // If a command was passed in as an argument to the help command then display more specific help information for the specified command.
    else {
        var cmd = shell.cmds[options.command];
        if (!cmd)
            shell.error(options.command + ' is not a valid command name.');
        else {

            var firstLine = options.command;
            // If a "usage key" is specified then display it.
            if (cmd.usage)
                firstLine += ' ' + cmd.usage;
            shell.log(firstLine, { bold: true });
            shell.log();

            // Display the command's description if it has one.
            if (cmd.description) {
                shell.log(cmd.description);
                shell.log();
            }

            // If the command defines options that it recognizes then iterate over those and display information about them.
            if (cmd.options) {
                var strs = [],
                    maxLength = 0;
                for (var key in cmd.options) {
                    var option = cmd.options[key];
                    if (!option.hidden) {
                        var optionStr = (key.length > 1 ? '--' : '-') + key;
                        if (option.aliases) {
                            option.aliases.forEach(function (alias) {
                                optionStr += ',' + (alias.length > 1 ? '--' : '-') + alias;
                            });
                        }
                        strs.push({ option: option, str: optionStr});
                        maxLength = optionStr.length > maxLength ? optionStr.length : maxLength;
                    }
                }
                if (strs.length > 0) {
                    shell.log('Options:');
                    shell.log();
                    for (var index in strs) {
                        var option = strs[index].option,
                            optionStr = strs[index].str;
                        if (option.description) {
                            optionStr += new Array((maxLength - optionStr.length) + 5).join(' ');
                            optionStr += option.description;
                        }
                        shell.log(optionStr, { dontType: true });
                    }
                    shell.log();
                }
            }
        }
    }
};<commit_msg>Fixed bug with string alias lists breaking the help command.<commit_after>exports.description = 'Displays general help info or info about a specific command.';

exports.usage = '[command]';

exports.options = {
    command: {
        noName: true,
        description: 'Get more information about a specific command.'
    }
};

exports.invoke = function (shell, options) {
    var cmdNames = [];

    // Populate cmdNames with all command module names and sort the array alphabetically.
    for (var key in shell.cmds) {
        var cmd = shell.cmds[key];
        if (cmd && cmd.access(shell, key))
            cmdNames.push(key);
    }
    cmdNames.sort();

    shell.log();

    // If no command was passed in as an argument to the help command then display the generic help menu listing all available commands.
    if (!options.command) {

        // Calculate the length of the largest command name for formatting purposes.
        var maxLength = 0;
        for (var index = 0; index < cmdNames.length; index++) {
            var cmdName = cmdNames[index];
            maxLength = cmdName.length > maxLength ? cmdName.length : maxLength;
        }

        // Iterate over all command modules and add a line of text with the command name and description.
        var inverted = false;
        for (var index = 0; index < cmdNames.length; index++) {
            var cmdName = cmdNames[index],
                cmd = shell.cmds[cmdName],
                helpStr = cmdName;
            if (cmd.description) {
                helpStr += new Array((maxLength - cmdName.length) + 7).join(' ');
                helpStr += cmd.description;
            }

            // If the command is not hidden then add the line.
            // If there are 5 commands or less then type the lines character by character.
            // If there are more than 5 commands then do not type them out as it takes too long and the effect isn't worth the wait.
            if (!cmd.hidden) {
                var lineOptions = { dontType: cmdNames.length > 5, inverted: inverted };
                inverted = !inverted;
                shell.log(helpStr, lineOptions);
            }
        }
        shell.log();
    }
    // If a command was passed in as an argument to the help command then display more specific help information for the specified command.
    else {
        var cmd = shell.cmds[options.command];
        if (!cmd)
            shell.error(options.command + ' is not a valid command name.');
        else {

            var firstLine = options.command;
            // If a "usage key" is specified then display it.
            if (cmd.usage)
                firstLine += ' ' + cmd.usage;
            shell.log(firstLine, { bold: true });
            shell.log();

            // Display the command's description if it has one.
            if (cmd.description) {
                shell.log(cmd.description);
                shell.log();
            }

            // If the command defines options that it recognizes then iterate over those and display information about them.
            if (cmd.options) {
                var strs = [],
                    maxLength = 0;
                for (var key in cmd.options) {
                    var option = cmd.options[key];
                    if (!option.hidden) {
                        var optionStr = (key.length > 1 ? '--' : '-') + key;
                        if (option.aliases) {
                            var aliases = option.aliases;
                            if (typeof(aliases) === 'string')
                                aliases = aliases.toString().replace(/, /, ',').split(',').unique();
                            aliases.forEach(function (alias) {
                                optionStr += ',' + (alias.length > 1 ? '--' : '-') + alias;
                            });
                        }
                        strs.push({ option: option, str: optionStr});
                        maxLength = optionStr.length > maxLength ? optionStr.length : maxLength;
                    }
                }
                if (strs.length > 0) {
                    shell.log('Options:');
                    shell.log();
                    for (var index in strs) {
                        var option = strs[index].option,
                            optionStr = strs[index].str;
                        if (option.description) {
                            optionStr += new Array((maxLength - optionStr.length) + 5).join(' ');
                            optionStr += option.description;
                        }
                        shell.log(optionStr, { dontType: true });
                    }
                    shell.log();
                }
            }
        }
    }
};<|endoftext|>