<commit_before>(function ($) {
    $.fn.extend({
        expandoControl: function (getControllees, options) {
            if (typeof getControllees !== "function")
                return this;

            var _this = $(this);
            var __cookieName = "Exp";
            var settings = $.extend({
                path: "/",
                key: _this.selector,
                collapse: false,
                remember: true
            }, options);
            _this.each(function (index, element) {
                var controller = $(element);
                var glyph = $("");

                glyph.data("controllees", getControllees(controller));

                if (glyph.data("controllees").length === 0 || glyph.data("controllees").height() < 1) {
                    return;
                }

                if ((settings.remember && "closed" === $.orchard.setting(__cookieName, { key: settings.key + "-" + controller.text(), path: settings.path }))
                    || settings.collapse
                    || (controller.closest("li").hasClass("collapsed") && !(settings.remember && "open" === $.orchard.setting(__cookieName, { key: settings.key + "-" + controller.text(), path: settings.path })))) {
                    glyph.addClass("closed").data("controllees").hide();
                }
                else if (settings.collapse) {

                }

                glyph.click(function () {
                    var __this = $(this);

                    if (settings.remember && !settings.collapse) { // remembering closed state as true because that's not the default - doesn't make sense to remember if the controllees are always to be collapsed by default
                        // need to allow specified keys since these selectors could get *really* long
                        $.orchard.setting(__cookieName, !__this.hasClass("closed") ? "closed" : "open", { key: settings.key + "-" + controller.text(), path: settings.path });
                    }

                    if (__this.hasClass("closed") || __this.hasClass("closing")) {
                        __this.data("controllees").slideDown(300, function () { __this.removeClass("opening").removeClass("closed").addClass("open"); });
                        __this.addClass("opening");
                    }
                    else {
                        __this.data("controllees").slideUp(300, function () { __this.removeClass("closing").removeClass("open").addClass("closed"); });
                        __this.addClass("closing");
                    }

                    return false;
                });

                controller.prepend(glyph);
            });

            return this;
        }
    });

    $(".bulk-actions-auto select").change(function () {
        $(this).closest("form").find(".apply-bulk-actions-auto:first").click();
    });

    $("body").on("click", "[itemprop~='RemoveUrl']", function () {
        // don't show the confirm dialog if the link is also UnsafeUrl, as it will already be handled in base.js
        if ($(this).filter("[itemprop~='UnsafeUrl']").length == 1) {
            return false;
        }

        return confirm(confirmRemoveMessage);
    });

    $(".check-all").change(function () {
        $(this).parents("table.items").find(":checkbox").prop('checked', $(this).prop("checked"));
    });
})(jQuery);

/*
 console-shim 1.0.2
 https://github.com/kayahr/console-shim
 Copyright (C) 2011 Klaus Reimer <k@ailis.de>
 Licensed under the MIT license
 (See http://www.opensource.org/licenses/mit-license)
*/
function f() { return function () { } }
(function () {
    function c(a, l, b) { var c = Array.prototype.slice.call(arguments, 2); return function () { var b = c.concat(Array.prototype.slice.call(arguments, 0)); a.apply(l, b) } } window.console || (window.console = {}); var a = window.console; if (!a.log) if (window.log4javascript) { var b = log4javascript.getDefaultLogger(); a.log = c(b.info, b); a.debug = c(b.debug, b); a.info = c(b.info, b); a.warn = c(b.warn, b); a.error = c(b.error, b) } else a.log = f(); a.debug || (a.debug = a.log); a.info || (a.info = a.log); a.warn || (a.warn = a.log); a.error || (a.error = a.log);
    if (null != window.__consoleShimTest__ || eval("/*@cc_on @_jscript_version \x3c\x3d 9@*/")) b = function (d) { var b, e, c; d = Array.prototype.slice.call(arguments, 0); c = d.shift(); e = d.length; if (1 < e && !1 !== window.__consoleShimTest__) { "string" != typeof d[0] && (d.unshift("%o"), e += 1); for (b = (b = d[0].match(/%[a-z]/g)) ? b.length + 1 : 1; b < e; b += 1) d[0] += " %o" } Function.apply.call(c, a, d) }, a.log = c(b, window, a.log), a.debug = c(b, window, a.debug), a.info = c(b, window, a.info), a.warn = c(b, window, a.warn), a.error = c(b, window, a.error); a.assert || (a.assert =
    function () { var d = Array.prototype.slice.call(arguments, 0); d.shift() || (d[0] = "Assertion failed: " + d[0], a.error.apply(a, d)) }); a.dir || (a.dir = a.log); a.dirxml || (a.dirxml = a.log); a.exception || (a.exception = a.error); if (!a.time || !a.timeEnd) { var g = {}; a.time = function (a) { g[a] = (new Date).getTime() }; a.timeEnd = function (b) { var c = g[b]; c && (a.log(b + ": " + ((new Date).getTime() - c) + "ms"), delete g[b]) } } a.table || (a.table = function (b, c) {
        var e, g, j, h, k; if (b && b instanceof Array && b.length) {
            if (!c || !(c instanceof Array)) for (e in c =
            [], b[0]) b[0].hasOwnProperty(e) && c.push(e); e = 0; for (g = b.length; e < g; e += 1) { j = []; h = 0; for (k = c.length; h < k; h += 1) j.push(b[e][c[h]]); Function.apply.call(a.log, a, j) }
        }
    }); a.clear || (a.clear = f()); a.trace || (a.trace = f()); a.group || (a.group = f()); a.groupCollapsed || (a.groupCollapsed = f()); a.groupEnd || (a.groupEnd = f()); a.timeStamp || (a.timeStamp = f()); a.profile || (a.profile = f()); a.profileEnd || (a.profileEnd = f()); a.count || (a.count = f())
})();<commit_msg>Modified admin javascript for check all checkbox to ignore disabled checkboxes.<commit_after>(function ($) {
    $.fn.extend({
        expandoControl: function (getControllees, options) {
            if (typeof getControllees !== "function")
                return this;

            var _this = $(this);
            var __cookieName = "Exp";
            var settings = $.extend({
                path: "/",
                key: _this.selector,
                collapse: false,
                remember: true
            }, options);
            _this.each(function (index, element) {
                var controller = $(element);
                var glyph = $("");

                glyph.data("controllees", getControllees(controller));

                if (glyph.data("controllees").length === 0 || glyph.data("controllees").height() < 1) {
                    return;
                }

                if ((settings.remember && "closed" === $.orchard.setting(__cookieName, { key: settings.key + "-" + controller.text(), path: settings.path }))
                    || settings.collapse
                    || (controller.closest("li").hasClass("collapsed") && !(settings.remember && "open" === $.orchard.setting(__cookieName, { key: settings.key + "-" + controller.text(), path: settings.path })))) {
                    glyph.addClass("closed").data("controllees").hide();
                }
                else if (settings.collapse) {

                }

                glyph.click(function () {
                    var __this = $(this);

                    if (settings.remember && !settings.collapse) { // remembering closed state as true because that's not the default - doesn't make sense to remember if the controllees are always to be collapsed by default
                        // need to allow specified keys since these selectors could get *really* long
                        $.orchard.setting(__cookieName, !__this.hasClass("closed") ? "closed" : "open", { key: settings.key + "-" + controller.text(), path: settings.path });
                    }

                    if (__this.hasClass("closed") || __this.hasClass("closing")) {
                        __this.data("controllees").slideDown(300, function () { __this.removeClass("opening").removeClass("closed").addClass("open"); });
                        __this.addClass("opening");
                    }
                    else {
                        __this.data("controllees").slideUp(300, function () { __this.removeClass("closing").removeClass("open").addClass("closed"); });
                        __this.addClass("closing");
                    }

                    return false;
                });

                controller.prepend(glyph);
            });

            return this;
        }
    });

    $(".bulk-actions-auto select").change(function () {
        $(this).closest("form").find(".apply-bulk-actions-auto:first").click();
    });

    $("body").on("click", "[itemprop~='RemoveUrl']", function () {
        // don't show the confirm dialog if the link is also UnsafeUrl, as it will already be handled in base.js
        if ($(this).filter("[itemprop~='UnsafeUrl']").length == 1) {
            return false;
        }

        return confirm(confirmRemoveMessage);
    });

    $(".check-all").change(function () {
        $(this).parents("table.items").find(":checkbox:not(:disabled)").prop('checked', $(this).prop("checked"));
    });
})(jQuery);

