<commit_before>let Loader = require("./lib/loader");
let fs = require("fs");
let path = require("path");
let PromiseEventEmitter = require("./lib/PromiseEventEmitter");
let Logger = require("./lib/Logger");

Array.prototype.unique = function () {
    let set = new Set();
    return this.filter(elem=> {
        if (set.has(elem))return false;
        set.add(elem);
        return true;
    });
};

Object.deepExtend = function (destination, source) {
    for (var property in source) {
        if (!source.hasOwnProperty(property))continue;
        if (source[property] && source[property].constructor &&
            source[property].constructor === Object) {
            destination[property] = destination[property] || {};
            arguments.callee(destination[property], source[property]);
        } else {
            destination[property] = source[property];
        }
    }
    return destination;
};

let modulePaths = [
    path.join(__dirname, "node_modules"), path.join(path.dirname(module.parent.filename), "node_modules")
];
let settings = {
    moin: {
        modulePaths: []
    },
    logging: {
        level: "debug",
        disabled: []
    }
};

let moin = function (cwd, init) {
    console.log(init);
    let config = {};
    if (fs.existsSync(path.join(cwd, "config.json"))) {
        config = require(path.join(cwd, "config.json"));
    }

    let confStr = JSON.stringify(config);

    Loader = Loader((conf)=> {
        config = Object.deepExtend(conf, config);
    });

    let _modules = [];
    config = Object.deepExtend(settings, config);
    let running = false;

    Logger = Logger(config.logging);
    let log = new Logger("main");

    let _api = (function () {
        let custom = {};
        let main = new class extends PromiseEventEmitter {
            joinPath(...pathSegments) {
                return path.join(cwd, ...pathSegments);
            }

            load(path) {
                return Loader(path);
            }

            getMainModule() {
                return module.parent;
            }

            getLogger(name) {
                return new Logger(name);
            }

            registerMethod(name, fnc, after = true) {
                if (!custom.hasOwnProperty(name))custom[name] = [];
                if (after) {
                    custom[name].push(fnc);
                } else {
                    custom[name].unshift(fnc);
                }
            }
        };

        process.on('SIGINT', function () {
            log.warn("SIGINT received. stopping Moin");
            _api.emit("exit").then(()=> {
                process.exit(0);
            });
        });

        let api = new Proxy(main, {
            get(target, name) {
                if (name in main)return main[name];
                if (!custom.hasOwnProperty(name))return undefined;
                return function () {
                    let lastValue = undefined;
                    let args = [...arguments];
                    let stop = false;
                    let thisObj = {
                        getLastValue(){
                            return lastValue;
                        },
                        setArguments(...arguments){
                            args = arguments;
                        },
                        stopPropagation(){
                            stop = true;
                        },
                        getApi(){
                            return api;
                        }
                    };

                    custom[name].forEach(function (fnc) {
                        if (stop)return;
                        lastValue = fnc.apply(thisObj, args);
                    });
                    return lastValue;
                };
            }
        });
        api.setThisObject(api);
        return api;
    })();

    function scanForFolders(folders) {
        return Promise.all(folders.map(folder=> {
            return new Promise((resolve, reject)=> {
                fs.readdir(folder, function (err, sub) {
                    if (err) {
                        resolve([]);
                    } else {
                        resolve(sub.map(f=>path.join(folder, f)));
                    }
                })
            })
        })).then(result=>result.reduce((arr, elem)=>arr.concat(elem), []));
    }

    return {
        addModulePath(path){
            settings.moin.modulePaths.push(path);
            return this;
        },
        getApi(){
            return _api;
        },
        run(){
            if (running)throw "Allready running";
            running = true;
            let lookupPaths = settings.moin.modulePaths.concat(modulePaths).map(p=>path.resolve(p)).unique();
            return scanForFolders(lookupPaths)
                .then((folders)=>Promise.all(folders.map(folder=>Loader(folder))))
                .then((modules)=>modules.filter(m=>m != null && m.getType() == "module"))
                .then(modules=> {
                    return new Promise((resolve, reject)=> {
                        let loadOrder = [];

                        while (modules.length > 0) {
                            let resolvable = modules
                                .filter(mod=>mod.isResolved())
                                .filter(mod=>config[mod.getName()].active);

                            modules = modules.filter(mod=>!mod.isResolved());
                            if (resolvable.length == 0)throw "Cannot fullfill all dependencies";
                            loadOrder = loadOrder.concat(resolvable);
                            modules.forEach(module=> {
                                resolvable.forEach(res=> {
                                    module.resolveDependency(res);
                                })
                            })
                        }
                        resolve(loadOrder);
                    });
                }).then(function (modules) {
                    if (init)return;
                    _modules = modules;
                    _modules.forEach(module=>module.load(_api, config[module.getName()]));
                    log.info(`${_modules.length} modules loaded. beginning startup`)
                }).then(function () {
                    log.startSpinner("Initializing Modules %s");
                }).then(function (spinner) {
                    return _api.emit("init");
                }).then(function (spinner) {
                    log.stopSpinner();
                }).then(function () {
                    log.info("Startup complete");
                    if (confStr != JSON.stringify(config)) {
                        log.info("Change in Modules detected. Saving config.json");
                        fs.writeFileSync(path.join(cwd, "config.json"), JSON.stringify(config, null, 2));
                    }
                })
                .catch(function (e) {
                    log.error("Error in startup routine:", e);
                });
        }

    };
};

module.exports = function (cwd = path.dirname(module.parent.filename), init = false) {
    moin = moin(cwd, init);
    return moin.run().then(()=>moin.getApi());
};<commit_msg>Added the init flag. With this flag moin only creates the config.json file and exits.<commit_after>let Loader = require("./lib/loader");
let fs = require("fs");
let path = require("path");
let PromiseEventEmitter = require("./lib/PromiseEventEmitter");
let Logger = require("./lib/Logger");

Array.prototype.unique = function () {
    let set = new Set();
    return this.filter(elem=> {
        if (set.has(elem))return false;
        set.add(elem);
        return true;
    });
};

Object.deepExtend = function (destination, source) {
    for (var property in source) {
        if (!source.hasOwnProperty(property))continue;
        if (source[property] && source[property].constructor &&
            source[property].constructor === Object) {
            destination[property] = destination[property] || {};
            arguments.callee(destination[property], source[property]);
        } else {
            destination[property] = source[property];
        }
    }
    return destination;
};

let modulePaths = [
    path.join(__dirname, "node_modules"), path.join(path.dirname(module.parent.filename), "node_modules")
];
let settings = {
    moin: {
        modulePaths: []
    },
    logging: {
        level: "debug",
        disabled: []
    }
};

let moin = function (cwd, init) {
    let config = {};
    if (fs.existsSync(path.join(cwd, "config.json"))) {
        config = require(path.join(cwd, "config.json"));
    }

    let confStr = JSON.stringify(config);

    Loader = Loader((conf)=> {
        config = Object.deepExtend(conf, config);
    });

    let _modules = [];
    config = Object.deepExtend(settings, config);
    let running = false;

    Logger = Logger(config.logging);
    let log = new Logger("main");

    let _api = (function () {
        let custom = {};
        let main = new class extends PromiseEventEmitter {
            joinPath(...pathSegments) {
                return path.join(cwd, ...pathSegments);
            }

            load(path) {
                return Loader(path);
            }

            getMainModule() {
                return module.parent;
            }

            getLogger(name) {
                return new Logger(name);
            }

            registerMethod(name, fnc, after = true) {
                if (!custom.hasOwnProperty(name))custom[name] = [];
                if (after) {
                    custom[name].push(fnc);
                } else {
                    custom[name].unshift(fnc);
                }
            }
        };

        process.on('SIGINT', function () {
            log.warn("SIGINT received. stopping Moin");
            _api.emit("exit").then(()=> {
                process.exit(0);
            });
        });

        let api = new Proxy(main, {
            get(target, name) {
                if (name in main)return main[name];
                if (!custom.hasOwnProperty(name))return undefined;
                return function () {
                    let lastValue = undefined;
                    let args = [...arguments];
                    let stop = false;
                    let thisObj = {
                        getLastValue(){
                            return lastValue;
                        },
                        setArguments(...arguments){
                            args = arguments;
                        },
                        stopPropagation(){
                            stop = true;
                        },
                        getApi(){
                            return api;
                        }
                    };

                    custom[name].forEach(function (fnc) {
                        if (stop)return;
                        lastValue = fnc.apply(thisObj, args);
                    });
                    return lastValue;
                };
            }
        });
        api.setThisObject(api);
        return api;
    })();

    function scanForFolders(folders) {
        return Promise.all(folders.map(folder=> {
            return new Promise((resolve, reject)=> {
                fs.readdir(folder, function (err, sub) {
                    if (err) {
                        resolve([]);
                    } else {
                        resolve(sub.map(f=>path.join(folder, f)));
                    }
                })
            })
        })).then(result=>result.reduce((arr, elem)=>arr.concat(elem), []));
    }

    return {
        addModulePath(path){
            settings.moin.modulePaths.push(path);
            return this;
        },
        getApi(){
            return _api;
        },
        run(){
            if (running)throw "Allready running";
            running = true;
            let lookupPaths = settings.moin.modulePaths.concat(modulePaths).map(p=>path.resolve(p)).unique();
            return scanForFolders(lookupPaths)
                .then((folders)=>Promise.all(folders.map(folder=>Loader(folder))))
                .then((modules)=>modules.filter(m=>m != null && m.getType() == "module"))
                .then(modules=> {
                    return new Promise((resolve, reject)=> {
                        let loadOrder = [];

                        while (modules.length > 0) {
                            let resolvable = modules
                                .filter(mod=>mod.isResolved())
                                .filter(mod=>config[mod.getName()].active);

                            modules = modules.filter(mod=>!mod.isResolved());
                            if (resolvable.length == 0)throw "Cannot fullfill all dependencies";
                            loadOrder = loadOrder.concat(resolvable);
                            modules.forEach(module=> {
                                resolvable.forEach(res=> {
                                    module.resolveDependency(res);
                                })
                            })
                        }
                        resolve(loadOrder);
                    });
                }).then(function (modules) {
                    if (init)return;
                    _modules = modules;
                    _modules.forEach(module=>module.load(_api, config[module.getName()]));
                    log.info(`${_modules.length} modules loaded. beginning startup`)
                }).then(function () {
                    log.startSpinner("Initializing Modules %s");
                }).then(function (spinner) {
                    return _api.emit("init");
                }).then(function (spinner) {
                    log.stopSpinner();
                }).then(function () {
                    log.info("Startup complete");
                    if (confStr != JSON.stringify(config)) {
                        log.info("Change in Modules detected. Saving config.json");
                        fs.writeFileSync(path.join(cwd, "config.json"), JSON.stringify(config, null, 2));
                    }
                })
                .catch(function (e) {
                    log.error("Error in startup routine:", e);
                });
        }

    };
};

module.exports = function (cwd = path.dirname(module.parent.filename), init = false) {
    moin = moin(cwd, init);
    return moin.run().then(()=>moin.getApi());
};<|endoftext|>


<commit_before>//pango.js