/*
 console-shim 1.0.2
 https://github.com/kayahr/console-shim
 Copyright (C) 2011 Klaus Reimer <k@ailis.de>
 Licensed under the MIT license
 (See http://www.opensource.org/licenses/mit-license)
*/
function f() { return function () { } }
(function () {
    function c(a, l, b) { var c = Array.prototype.slice.call(arguments, 2); return function () { var b = c.concat(Array.prototype.slice.call(arguments, 0)); a.apply(l, b) } } window.console || (window.console = {}); var a = window.console; if (!a.log) if (window.log4javascript) { var b = log4javascript.getDefaultLogger(); a.log = c(b.info, b); a.debug = c(b.debug, b); a.info = c(b.info, b); a.warn = c(b.warn, b); a.error = c(b.error, b) } else a.log = f(); a.debug || (a.debug = a.log); a.info || (a.info = a.log); a.warn || (a.warn = a.log); a.error || (a.error = a.log);
    if (null != window.__consoleShimTest__ || eval("/*@cc_on @_jscript_version \x3c\x3d 9@*/")) b = function (d) { var b, e, c; d = Array.prototype.slice.call(arguments, 0); c = d.shift(); e = d.length; if (1 < e && !1 !== window.__consoleShimTest__) { "string" != typeof d[0] && (d.unshift("%o"), e += 1); for (b = (b = d[0].match(/%[a-z]/g)) ? b.length + 1 : 1; b < e; b += 1) d[0] += " %o" } Function.apply.call(c, a, d) }, a.log = c(b, window, a.log), a.debug = c(b, window, a.debug), a.info = c(b, window, a.info), a.warn = c(b, window, a.warn), a.error = c(b, window, a.error); a.assert || (a.assert =
    function () { var d = Array.prototype.slice.call(arguments, 0); d.shift() || (d[0] = "Assertion failed: " + d[0], a.error.apply(a, d)) }); a.dir || (a.dir = a.log); a.dirxml || (a.dirxml = a.log); a.exception || (a.exception = a.error); if (!a.time || !a.timeEnd) { var g = {}; a.time = function (a) { g[a] = (new Date).getTime() }; a.timeEnd = function (b) { var c = g[b]; c && (a.log(b + ": " + ((new Date).getTime() - c) + "ms"), delete g[b]) } } a.table || (a.table = function (b, c) {
        var e, g, j, h, k; if (b && b instanceof Array && b.length) {
            if (!c || !(c instanceof Array)) for (e in c =
            [], b[0]) b[0].hasOwnProperty(e) && c.push(e); e = 0; for (g = b.length; e < g; e += 1) { j = []; h = 0; for (k = c.length; h < k; h += 1) j.push(b[e][c[h]]); Function.apply.call(a.log, a, j) }
        }
    }); a.clear || (a.clear = f()); a.trace || (a.trace = f()); a.group || (a.group = f()); a.groupCollapsed || (a.groupCollapsed = f()); a.groupEnd || (a.groupEnd = f()); a.timeStamp || (a.timeStamp = f()); a.profile || (a.profile = f()); a.profileEnd || (a.profileEnd = f()); a.count || (a.count = f())
})();<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();
var fs = require('fs');
var multer = require('multer');
var storage = multer.diskStorage({
  destination: function (req, file, callback) {
    callback(null, 'uploads/')
  },
  filename: function (req, file, callback) {
    callback(null, Date.now() + '.zip') //Appending .zip
  }
})
var upload = multer({ storage: storage });

/* GET a playlist by keyword*/
router.post('/with-words', function(req, res, next) {
  var words = req.body.words;
  var access_token = req.body.access_token;
  var user_id = req.body.user_id;

  api.createPlaylistFromWords(words, access_token, user_id, function(playlistID) {
    res.send(playlistID);
  });
});

router.post('/with-images',  upload.single('images_file'), function(req, res, next) {
  var access_token = req.body.access_token;
  var user_id = req.body.user_id

  var images_file = fs.createReadStream(req.file.path);
  if(!images_file) {
    return next({ error:'The photo album zip file is not found.  Please try again.', code:404});
  }
  else {
    api.createPlaylistFromImages(images_file, access_token, user_id, function(playlistID) {
      res.send(playlistID);
    });
  }
});

module.exports = router;
<commit_msg>forgot to include api in build-playlist routes<commit_after>var express = require('express');
var router = express.Router();
var api = require('../lib/api');
var fs = require('fs');
var multer = require('multer');
var storage = multer.diskStorage({
  destination: function (req, file, callback) {
    callback(null, 'uploads/')
  },
  filename: function (req, file, callback) {
    callback(null, Date.now() + '.zip') //Appending .zip
  }
})
var upload = multer({ storage: storage });

/* GET a playlist by keyword*/
router.post('/with-words', function(req, res, next) {
  var words = req.body.words;
  var access_token = req.body.access_token;
  var user_id = req.body.user_id;

  api.createPlaylistFromWords(words, access_token, user_id, function(playlistID) {
    res.send(playlistID);
  });
});

router.post('/with-images',  upload.single('images_file'), function(req, res, next) {
  var access_token = req.body.access_token;
  var user_id = req.body.user_id

  var images_file = fs.createReadStream(req.file.path);
  if(!images_file) {
    return next({ error:'The photo album zip file is not found.  Please try again.', code:404});
  }
  else {
    api.createPlaylistFromImages(images_file, access_token, user_id, function(playlistID) {
      res.send(playlistID);
    });
  }
});

module.exports = router;
<|endoftext|>


<commit_before>const data = [
            { id: 'isbn', name: 'ISBN' },
            { id: 'issn', name: 'ISSN' },
            { id: '0003', name: 'Standard Technical Report number' },
            { id: '0004', name: 'Publisher Number' },
            { id: '0005', name: 'CODEN' },
            { id: '0006', name: 'Control Number (001)' },
            { id: '0007', name: 'GPO Item Number' },
            { id: 'lccn', name: 'LCCN' },
            { id: '0009', name: 'System Control Number' },
            { id: '0010', name: 'Other Standard Identifier' },
            { id: 'asin', name: 'ASIN' },
            { id: 'UkMac', name: 'UkMac' },
            { id: 'StEdNL', name: 'StEdNL' },
            { id: 'bnb', name: 'BNB' },
            { id: '0015', name: 'OCLC' },
];

const identifierTypes = {

  selectOptions: selected => data.map(
    it => ({
      label: it.name,
      value: it.id,
      selected: it.id === selected,
    })),

  typeById: id => data.find(it => it.id === id),
};

export default identifierTypes;
<commit_msg>Fix typo in identifier type code.<commit_after>const data = [
            { id: 'isbn', name: 'ISBN' },
            { id: 'issn', name: 'ISSN' },
            { id: '0003', name: 'Standard Technical Report number' },
            { id: '0004', name: 'Publisher Number' },
            { id: '0005', name: 'CODEN' },
            { id: '0006', name: 'Control Number (001)' },
            { id: '0007', name: 'GPO Item Number' },
            { id: 'lccn', name: 'LCCN' },
            { id: '0009', name: 'System Control Number' },
            { id: '0010', name: 'Other Standard Identifier' },
            { id: 'asin', name: 'ASIN' },
            { id: 'UkMaC', name: 'UkMac' },
            { id: 'StEdNL', name: 'StEdNL' },
            { id: 'bnb', name: 'BNB' },
            { id: '0015', name: 'OCLC' },
];

const identifierTypes = {

  selectOptions: selected => data.map(
    it => ({
      label: it.name,
      value: it.id,
      selected: it.id === selected,
    })),

  typeById: id => data.find(it => it.id === id),
};

export default identifierTypes;
<|endoftext|>


<commit_before>var args = require('system').args;
var page = require('webpage').create();

var NUM_APPS = 100;
var OUTDIR = './captures';
var TOP_URL =  'https://play.google.com/store/apps/collection/topselling_free';

function valueOf(argument) {
    return argument.split('=')[1];
}

if(args.length >= 1) {
    args.forEach(function(arg, i) {
       if(arg.match(/^--num-apps=/)) {
           NUM_APPS = valueOf(arg);
       } else if(arg.match(/^--output-dir=/)) {
            OUTDIR = valueOf(arg);
       } else if(arg.match(/^--top-url=/)) {
           TOP_URL = valueOf(arg);
       }
    });
}

// Fake out our user agent, we're Chrome 28 now
page.settings.userAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36";

page.viewportSize = { width: 1024, height: 768 };
page.clipRect = { top: 0, left: 0, width: 1024, height: 768 };

page.onConsoleMessage = function(msg) {
    console.log("CONSOLE>", msg);
};

page.onResourceRequested = function(request) {
    console.log('REQUEST ' + request.url);
};

page.open(TOP_URL, function(status) {

    if(status !== 'success') {
        console.log('ohh boo', status);
        phantom.exit();
    }

    window.setInterval(function() {

        var links = page.evaluate(function() {

            var list = document.querySelectorAll('a');
            var out = [];

            for(var i = 0; i < list.length; i++) {
                var link = list[i].href;
                out.push(link);
            }

            return out;

        });

        var numLinks = links.length;

        console.log('num links', numLinks);

        var appLinks = Array.prototype.slice.call(links).filter(filterAppLink);
        var appsURLs = [];
        appLinks.forEach(function(link) {
            if(appsURLs.indexOf(link) === -1) {
                appsURLs.push(link);
            }
        });

        console.log('have', appsURLs.length);

        if(appsURLs.length >= NUM_APPS) {
            console.log('HAVE', appsURLs.length, 'app URLs');

            var fs = require('fs');
            fs.write(OUTDIR + '/appsURLs.json', JSON.stringify(appsURLs, null, 4));

            phantom.exit();
        }

        // This is so incredibly convoluted...
        var actualScroll = page.evaluate(function() {

            var currScroll = window.document.body.scrollTop;
            var newScroll = currScroll + 800;
            console.log(currScroll, '=>', newScroll);
            window.document.body.scrollTop = newScroll;
            // window.document.body.scrollTop = document.body.scrollHeight;
            console.log('actual?', window.document.body.scrollTop);

            if(window.document.body.scrollTop < newScroll) {
                // scrolling is not enough, sometimes
                var more = window.document.getElementById('show-more-button');
                more.click();
                console.log('MOAAAAR');
            }

            return window.document.body.scrollTop;
        });

        page.scrollPosition = { top: actualScroll, left: 0 };
        page.render(OUTDIR + '/' + Date.now() + '-' + actualScroll + '.png');

    }, 5000 + Math.random() * 10);
});

function getQuery(url) {

    var query = {};
    if(url.indexOf('?') === -1) {
        return query;
    }

    var parts = url.split('?');

    if(parts.length > 1) {
        var queryStr = parts[1];

        var pairsStr = queryStr.split('&');

        pairsStr.forEach(function(pairStr) {
            var pair = pairStr.split('=');
            var key = pair[0];
            var value = pair.length > 1 ? pair[1] : true;

            query[key] = value;
        });
    }

    return query;

}

function filterAppLink(link) {

    var linksRe = /^https:\/\/play\.google\.com\/store\/apps\/details/;
    var query = getQuery(link);
    var match = linksRe.exec(link);

    if(match && query.id) {

        return true;
    }

    return false;

}

<commit_msg>Sometimes you need to give up!<commit_after>var args = require('system').args;
var page = require('webpage').create();

var NUM_APPS = 100;
var OUTDIR = './captures';
var TOP_URL =  'https://play.google.com/store/apps/collection/topselling_free';

function valueOf(argument) {
    return argument.split('=')[1];
}

if(args.length >= 1) {
    args.forEach(function(arg, i) {
       if(arg.match(/^--num-apps=/)) {
           NUM_APPS = valueOf(arg);
       } else if(arg.match(/^--output-dir=/)) {
            OUTDIR = valueOf(arg);
       } else if(arg.match(/^--top-url=/)) {
           TOP_URL = valueOf(arg);
       }
    });
}

console.log('using out dir', OUTDIR);
var OUTFILE = OUTDIR + '/appsURLs.json';
console.log('output', OUTFILE);

// Fake out our user agent, we're Chrome 28 now
page.settings.userAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36";

page.viewportSize = { width: 1024, height: 768 };
page.clipRect = { top: 0, left: 0, width: 1024, height: 768 };

page.onConsoleMessage = function(msg) {
    console.log("CONSOLE>", msg);
};

page.onResourceRequested = function(request) {
    console.log('REQUEST ' + request.url);
};

page.open(TOP_URL, function(status) {

    if(status !== 'success') {
        console.log('ohh boo', status);
        phantom.exit();
    }

    var scrollAttempts = 0;
    var previousScroll = 0;

    window.setInterval(function() {

        var links = page.evaluate(function() {

            var list = document.querySelectorAll('a');
            var out = [];

            for(var i = 0; i < list.length; i++) {
                var link = list[i].href;
                out.push(link);
            }

            return out;

        });

        var numLinks = links.length;

        console.log('num links', numLinks);

        var appLinks = Array.prototype.slice.call(links).filter(filterAppLink);
        var appsURLs = [];
        appLinks.forEach(function(link) {
            if(appsURLs.indexOf(link) === -1) {
                appsURLs.push(link);
            }
        });

        console.log('have', appsURLs.length);

        if(appsURLs.length >= NUM_APPS || scrollAttempts > 5) {
            console.log('HAVE', appsURLs.length, 'app URLs');

            if(appsURLs.length < NUM_APPS) {
                console.log('we might have given up :-/');
            }

            var fs = require('fs');
            fs.write(OUTFILE, JSON.stringify(appsURLs, null, 4));

            phantom.exit();
        }

        // This is so incredibly convoluted...
        var actualScroll = page.evaluate(function() {

            var currScroll = window.document.body.scrollTop;
            var newScroll = currScroll + 800;
            console.log(currScroll, '=>', newScroll);
            window.document.body.scrollTop = newScroll;
            // window.document.body.scrollTop = document.body.scrollHeight;
            console.log('actual?', window.document.body.scrollTop);

            if(window.document.body.scrollTop < newScroll) {
                // scrolling is not enough, sometimes
                var more = window.document.getElementById('show-more-button');
                if(more) {
                    more.click();
                }
                console.log('MOAAAAR');
            }

            return window.document.body.scrollTop;

        });

        if(previousScroll === actualScroll) {
            console.log('another attempt', scrollAttempts, previousScroll, actualScroll);
            scrollAttempts++;
        } else {
            scrollAttempts = 0;
        }

        previousScroll = actualScroll;

        page.scrollPosition = { top: actualScroll, left: 0 };
        //page.render(OUTDIR + '/' + Date.now() + '-' + actualScroll + '.png');

    }, 5000 + Math.random() * 10);
});

function getQuery(url) {

    var query = {};
    if(url.indexOf('?') === -1) {
        return query;
    }

    var parts = url.split('?');

    if(parts.length > 1) {
        var queryStr = parts[1];

        var pairsStr = queryStr.split('&');

        pairsStr.forEach(function(pairStr) {
            var pair = pairStr.split('=');
            var key = pair[0];
            var value = pair.length > 1 ? pair[1] : true;

            query[key] = value;
        });
    }

    return query;

}

function filterAppLink(link) {

    var linksRe = /^https:\/\/play\.google\.com\/store\/apps\/details/;
    var query = getQuery(link);
    var match = linksRe.exec(link);

    if(match && query.id) {

        return true;
    }

    return false;

}

<|endoftext|>


<commit_before>var expect = require('chai').expect
var _ = require('../src/utils')

describe('utils', function () {

  describe('serializeMap', function () {
    var map = {
      name: 'John',
      get: function () { return this.name }
    }

    it('should map the name property', function () {
      expect(_.serializeMap(map).name).to.be.equal('John')
    })

    it('should serialize into string the fn method property', function () {
      var newMap = _.serializeMap(map)
      expect(newMap.get).to.be.empty
      expect(newMap.$$fn$$get).to.be.a('string')
    })
  })

  describe('fnName', function () {
    var namedFn = function Name() {}
    var unnamedFn = function () {}

    it('should return the function name', function () {
      expect(_.fnName(namedFn)).to.be.equal('Name')
    })

    it('should return an empty function name', function () {
      expect(_.fnName(unnamedFn)).to.be.equal('')
    })
  })

})
<commit_msg>feat(test): add util tests<commit_after>var expect = require('chai').expect
var _ = require('../src/utils')