function GameObj(options){
  this.pos=options.pos||[0,0,0];
  //position             x,y,z
  this.scl=options.scl||[1,1,1];
  //scale                x,y,z
  this.rot=options.rot||[0,0,0];

  this.children=options.children||[];

}

function Entity(options){
}
<commit_msg>defined some classes, none of which have function yet<commit_after>//pango.js

//z is up

var GameObj=function(options){
  this.pos=options.pos||[0,0,0];
  //position             x,y,z
  this.rot=options.rot||[0,0,0];
  //rotation
  this.children=options.children||[];
}

var Entity=function(options){

  this.scl=options.scl||[1,1,1];
  //scale                x,y,z

  this.doesRender=options.doesRender||true;
  this.mesh=options.mesh||undefined;
  this.material=options.material||undefined;
  //all must return true to render

  this.doesCollide=options.doesCollide||true;
  this.collider=options.collider||undefined;
  //leave undefined for no collision
}
inherit(Entity,GameObj);

var PointLight=function(options){
  this.brightness=options.brightness||100;
  this.color=options.color;
  //TODO: find if three.js wants [1,1,1] or '#FFFFFF'

  this.range=options.range||5;
  //i think this is a thing three will want?
}
inherit(PointLight,GameObj);

var SpotLight=function(options){
  this.brightness=options.brightness||100;
  this.color=options.color;
  //TODO: find if three.js wants [1,1,1] or '#FFFFFF'
  this.fov=options.fov||30;
  this.range=options.range||5;
  //i think this is a thing three will want?
}
inherit(SpotLight,GameObj);

var inherit = function (child, parent) {
  //http://www.sitepoint.com/simple-inheritance-javascript/
    child.prototype = Object.create(parent.prototype);
};
<|endoftext|>


<commit_before>'use strict';

var Likely = require('./widget');
var config = require('./config');
var utils = require('./utils');
var dom = require('./dom');
var history = require('./history');

/**
 * @param {Node} node
 * @param {Object} options
 * @private
 * @returns {Likely}
 */
var initWidget = function (node, options) {
    var fullOptions = options || {};
    var defaults = {
        counters: true,
        timeout: 1e3,
        zeroes: false,
        title: document.title,
        wait: 0.5e3,
        url: utils.getDefaultUrl(),
    };
    var widget = node[config.name];

    if (widget) {
        widget.update(fullOptions);
    }
    else {
        node[config.name] = new Likely(node, utils.merge(
            {}, defaults,
            fullOptions, utils.bools(node)
        ));
    }

    return widget;
};

var initLikely = function (nodes, options) {
    var realNodes;
    var realOptions;

    if (Array.isArray(nodes)) {
        // An array of nodes was passed
        realNodes = nodes;
        realOptions = options;
    }
    else if (nodes instanceof Node) {
        // A single node was passed
        realNodes = [nodes];
        realOptions = options;
    }
    else {
        // Options were passed, or null/undefined was passed, or the function was called without arguments
        realNodes = dom.findAll('.' + config.name);
        realOptions = options || nodes;
    }

    realNodes.forEach(function (node) {
        initWidget(node, realOptions);
    });
};

/**
 * @deprecated
 * @returns {Likely}
 */
var likely = function () {
    // eslint-disable-next-line no-console
    console.warn('likely function is DEPRECATED and will be removed in 3.0. Use likely.initiate instead.');
    return likely.initiate.apply(likely, arguments);
};

/**
 * Initiate Likely buttons on load
 * @param {Node|Array<Node>|Object} [nodes] a particular node or an array of widgets,
 *                                     if not specified,
 *                                     tries to init all the widgets
 * @param {Object} [options] additional options for each widget
 */
likely.initiate = function (nodes, options) {
    initLikely(nodes, options);

    history.onUrlChange(function () {
        initLikely(nodes, utils.extend({
            forceUpdate: true,
            url: utils.getDefaultUrl(),
        }, options));
    });
};

likely.initate = function () {
    // eslint-disable-next-line no-console
    console.warn('likely.initate function is DEPRECATED and will be removed in 3.0. Use likely.initiate instead.');
    return likely.initiate.apply(likely, arguments);
};

module.exports = likely;
<commit_msg>Reorder the likely methods<commit_after>'use strict';

var Likely = require('./widget');
var config = require('./config');
var utils = require('./utils');
var dom = require('./dom');
var history = require('./history');

/**
 * @param {Node} node
 * @param {Object} options
 * @private
 * @returns {Likely}
 */
var initWidget = function (node, options) {
    var fullOptions = options || {};
    var defaults = {
        counters: true,
        timeout: 1e3,
        zeroes: false,
        title: document.title,
        wait: 0.5e3,
        url: utils.getDefaultUrl(),
    };
    var widget = node[config.name];

    if (widget) {
        widget.update(fullOptions);
    }
    else {
        node[config.name] = new Likely(node, utils.merge(
            {}, defaults,
            fullOptions, utils.bools(node)
        ));
    }

    return widget;
};

var initLikely = function (nodes, options) {
    var realNodes;
    var realOptions;

    if (Array.isArray(nodes)) {
        // An array of nodes was passed
        realNodes = nodes;
        realOptions = options;
    }
    else if (nodes instanceof Node) {
        // A single node was passed
        realNodes = [nodes];
        realOptions = options;
    }
    else {
        // Options were passed, or null/undefined was passed, or the function was called without arguments
        realNodes = dom.findAll('.' + config.name);
        realOptions = options || nodes;
    }

    realNodes.forEach(function (node) {
        initWidget(node, realOptions);
    });
};

/**
 * @deprecated
 * @returns {Likely}
 */
var likely = function () {
    // eslint-disable-next-line no-console
    console.warn('likely function is DEPRECATED and will be removed in 3.0. Use likely.initiate instead.');
    return likely.initiate.apply(likely, arguments);
};

likely.initate = function () {
    // eslint-disable-next-line no-console
    console.warn('likely.initate function is DEPRECATED and will be removed in 3.0. Use likely.initiate instead.');
    return likely.initiate.apply(likely, arguments);
};

/**
 * Initiate Likely buttons on load
 * @param {Node|Array<Node>|Object} [nodes] a particular node or an array of widgets,
 *                                     if not specified,
 *                                     tries to init all the widgets
 * @param {Object} [options] additional options for each widget
 */
likely.initiate = function (nodes, options) {
    initLikely(nodes, options);

    history.onUrlChange(function () {
        initLikely(nodes, utils.extend({
            forceUpdate: true,
            url: utils.getDefaultUrl(),
        }, options));
    });
};

module.exports = likely;
<|endoftext|>


<commit_before>module.exports = UI;

function UI(store, target) {
  if (!(this instanceof UI)) return new UI(store, target);
  this.store = store;
  this.target = target || document.body;
}

UI.prototype = {
  open: function() {
    var el = this._el;
    if (!el) {
      el = this._el = this.render();
      this.target.appendChild(el);
      require.ensure(['./lib/draggable', '!!style-loader!css-loader!./canary.css'], function(require) {
        require('!!style-loader!css-loader!./canary.css');
        (require('./lib/draggable'))(el);
      });
    }
    el.style.display = '';
    return this;
  },
  close: function() {
    this._el.style.display = 'none';
    return this;
  },
  render: function() {
    var store = this.store;
    var list = this._ul(store);

    return DOM('div', {
      id: 'canary-ui'
    }, [
      this._reset(store),
      this._close(store),
      this._minimize(store),
      list
    ]);
  },
  hashchange: function() {
    var self = this;
    self._onhashchange(location.hash);
    window.addEventListener('hashchange', function() {
      self._onhashchange(location.hash);
    }, false);
    return self;
  },
  _onhashchange: function(hash) {
    if (hash.indexOf('#canary') !== 0) return;
    this.open();
    var parts = hash.split('=');
    try {
      var overrides = JSON.parse(parts[1] || '{}');
      for (var k in overrides) {
        this.store.override(k, overrides[k]);
      }
    } catch(e) {}
  },
  _reset: function(store) {
    return a('reset', 'reset', function() {
      store.reset();
    });
  },
  _close: function(store) {
    var self = this;
    return a('action close', '×', function() {
      self.close();
    });
  },
  _minimize: function(store) {
    var self = this;
    var minimize = a('action minimize', '_', function() {
      var el = self._el;
      var minimized = el.className === 'minimized';
      el.className = minimized ? '' : 'minimized';
      minimize.innerText = minimized ? '_' : '+';
    });
    return minimize;
  },
  _ul: function(store) {
    var self = this;
    var ul = DOM('ul');

    function onChange() {
      store.features().forEach(function(feature) {
        ul.appendChild(self._li(feature));
      });
    }

    store.on('change', function() {
      ul.innerHTML = '';
      onChange();
    });

    onChange();

    return ul;
  },
  _li: function(feature) {
    return DOM('li', {}, [
      DOM('label', {}, [
        DOM('span', {innerText: feature.name}),
        this._input(feature)
      ])
    ]);
  },
  _input: function(feature) {
    var variants = feature.variants;
    return variants.length === 2 && typeof variants[0].value === 'boolean' ?
      this._checkbox(feature) :
      this._select(feature);
  },
  _checkbox: function(feature) {
    var el = DOM('input', {
      type: 'checkbox',
      checked: feature.selected,
      onchange: function() {
        feature.set(!!el.checked);
      }
    });
    return el;
  },
  _select: function(feature) {
    var el = DOM('select', {
      onchange: function() {
        feature.set(el.value);
      }
    }, feature.variants.map(function(variant) {
      return DOM('option', {
        value: variant.value,
        selected: variant.isSelected,
        innerText: variant.value
      })
    }));
    return el;
  }
};

function a(className, text, onclick) {
  return DOM('a', {
    className: className,
    innerText: text,
    href: 'javascript:;',
    onclick: function(evt) {
      onclick(evt)
      return false;
    }
  });
}

function DOM(name, props, children) {
  var el = document.createElement(name);
  props = props || {};
  children = children || [];
  for (var k in props) {
    el[k] = props[k]
  }
  children.forEach(function(child) {
    el.appendChild(child);
  });
  return el;
}
<commit_msg>setTimeout on hashchange<commit_after>module.exports = UI;

function UI(store, target) {
  if (!(this instanceof UI)) return new UI(store, target);
  this.store = store;
  this.target = target || document.body;
}