describe('utils', function () {

  describe('isArr', function () {
    it('should be an array', function () {
      expect(_.isArr([])).to.be.true
      expect(_.isArr(new Array)).to.be.true
    })

    it('should not be an array', function () {
      expect(_.isArr({})).to.be.false
      expect(_.isArr(undefined)).to.be.false
      expect(_.isArr(null)).to.be.false
      expect(_.isArr('')).to.be.false
      expect(_.isArr(new Date)).to.be.false
      expect(_.isArr(10)).to.be.false
    })
  })

  describe('isObj', function () {
    it('should be an object', function () {
      expect(_.isObj({})).to.be.true
      expect(_.isObj(new Object)).to.be.true
    })

    it('should not be an object', function () {
      expect(_.isObj([])).to.be.false
      expect(_.isObj(undefined)).to.be.false
      expect(_.isObj(null)).to.be.false
      expect(_.isObj('')).to.be.false
      expect(_.isObj(new Date)).to.be.false
      expect(_.isObj(10)).to.be.false
    })
  })

  describe('isFn', function () {
    it('should be a function', function () {
      expect(_.isFn(function () {})).to.be.true
      expect(_.isFn(new Function)).to.be.true
    })

    it('should not be a function', function () {
      expect(_.isFn([])).to.be.false
      expect(_.isFn({})).to.be.false
      expect(_.isFn(undefined)).to.be.false
      expect(_.isFn(null)).to.be.false
      expect(_.isFn('')).to.be.false
      expect(_.isFn(new Date)).to.be.false
      expect(_.isFn(10)).to.be.false
    })
  })

  describe('serializeMap', function () {
    var map = {
      name: 'John',
      get: function () { return this.name }
    }

    it('should map the name property', function () {
      expect(_.serializeMap(map).name).to.be.equal('John')
    })

    it('should serialize into string the fn method property', function () {
      var newMap = _.serializeMap(map)
      expect(newMap.get).to.be.empty
      expect(newMap.$$fn$$get).to.be.a('string')
    })
  })

  describe('fnName', function () {
    var namedFn = function Name() {}
    var unnamedFn = function () {}

    it('should return the function name', function () {
      expect(_.fnName(namedFn)).to.be.equal('Name')
    })

    it('should return an empty function name', function () {
      expect(_.fnName(unnamedFn)).to.be.equal('')
    })
  })

})
<|endoftext|>


<commit_before>/*global app, client*/
"use strict";

var async = require('async');
var BaseCollection = require('./baseCollection');
var MUC = require('./muc');

module.exports = BaseCollection.extend({
    type: 'mucs',
    model: MUC,
    comparator: function (model1, model2) {
        var name1 = model1.displayName.toLowerCase();
        var name2 = model2.displayName.toLowerCase();
        if (name1 === name2) {
            return 0;
        }
        if (name1 < name2) {
            return -1;
        }
        return 1;
    },
    initialize: function (model, options) {
        this.bind('change', this.sort, this);
    },
    loadBookmarks: function () {
        var self = this;
        app.whenConnected(function () {
            client.getBookmarks(function (err, res) {
                if (err) return;

                var mucs = res.privateStorage.bookmarks.conferences;
                mucs.forEach(function (muc) {
                    self.add(muc);
                    if (muc.autoJoin) {
                        self.get(muc.jid).join();
                    }
                });
            });
        });
    },
    init: function () {
        var self = this;
        app.whenConnected(function () {

            function _fetch(init) {
                self.fetch(function() {
                    self.update();
                    if (init) self.trigger('loaded');
                    setTimeout(_fetch, 30000);
                });
            }
            _fetch(true);

        });
    },
    fetch: function(cb) {
        var self = this;
        while(app.mucInfos.length > 0) {
            app.mucInfos.pop();
        }

        if (SERVER_CONFIG.muc) {
            if (client.sessionStarted) {

                client.getBookmarks(function (err, res) {
                    if (err) return;

                    var mucs = res.privateStorage.bookmarks.conferences;
                    mucs.forEach(function (muc) {

                        var mucInfo = {
                          id: muc.jid.full,
                          name: muc.name,
                          jid: muc.jid,
                          nick: me.nick,
                          autoJoin: true,
                          persistent: true
                        };

                        client.getRoomMembers(muc.jid.full, me.jid, function(err, res){
                            if(err) return;
                            app.mucInfos.push(mucInfo);
                        });

                    });
                });

                var rooms = [];
                client.getDiscoItems(SERVER_CONFIG.muc, '', function (err, res) {
                    if (err) return;

                    rooms = res.discoItems.items;
                    if (rooms === undefined)
                        rooms = [];
                    var roomNum = 0;

                    rooms.forEach (function (room) {
                      client.getDiscoInfo(room.jid, '', function (err, res) {

                        roomNum++;
                        if (err) return;

                        var features = res.discoInfo.features;
                        var persistent = features.indexOf("muc_persistent") > -1;
                        var mucInfo = {
                          id: room.jid.full,
                          name: room.name,
                          jid: room.jid,
                          nick: me.nick,
                          autoJoin: persistent,
                          persistent: persistent
                        };

                        app.mucInfos.push(mucInfo);

                      }).then(function() {
                        if (cb && roomNum == rooms.length) cb();
                      });
                    });
                }).then(function() {
                    if (cb && !rooms.length) cb();
                });

            } else {
                app.whenConnected(function () {
                    self.fetch(cb);
                });
            }
            return;
        }

        if (cb) cb();

    },
    update: function () {
        if (SERVER_CONFIG.muc) {
            var toRemove = [];
            for ( var i = 0; i < this.models.length; i++) {
                toRemove.push(this.models[i]);
            }

            for (var i = 0; i < app.mucInfos.length; i++) {

                var mucInfo = app.mucInfos[i];
                var muc = this.get(mucInfo.jid);
                if (muc) {
                    muc.name = mucInfo.name;
                    muc.autoJoin =  mucInfo.autoJoin;
                    muc.persistent = mucInfo.persistent;

                    var index = toRemove.indexOf(muc);
                    if (index > -1) {
                        toRemove.splice(index, 1);
                    }
                }
                else {
                    this.add(mucInfo);
                    muc = this.get(mucInfo.jid);
                }

                if (muc.autoJoin && !muc.joined) {
                    muc.join();
                }

            }

            this.remove(toRemove);

            while(app.mucInfos.length > 0) {
                app.mucInfos.pop();
            }
        }
    },
    save: function (cb) {
        var self = this;
        app.whenConnected(function () {
            var models = [];
            self.models.forEach(function (model) {
                models.push({
                    name: model.name,
                    jid: model.jid,
                    nick: model.nick,
                    autoJoin: model.autoJoin
                });
            });
            client.setBookmarks({conferences: models}, cb);
        });
    }
});
<commit_msg>Check that channel does not exist before pushing<commit_after>/*global app, client*/
"use strict";

var async = require('async');
var BaseCollection = require('./baseCollection');
var MUC = require('./muc');