UI.prototype = {
  open: function() {
    var el = this._el;
    if (!el) {
      el = this._el = this.render();
      this.target.appendChild(el);
      require.ensure(['./lib/draggable', '!!style-loader!css-loader!./canary.css'], function(require) {
        require('!!style-loader!css-loader!./canary.css');
        (require('./lib/draggable'))(el);
      });
    }
    el.style.display = '';
    return this;
  },
  close: function() {
    this._el.style.display = 'none';
    return this;
  },
  render: function() {
    var store = this.store;
    var list = this._ul(store);

    return DOM('div', {
      id: 'canary-ui'
    }, [
      this._reset(store),
      this._close(store),
      this._minimize(store),
      list
    ]);
  },
  hashchange: function() {
    var self = this;
    function onChange() {
      self._onhashchange(location.hash);
    }
    setTimeout(onChange, 1000);
    window.addEventListener('hashchange', onChange);
    return self;
  },
  _onhashchange: function(hash) {
    if (hash.indexOf('#canary') !== 0) return;
    this.open();
    var parts = hash.split('=');
    try {
      var overrides = JSON.parse(parts[1] || '{}');
      for (var k in overrides) {
        this.store.override(k, overrides[k]);
      }
    } catch(e) {}
  },
  _reset: function(store) {
    return a('reset', 'reset', function() {
      store.reset();
    });
  },
  _close: function(store) {
    var self = this;
    return a('action close', '×', function() {
      self.close();
    });
  },
  _minimize: function(store) {
    var self = this;
    var minimize = a('action minimize', '_', function() {
      var el = self._el;
      var minimized = el.className === 'minimized';
      el.className = minimized ? '' : 'minimized';
      minimize.innerText = minimized ? '_' : '+';
    });
    return minimize;
  },
  _ul: function(store) {
    var self = this;
    var ul = DOM('ul');

    function onChange() {
      store.features().forEach(function(feature) {
        ul.appendChild(self._li(feature));
      });
    }

    store.on('change', function() {
      ul.innerHTML = '';
      onChange();
    });

    onChange();

    return ul;
  },
  _li: function(feature) {
    return DOM('li', {}, [
      DOM('label', {}, [
        DOM('span', {innerText: feature.name}),
        this._input(feature)
      ])
    ]);
  },
  _input: function(feature) {
    var variants = feature.variants;
    return variants.length === 2 && typeof variants[0].value === 'boolean' ?
      this._checkbox(feature) :
      this._select(feature);
  },
  _checkbox: function(feature) {
    var el = DOM('input', {
      type: 'checkbox',
      checked: feature.selected,
      onchange: function() {
        feature.set(!!el.checked);
      }
    });
    return el;
  },
  _select: function(feature) {
    var el = DOM('select', {
      onchange: function() {
        feature.set(el.value);
      }
    }, feature.variants.map(function(variant) {
      return DOM('option', {
        value: variant.value,
        selected: variant.isSelected,
        innerText: variant.value
      })
    }));
    return el;
  }
};

function a(className, text, onclick) {
  return DOM('a', {
    className: className,
    innerText: text,
    href: 'javascript:;',
    onclick: function(evt) {
      onclick(evt)
      return false;
    }
  });
}

function DOM(name, props, children) {
  var el = document.createElement(name);
  props = props || {};
  children = children || [];
  for (var k in props) {
    el[k] = props[k]
  }
  children.forEach(function(child) {
    el.appendChild(child);
  });
  return el;
}
<|endoftext|>


<commit_before>//pango.js

function Entity(options){
}
<commit_msg>updated gameobject<commit_after>//pango.js

function GameObj(options){
  this.pos=options.pos||[0,0,0];
  //position             x,y,z
  this.scl=options.scl||[1,1,1];
  //scale                x,y,z
  this.rot=options.rot||[0,0,0];

  this.children=options.children||[];

}

function Entity(options){
}
<|endoftext|>


<commit_before>/* global window, require */
'use strict';

window.b8r = require('./b8r.js');
<commit_msg>remove index.js<commit_after><|endoftext|>


<commit_before>/*!
 * question-cache <https://github.com/jonschlinkert/question-cache>
 *
 * Copyright (c) 2015, Jon Schlinkert.
 * Licensed under the MIT License.
 */

'use strict';

var utils = require('./lib/utils');

/**
 * Create an instance of `Questions` with the
 * given `options`.
 *
 * ```js
 * var inquirer = require('inquirer')
 * var questions = new Questions({inquirer: inquirer});
 * ```
 *
 * @param {Object} `options` Pass your instance of [inquirer] on the `inquirer` option.
 * @api public
 */

function Questions(options) {
  if (!(this instanceof Questions)) {
    return new Questions(options);
  }
  if (isObject(options) && 'prompt' in options) {
    options = {inquirer: options};
  }

  this.options = options || {};
  var inquirer = this.options.inquirer;
  if (typeof inquirer === 'undefined') {
    inquirer = utils.inquirer;
  }

  define(this, 'inquirer', inquirer);
  delete this.options.inquirer;
  this.cache = {};
  this.queue = [];
}

/**
 * Store a question object by `key`.
 *
 * ```js
 * questions.set('name', {
 *   type: 'input',
 *   message: 'Project name?',
 *   default: 'undefined'
 * });
 * ```
 *
 * @param {String} `key` Unique question id.
 * @param {Object} `value` Question object that follows [inquirer] conventions.
 * @api public
 */

Questions.prototype.set = function(key, value) {
  if (typeof key === 'undefined') {
    throw new TypeError('expected set to be a string or object.');
  }

  if (typeof key === 'object') {
    value = key;
    key = value.name;
  }

  if (typeof value === 'string') {
    value = {message: value};
  } else if (typeof key === 'string' && !value) {
    value = {message: addQmark(key)};
  }

  value = value || {};
  if (isObject(key)) {
    value = utils.merge({}, value, key);
  }

  value.type = value.type || 'input';
  value.name = value.name || value.key || key;

  utils.set(this.cache, key, value);
  this.queue.push(value);
  return this;
};

/**
 * Get a question by `key`.
 *
 * ```js
 * questions.get('name');
 * //=> {type: 'input', message: 'What is your name?', default: ''}
 * ```
 *
 * @param {String} `key` Unique question id.
 * @param {Object} `value` Question object that follows [inquirer] conventions.
 * @api public
 */

Questions.prototype.get = function(key) {
  return utils.get(this.cache, key);
};

/**
 * Return true if the given question name is stored on
 * question-cache.
 *
 * ```js
 * var exists = questions.has('name');
 * //=> true or false
 * ```
 *
 * @param {String} `key` Unique question id.
 * @param {Object} `value` Question object that follows [inquirer] conventions.
 * @api public
 */

Questions.prototype.has = function(key) {
  return utils.has(this.cache, key);
};

/**
 * Returns an array of question objects from an array of keys. Keys
 * may use dot notation.
 *
 * @param  {Array} `keys` Question names or object paths.
 * @return {Array} Array of question objects.
 * @api public
 */

Questions.prototype.resolve = function(keys) {
  keys = arrayify(keys);
  var len = keys.length, i = -1;
  var questions = [];

  while (++i < len) {
    var question = {};
    var key = keys[i];

    if (typeof key === 'string') {
      question = this.get(key);
    } else if (isObject(key)) {
      question = this.normalizeObject(key);
    }

    if (!question) {
      question = this.toQuestion(key);
    }

    if (question.hasOwnProperty('type')) {
      questions.push(question);
      continue;
    }

    for (var prop in question) {
      this.set(prop, question[prop]);
      var val = this.get(prop);

      if (question.hasOwnProperty(prop)) {
        questions.push(val);
      }
    }
  }
  return questions;
};

/**
 * Normalize questions into a consistent object format
 * following [inquirer][] conventions.
 *
 * @param {Object} `questions`
 * @param {Object} `options`
 * @return {Object}
 */

Questions.prototype.normalizeObject = function(questions) {
  var res = [];

  for (var key in questions) {
    if (questions.hasOwnProperty(key)) {
      var val = questions[key];
      var question;

      if (typeof val === 'string') {
        question = this.toQuestion(key, val);

      } else if (typeof val === 'object') {
        question = this.toQuestion(key, val);
      }

      if (question) res = res.concat(question);
    }
  }
  return res;
};

/**
 * Create a question object from a string. Uses the `input` question type,
 * and does the following basic normalization:
 *
 *   - when `foo` is passed, a `?` is added to the question. e.g. `foo?`
 *   - when `foo?` is passed, `?` is removed on the question key, so the answer to `foo?` is
 *   `{foo: 'bar'}`
 *
 * @param  {String} `key`
 * @return {Object} Returns a question object.
 * @api public
 */

Questions.prototype.toQuestion = function(key, value) {
  var obj = {};
  if (isReserved(key) && typeof value === 'string') {
    obj[key] = value;

  } else if (typeof key === 'string') {
    obj.name = key;

  } else if (typeof value === 'string') {
    obj.message = value;
  }
  if (isObject(value)) {
    obj = utils.merge({}, obj, value);
  }
  obj.name = stripQmark(obj.name || key);
  if (!obj.message) {
    obj.message = addQmark(obj.name);
  }
  obj.type = obj.type || 'input';
  return obj;
};

/**
 * Ask a question or array of questions.
 *
 * ```js
 * questions.ask(['name', 'homepage']);
 * //=> { name: 'foo', homepage: 'https://github/foo' }
 * ```
 *
 * @param {String} `key` Unique question id.
 * @param {Object} `value` Question object that follows [inquirer] conventions.
 * @api public
 */

Questions.prototype.ask = function(keys, cb) {
  if (isObject(keys)) keys = [keys];

  var questions = [];
  if (typeof keys === 'function') {
    cb = keys;
    questions = this.queue;
  } else {
    questions = this.resolve(keys);
  }

  if (questions.length === 0) {
    return cb(new Error('no questions found.'));
  }

  try {
    this.prompt(questions, function(answers) {
      cb(null, setEach({}, answers));
    });
  } catch(err) {
    cb(err);
  }
};

/**
 * Exposes the `prompt` method on [inquirer] as a convenience.
 *
 * ```js
 * questions.prompt({
 *   type: 'list',
 *   name: 'chocolate',
 *   message: 'What\'s your favorite chocolate?',
 *   choices: ['Mars', 'Oh Henry', 'Hershey']
 * }, function(answers) {
 *   //=> {chocolate: 'Hershey'}
 * });
 * ```
 *
 * @param {Object|Array} `question` Question object or array of question objects.
 * @param {Object} `callback` Callback function.
 * @api public
 */

Questions.prototype.prompt = function() {
  return this.inquirer.prompt.apply(this.inquirer, arguments);
};

/**
 * Utility for setting values on properties defined using
 * dot notation (object paths).
 *
 * @param {object} `obj` Object to store values on.
 * @param {object} `answers` Answers object.
 */

function setEach(obj, answers) {
  for (var key in answers) {
    if (answers.hasOwnProperty(key)) {
      utils.set(obj, key, answers[key]);
    }
  }
  return obj;
}

function addQmark(str) {
  if (str && str.slice(-1) !== '?') {
    return str + '?';
  }
  return str;
}

function stripQmark(str) {
  if (str && str.slice(-1) === '?') {
    return str.slice(0, -1);
  }
  return str;
}

function isReserved(key) {
  return ['name', 'input', 'message'].indexOf(key) > -1;
}

/**
 * Utility for casting a value to an array.
 */

function arrayify(val) {
  return val ? (Array.isArray(val) ? val : [val]) : [];
}

/**
 * Utility for casting a value to an array.
 */

function isObject(val) {
  return utils.typeOf(val) === 'object';
}

/**
 * Utility for definining a non-enumerable property.
 */

function define(obj, prop, val) {
  Object.defineProperty(obj, prop, {
    configurable: true,
    enumerable: false,
    writable: true,
    value: val
  });
}

/**
 * Expose `Questions`
 */