module.exports = BaseCollection.extend({
    type: 'mucs',
    model: MUC,
    comparator: function (model1, model2) {
        var name1 = model1.displayName.toLowerCase();
        var name2 = model2.displayName.toLowerCase();
        if (name1 === name2) {
            return 0;
        }
        if (name1 < name2) {
            return -1;
        }
        return 1;
    },
    initialize: function (model, options) {
        this.bind('change', this.sort, this);
    },
    loadBookmarks: function () {
        var self = this;
        app.whenConnected(function () {
            client.getBookmarks(function (err, res) {
                if (err) return;

                var mucs = res.privateStorage.bookmarks.conferences;
                mucs.forEach(function (muc) {
                    self.add(muc);
                    if (muc.autoJoin) {
                        self.get(muc.jid).join();
                    }
                });
            });
        });
    },
    init: function () {
        var self = this;
        app.whenConnected(function () {

            function _fetch(init) {
                self.fetch(function() {
                    self.update();
                    if (init) self.trigger('loaded');
                    setTimeout(_fetch, 30000);
                });
            }
            _fetch(true);

        });
    },
    fetch: function(cb) {
        var self = this;
        while(app.mucInfos.length > 0) {
            app.mucInfos.pop();
        }

        if (SERVER_CONFIG.muc) {
            if (client.sessionStarted) {

                client.getBookmarks(function (err, res) {
                    if (err) return;

                    var mucs = res.privateStorage.bookmarks.conferences;
                    mucs.forEach(function (muc) {

                        var mucInfo = {
                          id: muc.jid.full,
                          name: muc.name,
                          jid: muc.jid,
                          nick: me.nick,
                          autoJoin: true,
                          persistent: true
                        };

                        var existing = app.mucInfos.map(function(a) {return a.jid;});
                        if(existing.indexOf(mucInfo.jid) == -1) {
                            app.mucInfos.push(mucInfo);
                        }
                    });
                });

                var rooms = [];
                client.getDiscoItems(SERVER_CONFIG.muc, '', function (err, res) {
                    if (err) return;

                    rooms = res.discoItems.items;
                    if (rooms === undefined)
                        rooms = [];
                    var roomNum = 0;

                    rooms.forEach (function (room) {
                      client.getDiscoInfo(room.jid, '', function (err, res) {

                        roomNum++;
                        if (err) return;

                        var features = res.discoInfo.features;
                        var persistent = features.indexOf("muc_persistent") > -1;
                        var mucInfo = {
                          id: room.jid.full,
                          name: room.name,
                          jid: room.jid,
                          nick: me.nick,
                          autoJoin: persistent,
                          persistent: persistent
                        };

                        var existing = app.mucInfos.map(function(a) {return a.jid;});
                        if(existing.indexOf(mucInfo.jid) == -1) {
                            app.mucInfos.push(mucInfo);
                        }

                      }).then(function() {
                        if (cb && roomNum == rooms.length) cb();
                      });
                    });
                }).then(function() {
                    if (cb && !rooms.length) cb();
                });

            } else {
                app.whenConnected(function () {
                    self.fetch(cb);
                });
            }
            return;
        }

        if (cb) cb();

    },
    update: function () {
        if (SERVER_CONFIG.muc) {
            var toRemove = [];
            for ( var i = 0; i < this.models.length; i++) {
                toRemove.push(this.models[i]);
            }

            for (var i = 0; i < app.mucInfos.length; i++) {

                var mucInfo = app.mucInfos[i];
                var muc = this.get(mucInfo.jid);
                if (muc) {
                    muc.name = mucInfo.name;
                    muc.autoJoin =  mucInfo.autoJoin;
                    muc.persistent = mucInfo.persistent;

                    var index = toRemove.indexOf(muc);
                    if (index > -1) {
                        toRemove.splice(index, 1);
                    }
                }
                else {
                    this.add(mucInfo);
                    muc = this.get(mucInfo.jid);
                }

                if (muc.autoJoin && !muc.joined) {
                    muc.join();
                }

            }

            this.remove(toRemove);

            while(app.mucInfos.length > 0) {
                app.mucInfos.pop();
            }
        }
    },
    save: function (cb) {
        var self = this;
        app.whenConnected(function () {
            var models = [];
            self.models.forEach(function (model) {
                models.push({
                    name: model.name,
                    jid: model.jid,
                    nick: model.nick,
                    autoJoin: model.autoJoin
                });
            });
            client.setBookmarks({conferences: models}, cb);
        });
    }
});
<|endoftext|>


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

process.stdin.resume();
process.stdin.on('data', function(test) {
    var result = { log: [] }
    var error;
    var context = {
        $ERROR: function(err) {
            error = err;
        },
        $DONE: function(err) {
            if(err) context.$ERROR(err);
            if(error) {
                if(typeof error === 'object') {
                    if(error.hasOwnProperty('stack')) {
                        console.log("test262/error " + error.stack);
                    } else {
                        console.log("test262/error " + (error.name || Test262Error)  + ": " + error.message);
                    }
                } else {
                    console.log('test262/error Error: ' + error);
                }
            }
            console.log('test262/done');
        },
        $LOG: function(log) {
            console.log(log);
        },
        require: require,
        console: console
    }

    try {
        vm.runInNewContext(test, context);
    } catch(e) {
        context.$DONE(e);
    }
});
<commit_msg>Don't pass require to child context, doesn't work anyway<commit_after>var vm = require('vm');

process.stdin.resume();
process.stdin.on('data', function(test) {
    var result = { log: [] }
    var error;
    var context = {
        $ERROR: function(err) {
            error = err;
        },
        $DONE: function(err) {
            if(err) context.$ERROR(err);
            if(error) {
                if(typeof error === 'object') {
                    if(error.hasOwnProperty('stack')) {
                        console.log("test262/error " + error.stack);
                    } else {
                        console.log("test262/error " + (error.name || Test262Error)  + ": " + error.message);
                    }
                } else {
                    console.log('test262/error Error: ' + error);
                }
            }
            console.log('test262/done');
        },
        $LOG: function(log) {
            console.log(log);
        },
        console: console
    }

    try {
        vm.runInNewContext(test, context);
    } catch(e) {
        context.$DONE(e);
    }
});
<|endoftext|>


<commit_before>/* Python built-in exceptions */

var Exception = __inherit(object, "Exception");

Exception.prototype.__init__ = function() {
    if (arguments.length > 0) {
        this.message = arguments[0];
    } else {
        this.message = "";
    }
}

Exception.prototype.__str__ = function() {
    return str.__call__(js(this.__class__.__name__) + ": " + js(this.message));
};

Exception.prototype.toString = function() {
    return js(this.__str__());
};

py_builtins.__exceptions__ = [
    'NotImplementedError',
    'ZeroDivisionError',
    'AssertionError',
    'AttributeError',
    'RuntimeError',
    'ImportError',
    'TypeError',
    'ValueError',
    'NameError',
    'IndexError',
    'KeyError',
    'StopIteration'
];

for (var i in py_builtins.__exceptions__) {
    var name = py_builtins.__exceptions__[i];
    py_builtins[name] = __inherit(Exception, name);
};
<commit_msg> * Make Exception.__str__ not print the class name first. It is less easy to read, but python-compatible<commit_after>/* Python built-in exceptions */

var Exception = __inherit(object, "Exception");

Exception.prototype.__init__ = function() {
    if (arguments.length > 0) {
        this.message = arguments[0];
    } else {
        this.message = "";
    }
}

Exception.prototype.__str__ = function() {
    return str.__call__(this.message);
};

Exception.prototype.toString = function() {
    return js(this.__str__());
};

py_builtins.__exceptions__ = [
    'NotImplementedError',
    'ZeroDivisionError',
    'AssertionError',
    'AttributeError',
    'RuntimeError',
    'ImportError',
    'TypeError',
    'ValueError',
    'NameError',
    'IndexError',
    'KeyError',
    'StopIteration'
];

for (var i in py_builtins.__exceptions__) {
    var name = py_builtins.__exceptions__[i];
    py_builtins[name] = __inherit(Exception, name);
};
<|endoftext|>


<commit_before>var Joi = require('joi');

module.exports = {
    id: Joi.string(),
    name: Joi.string(),
    street_1: Joi.string(),
    street_2: Joi.string(),
    city: Joi.string(),
    state: Joi.string(),
    zip: Joi.string(),
    coordinates: Joi.array().includes(Joi.number()).min(2).max(2),
    address_date: Joi.date(),
    agent_name: Joi.string(),
    agent_street_1: Joi.string(),
    agent_street_2: Joi.string(),
    agent_city: Joi.string(),
    agent_state: Joi.string(),
    agent_zip: Joi.string(),
    agent_court_locality: Joi.string(),
    agent_date: Joi.date(),
    agent_status: Joi.string(),
    expiration_date: Joi.date(),
    incorporation_date: Joi.date(),
    industry: Joi.string(),
    state_formed: Joi.string(),
    status: Joi.string(),
    status_date: Joi.date(),
    domestic: Joi.string(),
    foreign: Joi.string(),
    merged: Joi.string(),
    number_shares: Joi.number(),
    total_shares: Joi.number(),
    stock_ind: Joi.string()
}<commit_msg>implement geo search. Resolves #10."<commit_after>var Joi = require('joi');
var officers = require('./officers');