module.exports = Questions;
<commit_msg>fix fallback inquirer<commit_after>/*!
 * question-cache <https://github.com/jonschlinkert/question-cache>
 *
 * Copyright (c) 2015, Jon Schlinkert.
 * Licensed under the MIT License.
 */

'use strict';

var utils = require('./lib/utils');

/**
 * Create an instance of `Questions` with the
 * given `options`.
 *
 * ```js
 * var inquirer = require('inquirer')
 * var questions = new Questions({inquirer: inquirer});
 * ```
 *
 * @param {Object} `options` Pass your instance of [inquirer] on the `inquirer` option.
 * @api public
 */

function Questions(options) {
  if (!(this instanceof Questions)) {
    return new Questions(options);
  }
  if (isObject(options) && 'prompt' in options) {
    options = {inquirer: options};
  }

  this.options = options || {};
  var inquirer = this.options.inquirer;
  if (typeof inquirer === 'undefined') {
    inquirer = utils.inquirer();
  }

  define(this, 'inquirer', inquirer);
  delete this.options.inquirer;
  this.cache = {};
  this.queue = [];
}

/**
 * Store a question object by `key`.
 *
 * ```js
 * questions.set('name', {
 *   type: 'input',
 *   message: 'Project name?',
 *   default: 'undefined'
 * });
 * ```
 *
 * @param {String} `key` Unique question id.
 * @param {Object} `value` Question object that follows [inquirer] conventions.
 * @api public
 */

Questions.prototype.set = function(key, value) {
  if (typeof key === 'undefined') {
    throw new TypeError('expected set to be a string or object.');
  }

  if (typeof key === 'object') {
    value = key;
    key = value.name;
  }

  if (typeof value === 'string') {
    value = {message: value};
  } else if (typeof key === 'string' && !value) {
    value = {message: addQmark(key)};
  }

  value = value || {};
  if (isObject(key)) {
    value = utils.merge({}, value, key);
  }

  value.type = value.type || 'input';
  value.name = value.name || value.key || key;

  utils.set(this.cache, key, value);
  this.queue.push(value);
  return this;
};

/**
 * Get a question by `key`.
 *
 * ```js
 * questions.get('name');
 * //=> {type: 'input', message: 'What is your name?', default: ''}
 * ```
 *
 * @param {String} `key` Unique question id.
 * @param {Object} `value` Question object that follows [inquirer] conventions.
 * @api public
 */

Questions.prototype.get = function(key) {
  return utils.get(this.cache, key);
};

/**
 * Return true if the given question name is stored on
 * question-cache.
 *
 * ```js
 * var exists = questions.has('name');
 * //=> true or false
 * ```
 *
 * @param {String} `key` Unique question id.
 * @param {Object} `value` Question object that follows [inquirer] conventions.
 * @api public
 */

Questions.prototype.has = function(key) {
  return utils.has(this.cache, key);
};

/**
 * Returns an array of question objects from an array of keys. Keys
 * may use dot notation.
 *
 * @param  {Array} `keys` Question names or object paths.
 * @return {Array} Array of question objects.
 * @api public
 */

Questions.prototype.resolve = function(keys) {
  keys = arrayify(keys);
  var len = keys.length, i = -1;
  var questions = [];

  while (++i < len) {
    var question = {};
    var key = keys[i];

    if (typeof key === 'string') {
      question = this.get(key);
    } else if (isObject(key)) {
      question = this.normalizeObject(key);
    }

    if (!question) {
      question = this.toQuestion(key);
    }

    if (question.hasOwnProperty('type')) {
      questions.push(question);
      continue;
    }

    for (var prop in question) {
      this.set(prop, question[prop]);
      var val = this.get(prop);

      if (question.hasOwnProperty(prop)) {
        questions.push(val);
      }
    }
  }
  return questions;
};

/**
 * Normalize questions into a consistent object format
 * following [inquirer][] conventions.
 *
 * @param {Object} `questions`
 * @param {Object} `options`
 * @return {Object}
 */

Questions.prototype.normalizeObject = function(questions) {
  var res = [];

  for (var key in questions) {
    if (questions.hasOwnProperty(key)) {
      var val = questions[key];
      var question;

      if (typeof val === 'string') {
        question = this.toQuestion(key, val);

      } else if (typeof val === 'object') {
        question = this.toQuestion(key, val);
      }

      if (question) res = res.concat(question);
    }
  }
  return res;
};

/**
 * Create a question object from a string. Uses the `input` question type,
 * and does the following basic normalization:
 *
 *   - when `foo` is passed, a `?` is added to the question. e.g. `foo?`
 *   - when `foo?` is passed, `?` is removed on the question key, so the answer to `foo?` is
 *   `{foo: 'bar'}`
 *
 * @param  {String} `key`
 * @return {Object} Returns a question object.
 * @api public
 */

Questions.prototype.toQuestion = function(key, value) {
  var obj = {};
  if (isReserved(key) && typeof value === 'string') {
    obj[key] = value;

  } else if (typeof key === 'string') {
    obj.name = key;

  } else if (typeof value === 'string') {
    obj.message = value;
  }
  if (isObject(value)) {
    obj = utils.merge({}, obj, value);
  }
  obj.name = stripQmark(obj.name || key);
  if (!obj.message) {
    obj.message = addQmark(obj.name);
  }
  obj.type = obj.type || 'input';
  return obj;
};

/**
 * Ask a question or array of questions.
 *
 * ```js
 * questions.ask(['name', 'homepage']);
 * //=> { name: 'foo', homepage: 'https://github/foo' }
 * ```
 *
 * @param {String} `key` Unique question id.
 * @param {Object} `value` Question object that follows [inquirer] conventions.
 * @api public
 */

Questions.prototype.ask = function(keys, cb) {
  if (isObject(keys)) keys = [keys];

  var questions = [];
  if (typeof keys === 'function') {
    cb = keys;
    questions = this.queue;
  } else {
    questions = this.resolve(keys);
  }

  if (questions.length === 0) {
    return cb(new Error('no questions found.'));
  }

  try {
    this.prompt(questions, function(answers) {
      cb(null, setEach({}, answers));
    });
  } catch(err) {
    cb(err);
  }
};

/**
 * Exposes the `prompt` method on [inquirer] as a convenience.
 *
 * ```js
 * questions.prompt({
 *   type: 'list',
 *   name: 'chocolate',
 *   message: 'What\'s your favorite chocolate?',
 *   choices: ['Mars', 'Oh Henry', 'Hershey']
 * }, function(answers) {
 *   //=> {chocolate: 'Hershey'}
 * });
 * ```
 *
 * @param {Object|Array} `question` Question object or array of question objects.
 * @param {Object} `callback` Callback function.
 * @api public
 */

Questions.prototype.prompt = function() {
  return this.inquirer.prompt.apply(this.inquirer, arguments);
};

/**
 * Utility for setting values on properties defined using
 * dot notation (object paths).
 *
 * @param {object} `obj` Object to store values on.
 * @param {object} `answers` Answers object.
 */

function setEach(obj, answers) {
  for (var key in answers) {
    if (answers.hasOwnProperty(key)) {
      utils.set(obj, key, answers[key]);
    }
  }
  return obj;
}

function addQmark(str) {
  if (str && str.slice(-1) !== '?') {
    return str + '?';
  }
  return str;
}

function stripQmark(str) {
  if (str && str.slice(-1) === '?') {
    return str.slice(0, -1);
  }
  return str;
}

function isReserved(key) {
  return ['name', 'input', 'message'].indexOf(key) > -1;
}

/**
 * Utility for casting a value to an array.
 */

function arrayify(val) {
  return val ? (Array.isArray(val) ? val : [val]) : [];
}

/**
 * Utility for casting a value to an array.
 */

function isObject(val) {
  return utils.typeOf(val) === 'object';
}

/**
 * Utility for definining a non-enumerable property.
 */

function define(obj, prop, val) {
  Object.defineProperty(obj, prop, {
    configurable: true,
    enumerable: false,
    writable: true,
    value: val
  });
}

/**
 * Expose `Questions`
 */

module.exports = Questions;
<|endoftext|>


<commit_before>//Adapted from: http://itblog.mobi/2015/12/29/how-to-create-a-simple-restful-api-with-node-js/

var express = require("express");
var app = express();

app.use(express.static('coloradodemography.github.io/_site'));

app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});

var routes = require("./routes/routes.js")(app);

//Handle 404
app.use(function(req, res) {
    res.send(404, 'Page not found');
});

var server = app.listen(4008, function() {
    console.log("Listening on port %s...", server.address().port);
});
  <commit_msg>rollback<commit_after>//Adapted from: http://itblog.mobi/2015/12/29/how-to-create-a-simple-restful-api-with-node-js/

var express = require("express");
var app = express();

app.use(express.static('coloradodemography.github.io/_site'));

app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});

var routes = require("./routes/routes.js")(app);

//Handle 404
// app.use(function(req, res) {
//     res.send(404, 'Page not found');
// });

var server = app.listen(4008, function() {
    console.log("Listening on port %s...", server.address().port);
});
  <|endoftext|>


<commit_before>exports.none = Object.create({
    value: function() {
        throw new Error('Called value on none');
    },
    isNone: function(){
        return true;
    },
    isSome: function(){
        return false;
    },
    map: function() {
        return exports.none;
    },
    toArray: function() {
        return [];
    },
    orElse: callOrReturn,
    valueOrElse: callOrReturn
});

function callOrReturn(value) {
    if (typeof(value) == "function") {
        return value();
    } else {
        return value;
    }
}

exports.some = function(value) {
    return new Some(value);
};

var Some = function(value) {
    this._value = value;
};

Some.prototype.value = function() {
    return this._value;
};

Some.prototype.isNone = function(){
    return false;
};

Some.prototype.isSome = function(){
    return true;
};

Some.prototype.map = function(func) {
    return new Some(func(this._value));
};

Some.prototype.toArray = function() {
    return [this._value];
};

Some.prototype.orElse = function(value) {
    return this;
};

Some.prototype.valueOrElse = function(value) {
    return this._value;
};

exports.isOption = function(value) {
    return value === exports.none || value instanceof Some;
};

exports.fromNullable = function(value) {
    if (value == null) {
        return exports.none;
    }
    return new Some(value);
}
<commit_msg>Consistency spacing formatting<commit_after>exports.none = Object.create({
    value: function() {
        throw new Error('Called value on none');
    },
    isNone: function() {
        return true;
    },
    isSome: function() {
        return false;
    },
    map: function() {
        return exports.none;
    },
    toArray: function() {
        return [];
    },
    orElse: callOrReturn,
    valueOrElse: callOrReturn
});

function callOrReturn(value) {
    if (typeof(value) == "function") {
        return value();
    } else {
        return value;
    }
}

exports.some = function(value) {
    return new Some(value);
};

var Some = function(value) {
    this._value = value;
};

Some.prototype.value = function() {
    return this._value;
};

Some.prototype.isNone = function() {
    return false;
};

Some.prototype.isSome = function() {
    return true;
};

Some.prototype.map = function(func) {
    return new Some(func(this._value));
};

Some.prototype.toArray = function() {
    return [this._value];
};

Some.prototype.orElse = function(value) {
    return this;
};

Some.prototype.valueOrElse = function(value) {
    return this._value;
};

exports.isOption = function(value) {
    return value === exports.none || value instanceof Some;
};

exports.fromNullable = function(value) {
    if (value == null) {
        return exports.none;
    }
    return new Some(value);
}
<|endoftext|>


<commit_before>#! /usr/bin/env node
var program = require('commander');
program
  .arguments('<word>')
  .option('-i, --image', 'Search Image on Google')
  .option('-n, --news', 'Search News on Google')
  .option('-v, --video', 'Search Video on Google')

  .action(function(word) {
    var exec = require('child_process').exec;
    var cmd = "open https://google.com/#q=" + word;

    let base = "open \'https://google.com/search?q="
    if (program.image) {
      cmd = base + word + "&tbm=isch\'"
      exec(cmd, function(error, stdout, stderr) {});
    } else if (program.news) {
      cmd = base + word + "&tbm=nws\'"
      exec(cmd, function(error, stdout, stderr) {});
    } else if (program.video) {
      cmd = base + word + "&tbm=vid\'"
      exec(cmd, function(error, stdout, stderr) {});
    } else {
      exec(cmd, function(error, stdout, stderr) {});
    }
  })
 .parse(process.argv);
// Comment
<commit_msg>Delete comment<commit_after>#! /usr/bin/env node
var program = require('commander');
program
  .arguments('<word>')
  .option('-i, --image', 'Search Image on Google')
  .option('-n, --news', 'Search News on Google')
  .option('-v, --video', 'Search Video on Google')

  .action(function(word) {
    var exec = require('child_process').exec;
    var cmd = "open https://google.com/#q=" + word;

    let base = "open \'https://google.com/search?q="
    if (program.image) {
      cmd = base + word + "&tbm=isch\'"
      exec(cmd, function(error, stdout, stderr) {});
    } else if (program.news) {
      cmd = base + word + "&tbm=nws\'"
      exec(cmd, function(error, stdout, stderr) {});
    } else if (program.video) {
      cmd = base + word + "&tbm=vid\'"
      exec(cmd, function(error, stdout, stderr) {});
    } else {
      exec(cmd, function(error, stdout, stderr) {});
    }
  })
 .parse(process.argv);
<|endoftext|>


<commit_before>var request = require('request')
  , reqOpts = {
      uri : 'http://html5.validator.nu',
      qs: {}
    };

module.exports = function(opts, callback){

  if(!opts.url){
    return callback(new Error('Missing required option: url'), null);
  } else {
    reqOpts.qs.doc = opts.url;
  }

  if(opts.format){
    reqOpts.qs.out = opts.format;
  }

  request(reqOpts, function(error, response, body){

    if(error){
      return callback(error, null);
    }

    var data = opts.format == 'json' ? JSON.parse(body) : body;

    return callback(null, data);

  });
};<commit_msg>Tiny fix<commit_after>var request = require('request')
  , reqOpts = {uri : 'http://html5.validator.nu', qs : {}};

module.exports = function(opts, callback){

  if(!opts.url){
    return callback(new Error('Missing required option: url'), null);
  } else {
    reqOpts.qs.doc = opts.url;
  }

  if(opts.format){
    reqOpts.qs.out = opts.format;
  }

  request(reqOpts, function(error, response, body){

    if(error){
      return callback(error, null);
    }

    var data = opts.format == 'json' ? JSON.parse(body) : body;

    return callback(null, data);

  });
};<|endoftext|>


<commit_before>let dhttp = require('dhttp')
let typeforce = require('typeforce')

// global used to prevent duplicates
let rpcCount = 0

function RPCClient (opts) {
  let { auth, pass, user, url } = opts
  if (!url) throw new TypeError('Expected RPC opts.url, got ' + url)

  if (auth) {
    this.auth = {
      'Authorization': 'Basic ' + Buffer.from(`${auth}`, 'utf8').toString('base64')
    }
  } else if (pass !== undefined || user !== undefined) {
    this.auth = {
      'Authorization': 'Basic ' + Buffer.from(`${user}:${pass}`, 'utf8').toString('base64')
    }
  }

  this.url = url
}

let RPC_MESSAGE_TYPE = typeforce.compile({
  method: typeforce.String,
  params: typeforce.Array,
  callback: typeforce.maybe(typeforce.Function)
})

RPCClient.prototype.batch = function (batch, done) {
  typeforce(typeforce.arrayOf(RPC_MESSAGE_TYPE), batch)

  let startCount = rpcCount
  let body = batch.map((x, i) => {
    return Object.assign({ id: startCount + i }, x)
  })

  if (body.length === 0) return done()

  // overflows at UINT32
  rpcCount = (rpcCount + body.length) | 0

  dhttp({
    url: this.url,
    method: 'POST',
    body,
    headers: this.auth
  }, (err, res) => {
    let responseMap = {}

    if (!err && (res.statusCode === 401)) err = new Error('Unauthorized')
    if (!err && res.body) {
      if (!Array.isArray(res.body)) {
        res.body = [res.body]
      }

      res.body.forEach((ibody) => {
        let error, id, result
        if (typeof ibody === 'string') {
          error = ibody
        } else {
          error = ibody.error
          id = ibody.id
          result = ibody.result
        }

        responseMap[id] = { error, result }
      })
    }

    batch.forEach(({ callback }, i) => {
      if (err) return callback(err)

      let rpcResult = responseMap[startCount + i]
      if (!rpcResult) return callback(new Error('Missing RPC response'))

      // unpack
      let { error, result } = rpcResult
      if (error) return callback(new Error(error.message || error.code))
      if (result === undefined) return callback(new TypeError('Missing RPC result'))

      callback(null, result)
    })

    done(err)
  })
}

RPCClient.prototype.call = function (method, params, callback) {
  typeforce(RPC_MESSAGE_TYPE, { method, params, callback })

  let body = { id: rpcCount, method, params }

  // overflows at UINT32
  rpcCount = (rpcCount + 1) | 0

  dhttp({
    url: this.url,
    method: 'POST',
    body,
    headers: this.auth
  }, (err, res) => {
    if (err) return callback(err)
    if (res.statusCode === 401) return callback(new Error('Unauthorized'))

    // unpack
    let { error, result } = res.body
    if (error) return callback(new Error(error.message || error.code))
    if (result === undefined) return callback(new TypeError('Missing RPC result'))

    callback(null, result)
  })
}

module.exports = RPCClient
<commit_msg>define err, dont bother filling responseMap<commit_after>let dhttp = require('dhttp')
let typeforce = require('typeforce')

// global used to prevent duplicates
let rpcCount = 0

function RPCClient (opts) {
  let { auth, pass, user, url } = opts
  if (!url) throw new TypeError('Expected RPC opts.url, got ' + url)

  if (auth) {
    this.auth = {
      'Authorization': 'Basic ' + Buffer.from(`${auth}`, 'utf8').toString('base64')
    }
  } else if (pass !== undefined || user !== undefined) {
    this.auth = {
      'Authorization': 'Basic ' + Buffer.from(`${user}:${pass}`, 'utf8').toString('base64')
    }
  }

  this.url = url
}

let RPC_MESSAGE_TYPE = typeforce.compile({
  method: typeforce.String,
  params: typeforce.Array,
  callback: typeforce.maybe(typeforce.Function)
})

RPCClient.prototype.batch = function (batch, done) {
  typeforce(typeforce.arrayOf(RPC_MESSAGE_TYPE), batch)

  let startCount = rpcCount
  let body = batch.map((x, i) => {
    return Object.assign({ id: startCount + i }, x)
  })

  if (body.length === 0) return done()

  // overflows at UINT32
  rpcCount = (rpcCount + body.length) | 0

  dhttp({
    url: this.url,
    method: 'POST',
    body,
    headers: this.auth
  }, (err, res) => {
    let responseMap = {}

    if (!err && (res.statusCode === 401)) err = new Error('Unauthorized')
    if (!err && res.body) {
      if (!Array.isArray(res.body)) {
        err = new Error(res.body)
      } else {
        res.body.forEach(({ error, id, result }) => {
          responseMap[id] = { error, result }
        })
      }
    }

    batch.forEach(({ callback }, i) => {
      if (err) return callback(err)

      let rpcResult = responseMap[startCount + i]
      if (!rpcResult) return callback(new Error('Missing RPC response'))

      // unpack
      let { error, result } = rpcResult
      if (error) return callback(new Error(error.message || error.code))
      if (result === undefined) return callback(new TypeError('Missing RPC result'))

      callback(null, result)
    })

    done(err)
  })
}

RPCClient.prototype.call = function (method, params, callback) {
  typeforce(RPC_MESSAGE_TYPE, { method, params, callback })

  let body = { id: rpcCount, method, params }

  // overflows at UINT32
  rpcCount = (rpcCount + 1) | 0

  dhttp({
    url: this.url,
    method: 'POST',
    body,
    headers: this.auth
  }, (err, res) => {
    if (err) return callback(err)
    if (res.statusCode === 401) return callback(new Error('Unauthorized'))

    // unpack
    let { error, result } = res.body
    if (error) return callback(new Error(error.message || error.code))
    if (result === undefined) return callback(new TypeError('Missing RPC result'))

    callback(null, result)
  })
}

module.exports = RPCClient
<|endoftext|>


<commit_before>#!/usr/bin/env node
const path = require('path');
const glob = require('glob');
const fs = require('fs');

const maxOldSpaceSice = process.env.LIMIT || 10240;
const cwd = process.cwd() + path.sep;

glob(path.join(cwd, "node_modules", ".bin", "*"), function(err, files) {

  files.forEach(file => {
    let contents = fs.readFileSync(file).toString();
    contents = contents.replace(/node\b(?: \-\-max\-old\-space\-size\=[0-9]+)?/gm, `node --max-old-space-size=${ maxOldSpaceSice }`);
    fs.writeFileSync(file, contents);
    console.log(`'${ file.replace(cwd, "") }'`, "written successfully.");
  });

});
<commit_msg>t push origin master Merge branch 'sandorfr-feature/improve-replacement'<commit_after>#!/usr/bin/env node
const path = require('path');
const glob = require('glob');
const fs = require('fs');

const maxOldSpaceSice = process.env.LIMIT || 10240;
const cwd = process.cwd() + path.sep;

glob(path.join(cwd, "node_modules", ".bin", "*"), function (err, files) {

  files.forEach(file => {
    let contents = fs.readFileSync(file).toString();
    let lines = contents.split('\n')

    let patchedContents = "";

    for (var index = 0; index < lines.length; index++) {
      var line = lines[index];
      if (line.startsWith("if [") || line.startsWith("@IF")) {
        patchedContents += line + "\n";
      } else {
        patchedContents += line.replace(/node\b(?: \-\-max\-old\-space\-size\=[0-9]+)?/, `node --max-old-space-size=${maxOldSpaceSice}`) + "\n";
      }
    }

    fs.writeFileSync(file, patchedContents);
    console.log(`'${file.replace(cwd, "")}'`, "written successfully.");
  });

});
<|endoftext|>


<commit_before>/* jshint node: true */
'use strict';