module.exports = Joi.object().keys({
    id: Joi.string(),
    name: Joi.string(),
    street_1: Joi.string(),
    street_2: Joi.string(),
    city: Joi.string(),
    state: Joi.string(),
    zip: Joi.string(),
    coordinates: Joi.array().includes(Joi.number(), Joi.number()).min(2).max(2),
    dist: Joi.number(),
    address_date: Joi.date(),
    agent_name: Joi.string(),
    agent_street_1: Joi.string(),
    agent_street_2: Joi.string(),
    agent_city: Joi.string(),
    agent_state: Joi.string(),
    agent_zip: Joi.string(),
    agent_court_locality: Joi.string(),
    agent_date: Joi.date(),
    agent_status: Joi.string(),
    expiration_date: Joi.date(),
    incorporation_date: Joi.date(),
    industry: Joi.string(),
    state_formed: Joi.string(),
    status: Joi.string(),
    status_date: Joi.date(),
    domestic: Joi.string(),
    foreign: Joi.string(),
    merged: Joi.string(),
    number_shares: Joi.number(),
    total_shares: Joi.number(),
    stock_ind: Joi.string()
}).with('coordinates', 'dist');<|endoftext|>


<commit_before>/**
 * XMLEnvironment wraps up all the global behavior that XML literals will adhere to. An
 * XMLEnvironment must define 4 functions for generating XML objects:
 *
 * function isNode(node);
 *   Returns `true` if `node` is any kind of Node; i.e. Node, Fragment, Text, Comment, etc.
 *
 * function createElement(uri, nodeName, children, attributes, attributesNS);
 *   Creates an element usable in this environment.
 *   uri:          Namespace URI for this element.
 *   nodeName:     Local name of this node; i.e. no prefix or URI included. This name is NOT
 *                 normalized and will appear with its original casing, however it will always be
 *                 a string.
 *   children:     Array of children. `undefined` if there are no children. Note that the array may
 *                 contain any combination of `Node`, `Text`, or `Fragment`s.
 *   attributes:   Map of attributes with no namespace. `undefined` if there are no attributes.
 *                 Looks like: {<attr>: <value>, ...}.
 *                 Attribute values are NOT casted to strings in the case of embedded expressions.
 *                 i.e.  may give you a non-string attribute.
 *   attributesNS: Map of attributes with namespaces. `undefined` if there are no attributes.
 *                 Looks like: {<uri>: {<attr>: <value>, ...}, ...}
 *
 * function createFragment(children);
 *   Creates a document fragment.
 *   children:     Array of children. `undefined` for an empty fragment. Note that the array may
 *                 contain any combination of `Node`, `Text`, or `Fragment`s.
 *
 * function createTextNode(data);
 *   data:         Unescaped data for this text node.
 *
 * If I cared more, there would be interfaces for `createComment`, and
 * `createProcessingInstruction`... but these are generally useless to me. If any of the creation
 * functions return a falsey value, that element will be ignored.
 *
 * The API of the document is left to the implementation to decide. Unless the bundled psuedo-DOM
 * API is used, js-dom-literal only handles the construction of new objects via XML literal syntax.
 *
 * When called in a browser, XMLEnvironment will be defined in the global object. When called as a
 * CommonJS module it will be an export. In the CommonJS case, you must make this a global yourself.
 */
~function() {
	this.XMLEnvironment = XMLEnvironment;
	function XMLEnvironment(fns) {
		this._namespaces = {};
		this.ignoreWhitespace = true;
		this.registerPrefix('', '');
	};

	XMLEnvironment.get = function() {
		return XMLEnvironment._currentEnvironment;
	}

	XMLEnvironment.set = function(env) {
		XMLEnvironment._currentEnvironment = env;
	}

	XMLEnvironment.prototype = {
		registerPrefix: function(prefix, uri) {
			this._namespaces[prefix] = uri;
		},

		removePrefix: function(prefix) {
			if (!(prefix in this._namespaces)) {
				throw new Error('namespace `' + prefix + '` does not exist');
			}
			delete this._namespaces[prefix];
		},

		_el: function(descriptor) {
			return this._generateChildren([descriptor], this._namespaces)[0];
		},

		_frag: function(descriptor) {
			return this.createFragment(this._generateChildren(descriptor, this._namespaces));
		},

		_generateChildren: function(descriptors, namespaces) {
			var elements = [];
			for (var ii = 0; ii < descriptors.length; ++ii) {
				var descriptor = descriptors[ii];
				if (descriptor.type === 1) { // TYPE_ELEMENT
					// Check tag match
					var open = descriptorToString(descriptor.open);
					var close = descriptorToString(descriptor.close);
					if (open !== close && close !== undefined) {
						throw new SyntaxError('XML tag name mismatch (expected ' + open + ')');
					}

					// Loop through attributes once to xmlns declarations
					var keys = descriptor.attributes && descriptor.attributes.keys;
					var vals = descriptor.attributes && descriptor.attributes.vals;
					var currentNamespaces;
					if (keys) {
						for (var jj = 0; jj < keys.length; ++jj) {
							if (xmlnsRegex.test(keys[jj])) {
								currentNamespaces = currentNamespaces || beget(namespaces);
								var xmlns = parseXMLName(keys[jj]);
								currentNamespaces[xmlns[1] ? xmlns[2] : ''] = vals[jj];
								keys.splice(jj, 1);
								vals.splice(jj, 1);
								--jj;
							}
						}
					}
					currentNamespaces = currentNamespaces || namespaces;

					// Parse element's name
					var nodeName = parseXMLName(open);
					var namespaceURI;
					if (nodeName[1]) {
						// Namespace via prefix
						if (!(nodeName[1] in currentNamespaces)) {
							throw new TypeError('invalid XML namespace ' + nodeName[1]);
						}
						namespaceURI = currentNamespaces[nodeName[1]];
					} else {
						namespaceURI = currentNamespaces[''];
					}

					// Generate attributes
					if (keys) {
						var attributes = {}, attributesNS = undefined;
						for (var jj = 0; jj < keys.length; ++jj) {
							var attrName = parseXMLName(keys[jj]);
							if (attrName[1]) {
								// Namespaced attributes
								if (!(attrName[1] in currentNamespaces)) {
									throw new TypeError('invalid XML namespace ' + attrName[1]);
								}
								var attrURI = currentNamespaces[attrName[1]];
								if (attrURI !== '') {
									attributesNS = attributesNS || {};
									if (!(attrURI in attributesNS)) {
										attributesNS[attrURI] = {};
									}
									if (attrName[2] in attributesNS[attrURI]) {
										throw new TypeError('duplicate XML attribute ' + keys[jj]);
									}
									attributesNS[attrURI][attrName[2]] = vals[jj];
									continue;
								}
							}

							// Non-namespaced attribute
							if (attrName[2] in attributes) {
								throw new TypeError('duplicate XML attribute ' + keys[jj]);
							}
							attributes[attrName[2]] = vals[jj];
						}
					}

					// Generate children
					var children = descriptor.content ?
						this._generateChildren(descriptor.content, currentNamespaces) : undefined;

					// Construct this element
					var element =
						this.createElement(namespaceURI, nodeName[2], children, attributes, attributesNS);
					if (element) {
						elements.push(element);
					}
					continue;
				}

				if (descriptor.type === 3) { // TYPE_EXPR
					if (this.isNode(descriptor.value)) {
						elements.push(descriptor.value);
						continue;
					} else {
						descriptor.value = ToString(descriptor.value);
					}
				} else if (descriptor.type === 2) { // TYPE_CDATA
					if (this.ignoreWhitespace) {
						// Hairbrained whitespace logic
						if (descriptors.length !== 1) {
							descriptor.value = descriptor.value.replace(whitespaceRegex, ' ');
						} else if (allWhitespaceRegex.test(descriptor.value)) {
							continue;
						}
					}
				}
				if (descriptor.value !== '') {
					var element = this.createTextNode(descriptor.value);
					if (element) {
						elements.push(element);
					}
				}
			}
			return elements;
		}
	};

	/**
	 * Inline utility functions for easy client code deployment.
	 */
	var xmlnsRegex = /^xmlns(?:$|:)/,
			xmlNameRegex = /^(?:([a-zA-Z_][a-zA-Z0-9_.\-]*):)?([a-zA-Z_][a-zA-Z0-9_.\-]*)$/,
			whitespaceRegex = /^[ \t\r\n]{2,}|[ \t\r\n]{2,}$/g,
			allWhitespaceRegex = /^[ \t\r\n]+$/g;
			undefined;
	function ToString(expr) {
		if (typeof expr === 'string') {
			return expr;
		} else if (expr === undefined) {
			return 'undefined';
		} else if (expr === null) {
			return 'null';
		}
		expr = expr.toString();
		if (typeof expr === 'string') {
			return expr;
		} else {
			throw new TypeError('can\'t convert expression to string');
		}
	}

	function beget(obj) {
		function F() {}
		F.prototype = obj;
		return new F;
	}

	function parseXMLName(name) {
		var ret = xmlNameRegex.exec(name);
		if (!ret) {
			throw new SyntaxError('illegal XML name ' + name);
		}
		return ret;
	}

	function descriptorToString(descriptor) {
		if (descriptor === undefined) {
			return undefined;
		}
		return descriptor.type === 3 ? ToString(descriptor.value) : descriptor;
	}
}.call(this);
<commit_msg>New whitespace logic<commit_after>/**
 * XMLEnvironment wraps up all the global behavior that XML literals will adhere to. An
 * XMLEnvironment must define 4 functions for generating XML objects:
 *
 * function isNode(node);
 *   Returns `true` if `node` is any kind of Node; i.e. Node, Fragment, Text, Comment, etc.
 *
 * function createElement(uri, nodeName, children, attributes, attributesNS);
 *   Creates an element usable in this environment.
 *   uri:          Namespace URI for this element.
 *   nodeName:     Local name of this node; i.e. no prefix or URI included. This name is NOT
 *                 normalized and will appear with its original casing, however it will always be
 *                 a string.
 *   children:     Array of children. `undefined` if there are no children. Note that the array may
 *                 contain any combination of `Node`, `Text`, or `Fragment`s.
 *   attributes:   Map of attributes with no namespace. `undefined` if there are no attributes.
 *                 Looks like: {<attr>: <value>, ...}.
 *                 Attribute values are NOT casted to strings in the case of embedded expressions.
 *                 i.e.  may give you a non-string attribute.
 *   attributesNS: Map of attributes with namespaces. `undefined` if there are no attributes.
 *                 Looks like: {<uri>: {<attr>: <value>, ...}, ...}
 *
 * function createFragment(children);
 *   Creates a document fragment.
 *   children:     Array of children. `undefined` for an empty fragment. Note that the array may
 *                 contain any combination of `Node`, `Text`, or `Fragment`s.
 *
 * function createTextNode(data);
 *   data:         Unescaped data for this text node.
 *
 * If I cared more, there would be interfaces for `createComment`, and
 * `createProcessingInstruction`... but these are generally useless to me. If any of the creation
 * functions return a falsey value, that element will be ignored.
 *
 * The API of the document is left to the implementation to decide. Unless the bundled psuedo-DOM
 * API is used, js-xml-literal only handles the construction of new objects via XML literal syntax.
 *
 * When called in a browser, XMLEnvironment will be defined in the global object. When called as a
 * CommonJS module it will be an export. In the CommonJS case, you must make this a global yourself.
 */
~function() {
	this.XMLEnvironment = XMLEnvironment;
	function XMLEnvironment(fns) {
		this._namespaces = {};
		this.ignoreWhitespace = true;
		this.registerPrefix('', '');
	};

	XMLEnvironment.get = function() {
		return XMLEnvironment._currentEnvironment;
	}

	XMLEnvironment.set = function(env) {
		XMLEnvironment._currentEnvironment = env;
	}

	XMLEnvironment.prototype = {
		registerPrefix: function(prefix, uri) {
			this._namespaces[prefix] = uri;
		},

		removePrefix: function(prefix) {
			if (!(prefix in this._namespaces)) {
				throw new Error('namespace `' + prefix + '` does not exist');
			}
			delete this._namespaces[prefix];
		},

		_el: function(descriptor) {
			return this._generateChildren([descriptor], this._namespaces)[0];
		},

		_frag: function(descriptor) {
			return this.createFragment(this._generateChildren(descriptor, this._namespaces));
		},

		_generateChildren: function(descriptors, namespaces) {
			var elements = [];
			for (var ii = 0; ii < descriptors.length; ++ii) {
				var descriptor = descriptors[ii];
				if (descriptor.type === 1) { // TYPE_ELEMENT
					// Check tag match
					var open = descriptorToString(descriptor.open);
					var close = descriptorToString(descriptor.close);
					if (open !== close && close !== undefined) {
						throw new SyntaxError('XML tag name mismatch (expected ' + open + ')');
					}

					// Loop through attributes once to xmlns declarations
					var keys = descriptor.attributes && descriptor.attributes.keys;
					var vals = descriptor.attributes && descriptor.attributes.vals;
					var currentNamespaces;
					if (keys) {
						for (var jj = 0; jj < keys.length; ++jj) {
							if (xmlnsRegex.test(keys[jj])) {
								currentNamespaces = currentNamespaces || beget(namespaces);
								var xmlns = parseXMLName(keys[jj]);
								currentNamespaces[xmlns[1] ? xmlns[2] : ''] = vals[jj];
								keys.splice(jj, 1);
								vals.splice(jj, 1);
								--jj;
							}
						}
					}
					currentNamespaces = currentNamespaces || namespaces;

					// Parse element's name
					var nodeName = parseXMLName(open);
					var namespaceURI;
					if (nodeName[1]) {
						// Namespace via prefix
						if (!(nodeName[1] in currentNamespaces)) {
							throw new TypeError('invalid XML namespace ' + nodeName[1]);
						}
						namespaceURI = currentNamespaces[nodeName[1]];
					} else {
						namespaceURI = currentNamespaces[''];
					}

					// Generate attributes
					if (keys) {
						var attributes = {}, attributesNS = undefined;
						for (var jj = 0; jj < keys.length; ++jj) {
							var attrName = parseXMLName(keys[jj]);
							if (attrName[1]) {
								// Namespaced attributes
								if (!(attrName[1] in currentNamespaces)) {
									throw new TypeError('invalid XML namespace ' + attrName[1]);
								}
								var attrURI = currentNamespaces[attrName[1]];
								if (attrURI !== '') {
									attributesNS = attributesNS || {};
									if (!(attrURI in attributesNS)) {
										attributesNS[attrURI] = {};
									}
									if (attrName[2] in attributesNS[attrURI]) {
										throw new TypeError('duplicate XML attribute ' + keys[jj]);
									}
									attributesNS[attrURI][attrName[2]] = vals[jj];
									continue;
								}
							}

							// Non-namespaced attribute
							if (attrName[2] in attributes) {
								throw new TypeError('duplicate XML attribute ' + keys[jj]);
							}
							attributes[attrName[2]] = vals[jj];
						}
					}

					// Generate children
					var children = descriptor.content ?
						this._generateChildren(descriptor.content, currentNamespaces) : undefined;

					// Construct this element
					var element =
						this.createElement(namespaceURI, nodeName[2], children, attributes, attributesNS);
					if (element) {
						elements.push(element);
					}
					continue;
				}

				if (descriptor.type === 3) { // TYPE_EXPR
					if (this.isNode(descriptor.value)) {
						elements.push(descriptor.value);
						continue;
					} else {
						descriptor.value = ToString(descriptor.value);
					}
				} else if (descriptor.type === 2) { // TYPE_CDATA
					if (this.ignoreWhitespace) {
						/**
						 * Hairbrained whitespace logic!
						 *
						 * Goals:
						 *
						 * 1) Pretty HTML doesn't contain problematic whitespace:
						 *
						 *        Hello
						 *
						 *    same as..
						 *      Hello
						 *
						 * 2) Meaningful whitespace persists:
						 *      My name is: Marcel
						 *    not the same as..
						 *      My name is:Marcel
						 *
						 */

						// First remove whitespace that starts on its own line
						descriptor.value = descriptor.value.replace(newlineWithSpaces, '\n');

						// Then remove newlines from the front and back
						descriptor.value = descriptor.value.replace(leadingAndTrailingNewlinesRegex, '');
					}
				}
				if (descriptor.value !== '') {
					var element = this.createTextNode(descriptor.value);
					if (element) {
						elements.push(element);
					}
				}
			}
			return elements;
		}
	};

	/**
	 * Inline utility functions for easy client code deployment.
	 */
	var xmlnsRegex = /^xmlns(?:$|:)/,
			xmlNameRegex = /^(?:([a-zA-Z_][a-zA-Z0-9_.\-]*):)?([a-zA-Z_][a-zA-Z0-9_.\-]*)$/,
			newlineWithSpaces = /[\r\n]+[ \t]+/g,
			leadingAndTrailingNewlinesRegex = /(?:^[\n\r]+)|(?:[\n\r]+$)/g;
	function ToString(expr) {
		if (typeof expr === 'string') {
			return expr;
		} else if (expr === undefined) {
			return 'undefined';
		} else if (expr === null) {
			return 'null';
		}
		expr = expr.toString();
		if (typeof expr === 'string') {
			return expr;
		} else {
			throw new TypeError('can\'t convert expression to string');
		}
	}

	function beget(obj) {
		function F() {}
		F.prototype = obj;
		return new F;
	}

	function parseXMLName(name) {
		var ret = xmlNameRegex.exec(name);
		xmlNameRegex.lastIndex = 0;
		if (!ret) {
			throw new SyntaxError('illegal XML name ' + name);
		}
		return ret;
	}

	function descriptorToString(descriptor) {
		if (descriptor === undefined) {
			return undefined;
		}
		return descriptor.type === 3 ? ToString(descriptor.value) : descriptor;
	}
}.call(this);
<|endoftext|>