var path = require('path'),
    spawn = require('child_process').spawn,
    RSVP = require('rsvp'),
    touch = require('touch'),
    fs = require('fs'),
    chalk = require('chalk'),
    isWin = /^win/.test(process.platform),
    cliPath = path.resolve(__dirname, 'node_modules', 'ember-cli-windows', 'bin', 'ember-cli-windows');

module.exports = {
    name: 'ember-cli-windows-addon',
    includedCommands: function () {
        return {
            windows: {
                name: 'windows',
                aliases: ['win'],
                description: 'Configure Windows Search and Defender to improve performanc for this project',
                works: 'insideProject',

                runCommand: function (args) {
                    return new RSVP.Promise(function (resolve, reject) {
                        var child, result, options, i;

                        options = [cliPath];
                        options.push('headless');
                        for (i = 0; i < args.length; i = i + 1) {
                            if (args.hasOwnProperty(args[i])) {
                                options.push(args[i]);
                            }
                        }

                        child = spawn('node', options);
                        result = {
                            output: [],
                            errors: [],
                            code: null
                        };

                        child.stdout.on('data', function (data) {
                            var string = data.toString();
                            console.log(string);

                            result.output.push(string);
                        });

                        child.stderr.on('data', function (data) {
                            var string = data.toString();
                            console.error(string);

                            result.errors.push(string);
                        });

                        child.on('close', function (code) {
                            result.code = code;

                            if (code === 0) {
                                touch.sync(path.join(__dirname, '.configured'));
                                resolve(result);
                            } else {
                                reject(result);
                            }
                        });
                    });
                },

                run: function (options, rawArgs) {
                    console.log(rawArgs);
                    if (!isWin) {
                        return console.error('This addon configures Windows, but the OS is not Windows.');
                    }

                    return this.runCommand(rawArgs);
                }
            }
        };
    },

    preBuild: function () {
        if (!isWin) {
            try {
                var stats = fs.lstatSync(path.join(__dirname, '.configured')); // jshint ignore:line
            } catch (error) {
                // .configured doesn't exist, meaning that we're not configured yet
                return console.log(chalk.green.bold('Please run \'ember windows\` to configure Windows for better build performance.'));
            }
        }
        return;
    }
};
<commit_msg>Silent Fail<commit_after>/* jshint node: true */
'use strict';

var path = require('path'),
    spawn = require('child_process').spawn,
    RSVP = require('rsvp'),
    touch = require('touch'),
    fs = require('fs'),
    chalk = require('chalk'),
    isWin = /^win/.test(process.platform),
    cliPath = path.resolve(__dirname, 'node_modules', 'ember-cli-windows', 'bin', 'ember-cli-windows');

module.exports = {
    name: 'ember-cli-windows-addon',
    includedCommands: function () {
        return {
            windows: {
                name: 'windows',
                aliases: ['win'],
                description: 'Configure Windows Search and Defender to improve performanc for this project',
                works: 'insideProject',

                runCommand: function (args) {
                    return new RSVP.Promise(function (resolve, reject) {
                        var child, result, options, i;

                        options = [cliPath];
                        options.push('headless');
                        for (i = 0; i < args.length; i = i + 1) {
                            if (args.hasOwnProperty(args[i])) {
                                options.push(args[i]);
                            }
                        }

                        child = spawn('node', options);
                        result = {
                            output: [],
                            errors: [],
                            code: null
                        };

                        child.stdout.on('data', function (data) {
                            var string = data.toString();
                            if (this.ui) {
                                this.ui.writeLine(string);
                            } else {
                                console.log(string);
                            }

                            result.output.push(string);
                        });

                        child.stderr.on('data', function (data) {
                            var string = data.toString();
                            if (this.ui) {
                                this.ui.writeLine(string);
                            } else {
                                console.error(string);
                            }

                            result.errors.push(string);
                        });

                        child.on('close', function (code) {
                            result.code = code;

                            if (code === 0) {
                                touch.sync(path.join(__dirname, '.configured'));
                                resolve(result);
                            } else {
                                reject(result);
                            }
                        });
                    });
                },

                run: function (options, rawArgs) {
                    if (!isWin) {
                        return;
                    }

                    return this.runCommand(rawArgs);
                }
            }
        };
    },

    preBuild: function () {
        if (!isWin) {
            try {
                var stats = fs.lstatSync(path.join(__dirname, '.configured')); // jshint ignore:line
            } catch (error) {
                // .configured doesn't exist, meaning that we're not configured yet
                if (this.ui) {
                    this.ui.writeLine(chalk.green.bold('Please run \'ember windows\` to configure Windows for better build performance.'));
                } else {
                    console.log(chalk.green.bold('Please run \'ember windows\` to configure Windows for better build performance.'));
                }
            }
        }
        return;
    }
};
<|endoftext|>


<commit_before>'use strict';

var Combine = require('stream-combiner');
var closureTemplates = require('closure-templates');
var fs = require('fs');
var gutil = require('gulp-util');
var path = require('path');
var soynode = require('soynode');
var spawn = require('child_process').spawn;
var through = require('through2');

var PATH_TO_MSG_EXTRACTOR = closureTemplates['SoyMsgExtractor.jar'];

var gulpSoynode = function(options) {
  options = options || {};

  // Resolve internal options.
  var optionsInternal = {};
  optionsInternal.renderSoyWeb = options.renderSoyWeb;
  optionsInternal.renderSoyWebContext = options.renderSoyWebContext;
  optionsInternal.renderSoyWebInjectedData = options.renderSoyWebInjectedData;
  optionsInternal.renderSoyWebFileExtension = options.renderSoyWebFileExtension || '.html';
  delete options.renderSoyWeb;
  delete options.renderSoyWebContext;
  delete options.renderSoyWebInjectedData;
  delete options.renderSoyWebFileExtension;

  // Resolve soynode options.
  var optionsSoynode = options;
  optionsSoynode.uniqueDir = false;
  optionsSoynode.outputDir = path.resolve(options.outputDir || '/tmp/soynode');

  return new Combine(
    gutil.buffer(),
    through.obj(function(files, enc, cb) {
      // Discourage usage of `allowDynamicRecompile` option.
      if (optionsSoynode.allowDynamicRecompile) {
        this.emit('error', new gutil.PluginError(
        'gulp-soynode',
        'Option `allowDynamicRecompile` is not supported, use `gulp.watch` instead.'));
      }

      // When rendering soyweb templates make sure to load compiled templates.
      if (optionsInternal.renderSoyWeb) {
        if (optionsSoynode.loadCompiledTemplates === false) {
          this.emit('error', new gutil.PluginError(
          'gulp-soynode',
          'Option `renderSoyWeb` requires `loadCompiledTemplates` to be enabled.'));
        }
      }

      compileFiles(this, files, optionsInternal, optionsSoynode, cb);
    }));
};

/**
 * Extracts messages from the given soy template files.
 * @param {object} options
 */
gulpSoynode.lang = function(options) {
  options = options || {};

  return new Combine(
    gutil.buffer(),
    through.obj(function(files, enc, cb) {
      var stream = this;
      var outputFile = options.outputFile || '/tmp/soynode/translations.xlf';

      var args = [
        '-jar', PATH_TO_MSG_EXTRACTOR,
        '--outputFile', outputFile
      ];
      args = args.concat(getFilePaths(files));

      var process = spawn('java', args);
      process.on('exit', function (err) {
        if (err) {
          stream.emit('error', new gutil.PluginError('gulp-soynode', err));
          stream.emit('end');
          cb();
          return;
        }

        var translationFile = new gutil.File({
          contents: fs.readFileSync(outputFile),
          path: outputFile
        });

        stream.emit('data', translationFile);
        stream.emit('end');
        cb();
      });
    })
  );
};

/**
 * Compiles buffered files from a through stream.
 * @param {Stream} stream
 * @param {array} files Buffered files array.
 * @param {object} optionsInternal
 * @param {object} optionsSoynode
 * @param {function} cb
 */
function compileFiles(stream, files, optionsInternal, optionsSoynode, cb) {
  var filepaths = getFilePaths(files);

  soynode.setOptions(optionsSoynode);
  soynode.compileTemplateFiles(filepaths, function(err) {
    if (err) {
      this.emit('error', new gutil.PluginError('gulp-soynode', err));
    }

    files.forEach(function(file) {
      var relative = path.relative(file.cwd, file.path);
      var soypath = relative + '.js';

      var compiled = new gutil.File({
        base: file.base,
        contents: fs.readFileSync(path.join(optionsSoynode.outputDir, soypath)),
        cwd: file.cwd,
        path: gutil.replaceExtension(file.path, '.soy.js')
      });

      if (optionsInternal.renderSoyWeb) {
        try {
          // When building a static SoyWeb template make sure to only emit
          // the output file, no need to emit the .soy and .soy.js.
          file = renderSoyWeb(file, optionsInternal, optionsSoynode);
          compiled = null;
        } catch (err) {}
      }

      stream.emit('data', file);

      if (compiled) {
        stream.emit('data', compiled);
      }
    });

    stream.emit('end');
    cb();
  });
}

/**
 * Returns the file paths of the given files.
 * @param {array} files Buffered files array.
 * @return {array}
 */
function getFilePaths(files) {
  return files.map(function(file) {
    return path.relative(file.cwd, file.path);
  });
}

/**
 * This method allows templates to be rendered by SoyWeb. It deliberately
 * includes dummy data so the designer can get a feel for how the task list
 * will appear with real data rather with minimal copy and paste. For more
 * information visit: http://plovr.com/soyweb.html
 * @param {File} file The soy template file.
 * @param {object} optionsInternal
 * @param {object} optionsSoynode
 * @return {File} Returns a file containing the rendered SoyWeb content.
 */
function renderSoyWeb(file, optionsInternal, optionsSoynode) {
  var namespace = lookupNamespace(file.contents.toString());

  var rendered = soynode.render(
    namespace + '.soyweb',
    optionsInternal.renderSoyWebContext,
    optionsInternal.renderSoyWebInjectedData,
    optionsSoynode.locales ? optionsSoynode.locales[0] : null
  );
  var renderedFile = new gutil.File({
    base: file.base,
    contents: new Buffer(rendered),
    cwd: file.cwd,
    path: gutil.replaceExtension(file.path, optionsInternal.renderSoyWebFileExtension)
  });
  return renderedFile;
}

/**
 * Lookups namespace from template content.
 * @param {string} contents
 * @return {string} The template namespace
 */
function lookupNamespace(contents) {
  var startToken = '{namespace ';
  var startPos = contents.indexOf(startToken);
  var namespace = contents.substring(startPos + startToken.length, contents.indexOf('}'));
  var spacePos = namespace.indexOf(' ');
  if (spacePos > -1) {
    namespace = namespace.substring(0, spacePos);
  }
  return namespace;
}

module.exports = gulpSoynode;
<commit_msg>Fixes renderSoyWebInjectedData default value<commit_after>'use strict';

var Combine = require('stream-combiner');
var closureTemplates = require('closure-templates');
var fs = require('fs');
var gutil = require('gulp-util');
var path = require('path');
var soynode = require('soynode');
var spawn = require('child_process').spawn;
var through = require('through2');

var PATH_TO_MSG_EXTRACTOR = closureTemplates['SoyMsgExtractor.jar'];

var gulpSoynode = function(options) {
  options = options || {};

  // Resolve internal options.
  var optionsInternal = {};
  optionsInternal.renderSoyWeb = options.renderSoyWeb;
  optionsInternal.renderSoyWebContext = options.renderSoyWebContext;
  optionsInternal.renderSoyWebInjectedData = options.renderSoyWebInjectedData || {};
  optionsInternal.renderSoyWebFileExtension = options.renderSoyWebFileExtension || '.html';
  delete options.renderSoyWeb;
  delete options.renderSoyWebContext;
  delete options.renderSoyWebInjectedData;
  delete options.renderSoyWebFileExtension;

  // Resolve soynode options.
  var optionsSoynode = options;
  optionsSoynode.uniqueDir = false;
  optionsSoynode.outputDir = path.resolve(options.outputDir || '/tmp/soynode');

  return new Combine(
    gutil.buffer(),
    through.obj(function(files, enc, cb) {
      // Discourage usage of `allowDynamicRecompile` option.
      if (optionsSoynode.allowDynamicRecompile) {
        this.emit('error', new gutil.PluginError(
        'gulp-soynode',
        'Option `allowDynamicRecompile` is not supported, use `gulp.watch` instead.'));
      }

      // When rendering soyweb templates make sure to load compiled templates.
      if (optionsInternal.renderSoyWeb) {
        if (optionsSoynode.loadCompiledTemplates === false) {
          this.emit('error', new gutil.PluginError(
          'gulp-soynode',
          'Option `renderSoyWeb` requires `loadCompiledTemplates` to be enabled.'));
        }
      }

      compileFiles(this, files, optionsInternal, optionsSoynode, cb);
    }));
};

/**
 * Extracts messages from the given soy template files.
 * @param {object} options
 */
gulpSoynode.lang = function(options) {
  options = options || {};

  return new Combine(
    gutil.buffer(),
    through.obj(function(files, enc, cb) {
      var stream = this;
      var outputFile = options.outputFile || '/tmp/soynode/translations.xlf';

      var args = [
        '-jar', PATH_TO_MSG_EXTRACTOR,
        '--outputFile', outputFile
      ];
      args = args.concat(getFilePaths(files));

      var process = spawn('java', args);
      process.on('exit', function (err) {
        if (err) {
          stream.emit('error', new gutil.PluginError('gulp-soynode', err));
          stream.emit('end');
          cb();
          return;
        }

        var translationFile = new gutil.File({
          contents: fs.readFileSync(outputFile),
          path: outputFile
        });

        stream.emit('data', translationFile);
        stream.emit('end');
        cb();
      });
    })
  );
};

/**
 * Compiles buffered files from a through stream.
 * @param {Stream} stream
 * @param {array} files Buffered files array.
 * @param {object} optionsInternal
 * @param {object} optionsSoynode
 * @param {function} cb
 */
function compileFiles(stream, files, optionsInternal, optionsSoynode, cb) {
  var filepaths = getFilePaths(files);

  soynode.setOptions(optionsSoynode);
  soynode.compileTemplateFiles(filepaths, function(err) {
    if (err) {
      this.emit('error', new gutil.PluginError('gulp-soynode', err));
    }

    files.forEach(function(file) {
      var relative = path.relative(file.cwd, file.path);
      var soypath = relative + '.js';

      var compiled = new gutil.File({
        base: file.base,
        contents: fs.readFileSync(path.join(optionsSoynode.outputDir, soypath)),
        cwd: file.cwd,
        path: gutil.replaceExtension(file.path, '.soy.js')
      });

      if (optionsInternal.renderSoyWeb) {
        try {
          // When building a static SoyWeb template make sure to only emit
          // the output file, no need to emit the .soy and .soy.js.
          file = renderSoyWeb(file, optionsInternal, optionsSoynode);
          compiled = null;
        } catch (err) {}
      }

      stream.emit('data', file);

      if (compiled) {
        stream.emit('data', compiled);
      }
    });

    stream.emit('end');
    cb();
  });
}

/**
 * Returns the file paths of the given files.
 * @param {array} files Buffered files array.
 * @return {array}
 */
function getFilePaths(files) {
  return files.map(function(file) {
    return path.relative(file.cwd, file.path);
  });
}

/**
 * This method allows templates to be rendered by SoyWeb. It deliberately
 * includes dummy data so the designer can get a feel for how the task list
 * will appear with real data rather with minimal copy and paste. For more
 * information visit: http://plovr.com/soyweb.html
 * @param {File} file The soy template file.
 * @param {object} optionsInternal
 * @param {object} optionsSoynode
 * @return {File} Returns a file containing the rendered SoyWeb content.
 */
function renderSoyWeb(file, optionsInternal, optionsSoynode) {
  var namespace = lookupNamespace(file.contents.toString());

  var rendered = soynode.render(
    namespace + '.soyweb',
    optionsInternal.renderSoyWebContext,
    optionsInternal.renderSoyWebInjectedData,
    optionsSoynode.locales ? optionsSoynode.locales[0] : null
  );
  var renderedFile = new gutil.File({
    base: file.base,
    contents: new Buffer(rendered),
    cwd: file.cwd,
    path: gutil.replaceExtension(file.path, optionsInternal.renderSoyWebFileExtension)
  });
  return renderedFile;
}

/**
 * Lookups namespace from template content.
 * @param {string} contents
 * @return {string} The template namespace
 */
function lookupNamespace(contents) {
  var startToken = '{namespace ';
  var startPos = contents.indexOf(startToken);
  var namespace = contents.substring(startPos + startToken.length, contents.indexOf('}'));
  var spacePos = namespace.indexOf(' ');
  if (spacePos > -1) {
    namespace = namespace.substring(0, spacePos);
  }
  return namespace;
}

module.exports = gulpSoynode;
<|endoftext|>


<commit_before>'use strict';

var express = require('express');
var bodyParser = require('body-parser');
var request = require('request');
var app = express();

let Wit = null;
let log = null;
try {
  // if running from repo
  Wit = require('../').Wit;
  log = require('../').log;
} catch (e) {
  Wit = require('node-wit').Wit;
  log = require('node-wit').log;
}

// Variables are defined in Heroku
const WIT_TOKEN = process.env.WIT_TOKEN;
const FB_PAGE_ACCESS_TOKEN = process.env.PAGE_ACCESS_TOKEN;
const PORT = process.env.PORT;
//Needs feature Dyno Metadata (https://stackoverflow.com/questions/7917523/how-do-i-access-the-current-heroku-release-version-programmatically)
const VERSION = process.env.HEROKU_RELEASE_VERSION;

const { pgClient } = require('pg');

const pgClient = new Client({
  connectionString: process.env.DATABASE_URL,
  ssl: true,
});

app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.listen(PORT);
console.log('Listening on :' + PORT + '...');

// Server frontpage
app.get('/', function (req, res) {
    res.send('This is TestBot Server');
});

// Facebook Webhook
app.get('/webhook', function (req, res) {
    if (req.query['hub.verify_token'] === 'luzbot_hans') {
        res.send(req.query['hub.challenge']);
    } else {
        res.send('Invalid verify token');
    }
});

// handler receiving messages
app.post('/webhook', function (req, res) {
    var events = req.body.entry[0].messaging;
    for (var i = 0; i < events.length; i++) {
        var event = events[i];
        if (event.message && event.message.text) {

			// Yay! We got a new message!
			// We retrieve the Facebook user ID of the sender
			const sender = event.sender.id;

			// We retrieve the user's current session, or create one if it doesn't exist
			// This is needed for our bot to figure out the conversation history
			const sessionId = findOrCreateSession(sender);

			var question = event.message.text;

			if(question.toUpperCase() == "HI") {
				var answer = "Hi. How are you?";
				sendMessage(event.sender.id, answer);
			}
			else if(question.toUpperCase() == "VERSION") {
				var answer = "Aktuelle Version ist " + VERSION;
				sendMessage(event.sender.id, answer);
			}
			else {
				//forward question to wit framework
				console.log('New message detected, text: ' + question);
				console.log('New message detected, sender: ' + sender);
				console.log('New message detected, sessionId: ' + sessionId);

				wit.message(question, {})
					.then((data) =>
					{
						var body = JSON.stringify(data);
						console.log('Yay, got Wit.ai response: ' + body);
						var answer = getAnswer(data);
						sendMessage(event.sender.id, answer);
					})
				.catch(console.error);

			}

			// Let's forward the message to the Wit.ai Bot Engine
            // This will run all actions until our bot has nothing left to do
            /*wit.runActions(
              sessionId, // the user's current session
              text, // the user's message
              sessions[sessionId].context // the user's current session state
            ).then((context) => {
              // Our bot did everything it has to do.
              // Now it's waiting for further messages to proceed.
              console.log('Waiting for next user messages');

              // Based on the session state, you might want to reset the session.
              // This depends heavily on the business logic of your bot.
              // Example:
              // if (context['done']) {
              //   delete sessions[sessionId];
              // }

              // Updating the user's current session state
              sessions[sessionId].context = context;
            })
            .catch((err) => {
              console.error('Oops! Got an error from Wit: ', err.stack || err);
            })
			*/

        }
    }
    res.sendStatus(200);
});

//witJSON answer of WIT Engine, i.e.
/*
{
	"_text":"Zeige mir Restaurants"
	,"entities":{"intent":[{"confidence":0.78031343410165,"value":"restaurant"}]}
	,"msg_id":"0xaoNXhmAyWix0sms"
}
*/
function getAnswer(nlpJson) {
	var answer = "";
	//Process JSON for correct answer

	if (nlpJson['entities']['intent']['0']['value'] === 'temperature_get') {
		answer = "Die aktuelle Temperatur ist...";
	}
	else if (nlpJson['entities']['intent']['0']['value'] === 'temperature_set') {
		answer = "Die neue Temperatur ist " + nlpJson['entities']['temperature']['0']['value'] + ' ' + nlpJson['entities']['temperature']['0']['unit'];
	}
	else if (nlpJson['entities']['intent']['0']['value'] === 'restaurant') {
		client.connect();

		answer = 'Ich zeige dir eine Liste von Restaurants...';

		var sql = "SELECT resultname FROM results res LEFT OUTER JOIN category cat ON res.idcategory = cat.idcategory LEFT OUTER JOIN subcategory scat ON res.idsubcategory = scat.idsubcategory WHERE category = 'Eating'";

		//'SELECT table_schema,table_name FROM information_schema.tables;'

		client.query(sql, (err, res) => {
		if (err) throw err;
		for (let row of res.rows) {
			console.log(JSON.stringify(row));
			answer += JSON.stringify(row);
		}
		client.end();
		});

		answer += "...Ende der Liste...";
	}
	else {
		answer = "Ich verstehe deine Anfrage nicht. Sorry.";
	}

	/*
	SELECT resultname FROM results res
	LEFT OUTER JOIN category cat ON res.idcategory = cat.idcategory
	LEFT OUTER JOIN subcategory scat ON res.idsubcategory = scat.idsubcategory
	WHERE category = 'Eating'
	*/

    return answer;
}