<commit_before>"use strict";

const Alexa = require("alexa-sdk");
const helpers = require("./helpers");

// Define states
let states = {
    WHATS_ON: "_WHATS_ON"
};

function logHandler(name) {
    console.log("Intent: " + name);
}

module.exports = {
    mainHandlers: {
        "AMAZON.YesIntent": function () {
            logHandler(this.name);

            this.emit(":tell", this.t("CANCEL_RESPONSE"));
        },

        "AMAZON.NoIntent": function () {
            logHandler(this.name);

            this.emit(":tell", this.t("CANCEL_RESPONSE"));
        },

        "AMAZON.CancelIntent": function () {
            logHandler(this.name);

            this.emit(":tell", this.t("CANCEL_RESPONSE"));
        },

        "AMAZON.StopIntent": function () {
            logHandler(this.name);

            this.emit(":tell", this.t("CANCEL_RESPONSE"));
        },

        "Unhandled": function x() {
            logHandler(this.name);

            this.handler.state = null;
            this.emit(":tell", this.t("GOODBYE"));
        },

        "AMAZON.HelpIntent": function () {
            logHandler(this.name);

            this.emit(":ask", this.t("HELP_TEXT"), this.t("HELP_TEXT_REPROMPT"));
        },

        "LaunchRequest": function () {
            logHandler(this.name);

            this.emit(":ask", this.t("LAUNCH_TEXT"), this.t("LAUNCH_TEXT_REPROMPT"));
        },

        "WhatsOnIntent": function () {
            logHandler(this.name);

            this.handler.state = states.WHATS_ON;

            this.emitWithState("WhatsOnIntent");
        }
    },

    whatsOnHandlers: Alexa.CreateStateHandler(states.WHATS_ON, {
        "AMAZON.YesIntent": function (callback, done) {
            logHandler(this.name);

            let houseOfInterest = this.attributes.houseOfInterest;

            let uri_options = helpers.getCalendarUriOptions(houseOfInterest);

            // Get our events and generate a message from them
            helpers.getEvents(uri_options, function (events) {
                helpers.generateDetailedEventMessage(events, this, callback, done);
            });
        },

        "AMAZON.NoIntent": function () {
            logHandler(this.name);

            this.handler.state = null;
            this.emit(":tell", this.t("NO_RESPONSE"));
        },

        "AMAZON.CancelIntent": function () {
            logHandler(this.name);

            this.handler.state = null;
            this.emit(":tell", this.t("NO_RESPONSE"));
        },

        "AMAZON.StopIntent": function () {
            logHandler(this.name);

            this.handler.state = null;
            this.emit(":tell", this.t("NO_RESPONSE"));
        },

        "Unhandled": function () {
            logHandler(this.name);

            this.handler.state = null;
            this.emit(":tell", this.t("GOODBYE"));
        },

        "AMAZON.HelpIntent": function () {
            logHandler(this.name);

            this.emit(":ask", this.t("HELP_TEXT"), this.t("HELP_TEXT_REPROMPT"));
        },

        "WhatsOnIntent": function (callback, done) {
            logHandler(this.name);

            let handlers = this;

            let houseOfInterest = helpers.getHouseIntentData(handlers.event.request.intent);
            handlers.attributes.houseOfInterest = houseOfInterest;

            let uri_options = helpers.getCalendarUriOptions(houseOfInterest);

            // Get our events and generate a message from them
            helpers.getEvents(uri_options, function (events) {
                helpers.generateEventMessage(events, handlers, callback, done);
            });
        }
    })
};
<commit_msg>Add improved AWS Yes handlers<commit_after>"use strict";

const Alexa = require("alexa-sdk");
const helpers = require("./helpers");

// Define states
let states = {
    WHATS_ON: "_WHATS_ON"
};

function logHandler(name) {
    console.log("Intent: " + name);
}

module.exports = {
    mainHandlers: {
        "AMAZON.YesIntent": function () {
            logHandler(this.name);

            this.emit(":tell", this.t("CANCEL_RESPONSE"));
        },

        "AMAZON.NoIntent": function () {
            logHandler(this.name);

            this.emit(":tell", this.t("CANCEL_RESPONSE"));
        },

        "AMAZON.CancelIntent": function () {
            logHandler(this.name);

            this.emit(":tell", this.t("CANCEL_RESPONSE"));
        },

        "AMAZON.StopIntent": function () {
            logHandler(this.name);

            this.emit(":tell", this.t("CANCEL_RESPONSE"));
        },

        "Unhandled": function x() {
            logHandler(this.name);

            this.handler.state = null;
            this.emit(":tell", this.t("GOODBYE"));
        },

        "AMAZON.HelpIntent": function () {
            logHandler(this.name);

            this.emit(":ask", this.t("HELP_TEXT"), this.t("HELP_TEXT_REPROMPT"));
        },

        "LaunchRequest": function () {
            logHandler(this.name);

            this.emit(":ask", this.t("LAUNCH_TEXT"), this.t("LAUNCH_TEXT_REPROMPT"));
        },

        "WhatsOnIntent": function () {
            logHandler(this.name);

            this.handler.state = states.WHATS_ON;

            this.emitWithState("WhatsOnIntent");
        }
    },

    whatsOnHandlers: Alexa.CreateStateHandler(states.WHATS_ON, {
        "AMAZON.YesIntent": function (callback, done) {
            logHandler(this.name);

            let handlers = this;

            let houseOfInterest = handlers.attributes.houseOfInterest;

            let uri_options = helpers.getCalendarUriOptions(houseOfInterest);

            // Get our events and generate a message from them
            helpers.getEvents(uri_options, function (events) {
                helpers.generateDetailedEventMessage(events, handlers, callback, done);
            });
        },

        "AMAZON.NoIntent": function () {
            logHandler(this.name);

            this.handler.state = null;
            this.emit(":tell", this.t("NO_RESPONSE"));
        },

        "AMAZON.CancelIntent": function () {
            logHandler(this.name);

            this.handler.state = null;
            this.emit(":tell", this.t("NO_RESPONSE"));
        },

        "AMAZON.StopIntent": function () {
            logHandler(this.name);

            this.handler.state = null;
            this.emit(":tell", this.t("NO_RESPONSE"));
        },

        "Unhandled": function () {
            logHandler(this.name);

            this.handler.state = null;
            this.emit(":tell", this.t("GOODBYE"));
        },

        "AMAZON.HelpIntent": function () {
            logHandler(this.name);

            this.emit(":ask", this.t("HELP_TEXT"), this.t("HELP_TEXT_REPROMPT"));
        },

        "WhatsOnIntent": function (callback, done) {
            logHandler(this.name);

            let handlers = this;

            let houseOfInterest = helpers.getHouseIntentData(handlers.event.request.intent);
            handlers.attributes.houseOfInterest = houseOfInterest;

            let uri_options = helpers.getCalendarUriOptions(houseOfInterest);

            // Get our events and generate a message from them
            helpers.getEvents(uri_options, function (events) {
                helpers.generateEventMessage(events, handlers, callback, done);
            });
        }
    })
};
<|endoftext|>