// generic function sending messages
function sendMessage(recipientId, msg) {
	var message = {text: msg};
    request({
        url: 'https://graph.facebook.com/v2.10/me/messages',
        qs: {access_token: FB_PAGE_ACCESS_TOKEN},
        method: 'POST',
        json: {
            recipient: {id: recipientId},
            message: message,
        }
    }, function(error, response, body) {
        if (error) {
            console.log('Error sending message: ', error);
        } else if (response.body.error) {
            console.log('Error: ', response.body.error);
        }
    });
};

// ----------------------------------------------------------------------------
// Messenger API specific code

// See the Send API reference
// https://developers.facebook.com/docs/messenger-platform/send-api-reference

const fbMessage = (id, text) => {
  const body = JSON.stringify({
    recipient: { id },
    message: { text },
  });
  const qs = 'access_token=' + encodeURIComponent(FB_PAGE_ACCESS_TOKEN);
  return fetch('https://graph.facebook.com/me/messages?' + qs, {
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    body,
  })
  .then(rsp => rsp.json())
  .then(json => {
    if (json.error && json.error.message) {
      throw new Error(json.error.message);
    }
    return json;
  });
};

// ----------------------------------------------------------------------------
// Wit.ai bot specific code

// This will contain all user sessions.
// Each session has an entry:
// sessionId -> {fbid: facebookUserId, context: sessionState}
const sessions = {};

const findOrCreateSession = (fbid) => {
  let sessionId;
  // Let's see if we already have a session for the user fbid
  Object.keys(sessions).forEach(k => {
    if (sessions[k].fbid === fbid) {
      // Yep, got it!
      sessionId = k;
    }
  });
  if (!sessionId) {
    // No session found for user fbid, let's create a new one
    sessionId = new Date().toISOString();
    sessions[sessionId] = {fbid: fbid, context: {}};
  }
  return sessionId;
};

// Our bot actions
const actions = {
  send({sessionId}, {text}) {
	console.log('Our bot has something to say!');
    // Our bot has something to say!
    // Let's retrieve the Facebook user whose session belongs to
    const recipientId = sessions[sessionId].fbid;
	console.log('Our bot has something to say!' + recipientId);
    if (recipientId) {
		console.log('// Yay, we found our recipient!');
      // Yay, we found our recipient!
      // Let's forward our bot response to her.
      // We return a promise to let our bot know when we're done sending
      return fbMessage(recipientId, text)
      .then(() => null)
      .catch((err) => {
        console.error(
          'Oops! An error occurred while forwarding the response to',
          recipientId,
          ':',
          err.stack || err
        );
      });
    } else {
      console.error('Oops! Couldn\'t find user for session:', sessionId);
      // Giving the wheel back to our bot
      return Promise.resolve()
    }
  },
  // You should implement your custom actions here
  // See https://wit.ai/docs/quickstart
};

// Setting up our bot
const wit = new Wit({
  accessToken: WIT_TOKEN,
  actions,
  logger: new log.Logger(log.INFO)
});
<commit_msg>Example postgres connection<commit_after>'use strict';

var express = require('express');
var bodyParser = require('body-parser');
var request = require('request');
var app = express();

let Wit = null;
let log = null;
try {
  // if running from repo
  Wit = require('../').Wit;
  log = require('../').log;
} catch (e) {
  Wit = require('node-wit').Wit;
  log = require('node-wit').log;
}

// Variables are defined in Heroku
const WIT_TOKEN = process.env.WIT_TOKEN;
const FB_PAGE_ACCESS_TOKEN = process.env.PAGE_ACCESS_TOKEN;
const PORT = process.env.PORT;
//Needs feature Dyno Metadata (https://stackoverflow.com/questions/7917523/how-do-i-access-the-current-heroku-release-version-programmatically)
const VERSION = process.env.HEROKU_RELEASE_VERSION;

const { Client } = require('pg');

const pgClient = new Client({
  connectionString: process.env.DATABASE_URL,
  ssl: true,
});

app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.listen(PORT);
console.log('Listening on :' + PORT + '...');

// Server frontpage
app.get('/', function (req, res) {
    res.send('This is TestBot Server');
});

// Facebook Webhook
app.get('/webhook', function (req, res) {
    if (req.query['hub.verify_token'] === 'luzbot_hans') {
        res.send(req.query['hub.challenge']);
    } else {
        res.send('Invalid verify token');
    }
});

// handler receiving messages
app.post('/webhook', function (req, res) {
    var events = req.body.entry[0].messaging;
    for (var i = 0; i < events.length; i++) {
        var event = events[i];
        if (event.message && event.message.text) {

			// Yay! We got a new message!
			// We retrieve the Facebook user ID of the sender
			const sender = event.sender.id;

			// We retrieve the user's current session, or create one if it doesn't exist
			// This is needed for our bot to figure out the conversation history
			const sessionId = findOrCreateSession(sender);

			var question = event.message.text;

			if(question.toUpperCase() == "HI") {
				var answer = "Hi. How are you?";
				sendMessage(event.sender.id, answer);
			}
			else if(question.toUpperCase() == "VERSION") {
				var answer = "Aktuelle Version ist " + VERSION;
				sendMessage(event.sender.id, answer);
			}
			else {
				//forward question to wit framework
				console.log('New message detected, text: ' + question);
				console.log('New message detected, sender: ' + sender);
				console.log('New message detected, sessionId: ' + sessionId);

				wit.message(question, {})
					.then((data) =>
					{
						var body = JSON.stringify(data);
						console.log('Yay, got Wit.ai response: ' + body);
						var answer = getAnswer(data);
						sendMessage(event.sender.id, answer);
					})
				.catch(console.error);

			}

			// Let's forward the message to the Wit.ai Bot Engine
            // This will run all actions until our bot has nothing left to do
            /*wit.runActions(
              sessionId, // the user's current session
              text, // the user's message
              sessions[sessionId].context // the user's current session state
            ).then((context) => {
              // Our bot did everything it has to do.
              // Now it's waiting for further messages to proceed.
              console.log('Waiting for next user messages');

              // Based on the session state, you might want to reset the session.
              // This depends heavily on the business logic of your bot.
              // Example:
              // if (context['done']) {
              //   delete sessions[sessionId];
              // }

              // Updating the user's current session state
              sessions[sessionId].context = context;
            })
            .catch((err) => {
              console.error('Oops! Got an error from Wit: ', err.stack || err);
            })
			*/

        }
    }
    res.sendStatus(200);
});

//witJSON answer of WIT Engine, i.e.
/*
{
	"_text":"Zeige mir Restaurants"
	,"entities":{"intent":[{"confidence":0.78031343410165,"value":"restaurant"}]}
	,"msg_id":"0xaoNXhmAyWix0sms"
}
*/
function getAnswer(nlpJson) {
	var answer = "";
	//Process JSON for correct answer

	if (nlpJson['entities']['intent']['0']['value'] === 'temperature_get') {
		answer = "Die aktuelle Temperatur ist...";
	}
	else if (nlpJson['entities']['intent']['0']['value'] === 'temperature_set') {
		answer = "Die neue Temperatur ist " + nlpJson['entities']['temperature']['0']['value'] + ' ' + nlpJson['entities']['temperature']['0']['unit'];
	}
	else if (nlpJson['entities']['intent']['0']['value'] === 'restaurant') {
		pgClient.connect();

		answer = 'Ich zeige dir eine Liste von Restaurants...';

		var sql = "SELECT resultname FROM results res LEFT OUTER JOIN category cat ON res.idcategory = cat.idcategory LEFT OUTER JOIN subcategory scat ON res.idsubcategory = scat.idsubcategory WHERE category = 'Eating'";

		//'SELECT table_schema,table_name FROM information_schema.tables;'

		pgClient.query(sql, (err, res) => {
		if (err) throw err;
		for (let row of res.rows) {
			console.log(JSON.stringify(row));
			answer += JSON.stringify(row);
		}
		pgClient.end();
		});

		answer += "...Ende der Liste...";
	}
	else {
		answer = "Ich verstehe deine Anfrage nicht. Sorry.";
	}

	/*
	SELECT resultname FROM results res
	LEFT OUTER JOIN category cat ON res.idcategory = cat.idcategory
	LEFT OUTER JOIN subcategory scat ON res.idsubcategory = scat.idsubcategory
	WHERE category = 'Eating'
	*/

    return answer;
}

// generic function sending messages
function sendMessage(recipientId, msg) {
	var message = {text: msg};
    request({
        url: 'https://graph.facebook.com/v2.10/me/messages',
        qs: {access_token: FB_PAGE_ACCESS_TOKEN},
        method: 'POST',
        json: {
            recipient: {id: recipientId},
            message: message,
        }
    }, function(error, response, body) {
        if (error) {
            console.log('Error sending message: ', error);
        } else if (response.body.error) {
            console.log('Error: ', response.body.error);
        }
    });
};

// ----------------------------------------------------------------------------
// Messenger API specific code

// See the Send API reference
// https://developers.facebook.com/docs/messenger-platform/send-api-reference

const fbMessage = (id, text) => {
  const body = JSON.stringify({
    recipient: { id },
    message: { text },
  });
  const qs = 'access_token=' + encodeURIComponent(FB_PAGE_ACCESS_TOKEN);
  return fetch('https://graph.facebook.com/me/messages?' + qs, {
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    body,
  })
  .then(rsp => rsp.json())
  .then(json => {
    if (json.error && json.error.message) {
      throw new Error(json.error.message);
    }
    return json;
  });
};

// ----------------------------------------------------------------------------
// Wit.ai bot specific code

// This will contain all user sessions.
// Each session has an entry:
// sessionId -> {fbid: facebookUserId, context: sessionState}
const sessions = {};

const findOrCreateSession = (fbid) => {
  let sessionId;
  // Let's see if we already have a session for the user fbid
  Object.keys(sessions).forEach(k => {
    if (sessions[k].fbid === fbid) {
      // Yep, got it!
      sessionId = k;
    }
  });
  if (!sessionId) {
    // No session found for user fbid, let's create a new one
    sessionId = new Date().toISOString();
    sessions[sessionId] = {fbid: fbid, context: {}};
  }
  return sessionId;
};

// Our bot actions
const actions = {
  send({sessionId}, {text}) {
	console.log('Our bot has something to say!');
    // Our bot has something to say!
    // Let's retrieve the Facebook user whose session belongs to
    const recipientId = sessions[sessionId].fbid;
	console.log('Our bot has something to say!' + recipientId);
    if (recipientId) {
		console.log('// Yay, we found our recipient!');
      // Yay, we found our recipient!
      // Let's forward our bot response to her.
      // We return a promise to let our bot know when we're done sending
      return fbMessage(recipientId, text)
      .then(() => null)
      .catch((err) => {
        console.error(
          'Oops! An error occurred while forwarding the response to',
          recipientId,
          ':',
          err.stack || err
        );
      });
    } else {
      console.error('Oops! Couldn\'t find user for session:', sessionId);
      // Giving the wheel back to our bot
      return Promise.resolve()
    }
  },
  // You should implement your custom actions here
  // See https://wit.ai/docs/quickstart
};

// Setting up our bot
const wit = new Wit({
  accessToken: WIT_TOKEN,
  actions,
  logger: new log.Logger(log.INFO)
});
<|endoftext|>