<commit_before>const debug = require('debug')('kickthemout')
const _ = require('lodash')
const async = require('async')
const chalk = require('chalk')
const inquirer = require('inquirer')
const latestVersion = require('latest-version')
const pkg = require('./package.json')
const isRoot = require('./lib/utility').isRoot
const getInterfaces = require('./lib/utility').getInterfaces
const printLogoAndCredits = require('./lib/utility').printLogoAndCredits
const vendors = require('./lib/vendors')
const Attack = require('./lib/Attack')
const Spinner = require('cli-spinner').Spinner
const scan = require('./lib/scan')
const arp = require('arpjs')

debug('Debug enabled.')

async.waterfall([
    function(callback) {
      debug('Printing logo and credits')
      printLogoAndCredits(function(ascii){
        console.log(ascii)
        callback(null)
      })
    },
    function(callback) {
      // root permission required
      if (!isRoot()) {
        callback('root permission required')
      }else{
        console.log(chalk.green(' \u2713 Running as', chalk.blue('root\n')))
        callback(null)
      }
    },
    function(callback){
      debug('Checks for available update..')
      latestVersion(pkg.name).then(function(version){
        debug('Current version:', pkg.version, '- Latest version:', version)
        if (require('semver').lt(pkg.version, version)) console.log('  Update available '+chalk.gray(pkg.version)+' → '+chalk.green(version)+'\n')
        callback(null)
      }).catch(callback)
    },
    function(callback){
      inquirer.prompt([{
        type: 'list',
        name: 'choice',
        message: 'What to do?',
        choices: ['Start KickThemOut',
        new inquirer.Separator(),
        {name: 'Update MAC Vendors DB', value: 'oui'}]
      }]).then(function (answers) {
        debug('Choice:', answers.choice);
        if (answers.choice === 'oui'){
          vendors.ouiUpdate(function(err, mex){
            if (err) return callback(err)
            console.log(mex)
            process.exit(0)
          })
        }else{
          callback(null)
        }
      })
    },
    function(callback) {
      getInterfaces(function(err, ifaces){
        if (err) return callback(err)
        debug('Getting available interfaces', ifaces)
        if (ifaces.length === 0) return callback('No network interfaces available')
        var interfaces = ifaces.map(function(i){return {name: i.name, value: i}})
        interfaces.push(new inquirer.Separator('\n'))
        inquirer.prompt([{
          type: 'list',
          name: 'iface',
          message: 'Select the network Interface:',
          choices: interfaces
        }]).then(function (answers) {
          debug('Selected interface:', answers.iface)
          callback(null, answers.iface)
        })
      })
    },
    function(iface, callback) {
      var myIP = iface.ip_address

      // host discovery
      debug('Starting host discovery in LAN')
      var spinner = new Spinner('  Scanning LAN.. %s');
      spinner.setSpinnerString('|/-\\')
      spinner.start()
      scan(myIP, function(err, hosts){
        if (err) return callback('Scan error '+ err.toString())
        debug('hosts found:', hosts)
        spinner.stop()
        // adding iface mac
        iface.gateway_mac_address = (_.find(hosts, {'ip': iface.gateway_ip})).mac
        // removing ourself and the iface ip from targetHosts.
        _.remove(hosts, function(host){ return host.ip === myIP || host.ip === iface.gateway_ip})
        // getting target hosts' vendors (new prop. vendor)
        vendors.get(function(err, newHosts){
          if (err) return callback(err)
          hosts = newHosts
          callback(null, hosts, iface)
        })
      })

    },
    function(hosts, iface, callback){
      arp.table(function(err, table){
        // now refreshed by Ping sweep
        if (err) debug(err)
        debug('Local ARP Table:', table)
        callback(null, hosts, iface)
      })
    },
    function(hosts, iface, callback){
      console.log(chalk.blue(chalk.green(' \u2713'),'Gateway',chalk.yellow(iface.gateway_ip),'has',chalk.green(hosts.length),'hosts up\n'))
      // attack options
      inquirer.prompt([{
        type: 'list',
        name: 'attackOption',
        message: 'Choose an option:',
        choices: [
          {name: 'Kick ONE off', value: 'one'},
          {name: 'Kick SOME off', value: 'some'},
          {name: 'Kick ALL off', value: 'all'},
          new inquirer.Separator(),
          {name: 'Exit KickThemOut\n', value: 'exit'},
        ]
      }]).then(function (answers) {
        debug('Selected option:', answers.attackOption)
        callback(null, hosts, iface, answers.attackOption)
      })
    },
    function(hosts, iface, attackOption, callback){
      if (attackOption === 'exit') process.exit(0)

      /*
      // TODO

      if (attackOption === 'one' || attackOption === 'all'){

      }
      var attack = new Attack()
      attack.setInterface(iface)
            .setTarget(hosts)
            .start()

      // TODO
      inquirer.prompt([{
        type: 'list',
        name: 'targetHosts',
        message: 'Select target hosts:',
        choices: []
      }]).then(function (answers) {
        debug('Selected hosts:', answers.targetHosts)
        callback(null, hosts, iface, answers.targetHosts)
      })
      */

    }
],
// final result callback
function(err, results) {
  console.log(chalk.red('Error: '+err))
  debug('Async final results:', results)
    // results is now equal to ['one', 'two']
});

/*

setInterval(function(){
  arp.poison('192.168.0.100', '192.168.0.1')
}, 6 * 1000)

*/
<commit_msg>code refactoring, splitting in classes<commit_after>const debug = require('debug')('kickthemout')
const _ = require('lodash')
const async = require('async')
const chalk = require('chalk')
const inquirer = require('inquirer')
const latestVersion = require('latest-version')
const pkg = require('./package.json')
const isRoot = require('./lib/utility').isRoot
const printLogoAndCredits = require('./lib/utility').printLogoAndCredits
const vendors = require('./lib/vendors')
const Attack = require('./lib/Attack')
const Network = require('./lib/Network')
const Inquiries = require('./lib/Inquiries')
const Spinner = require('cli-spinner').Spinner
const arp = require('arpjs')

debug('Debug enabled.')

const network = new Network()
const ask = new Inquiries()

async.waterfall([
    function(callback) {
      debug('Printing logo and credits')
      printLogoAndCredits(function(ascii){
        console.log(ascii)
        callback(null)
      })
    },
    function(callback) {
      // root permission required
      if (!isRoot()) {
        callback('root permission required')
      }else{
        console.log(chalk.green(' \u2713 Running as', chalk.blue('root\n')))
        callback(null)
      }
    },
    function(callback){
      debug('Checks for available update..')
      latestVersion(pkg.name).then(function(version){
        debug('Current version:', pkg.version, '- Latest version:', version)
        if (require('semver').lt(pkg.version, version)) console.log('  Update available '+chalk.gray(pkg.version)+' → '+chalk.green(version)+'\n')
        callback(null)
      }).catch(callback)
    },
    function(callback){
      // starting questions
      ask.whatToDo(callback)
    },
    function(callback) {
      // get Interfaces
      network.getInterfaces(callback)
    },
    function(ifaces, callback) {
      // select Interface
      ask.selectInterface(ifaces, function(err, iface){
        if (err) return callback(err)
        network.selectInterface(iface)
        callback(null)
      })
    },
    function(callback) {
      // host discovery
      var iface = network.iface
      var myIP = iface.ip_address

      var spinner = new Spinner('  Scanning LAN.. %s');
      spinner.setSpinnerString('|/-\\')
      spinner.start()
      network.scan(myIP, function(hosts){
        debug('hosts found:', hosts)
        if (!hosts.length) return callback('No hosts found!')
        spinner.stop()
        // adding iface mac
        network.iface.gateway_mac_address = (_.find(hosts, {'ip': iface.gateway_ip})).mac
        // removing ourself and the iface ip from targetHosts.
        _.remove(network.hosts, function(host){ return host.ip === myIP || host.ip === iface.gateway_ip})
        // getting target hosts' vendors (new prop. vendor)
        network.resolveVendors()
        callback(null)
      })

    },
    function(callback){
      arp.table(function(err, table){
        // now refreshed by Ping sweep
        if (err) debug(err)
        debug('Local ARP Table:', table)
        callback(null)
      })
    },
    function(callback){
      var hosts = network.hosts
      var iface = network.iface
      console.log(chalk.blue(chalk.green(' \u2713'),'Gateway',chalk.yellow(iface.gateway_ip),'has',chalk.green(hosts.length),'hosts up\n'))
      // attack options
      inquirer.prompt([{
        type: 'list',
        name: 'attackOption',
        message: 'Choose an option:',
        choices: [
          {name: 'Kick ONE off', value: 'one'},
          {name: 'Kick SOME off', value: 'some'},
          {name: 'Kick ALL off', value: 'all'},
          new inquirer.Separator(),
          {name: 'Exit KickThemOut\n', value: 'exit'},
        ]
      }]).then(function (answers) {
        debug('Selected option:', answers.attackOption)
        callback(null, hosts, iface, answers.attackOption)
      })
    },
    function(hosts, iface, attackOption, callback){
      if (attackOption === 'exit') process.exit(0)

      /*
      // TODO

      if (attackOption === 'one' || attackOption === 'all'){

      }
      var attack = new Attack()
      attack.setInterface(iface)
            .setTarget(hosts)
            .start()

      // TODO
      inquirer.prompt([{
        type: 'list',
        name: 'targetHosts',
        message: 'Select target hosts:',
        choices: []
      }]).then(function (answers) {
        debug('Selected hosts:', answers.targetHosts)
        callback(null, hosts, iface, answers.targetHosts)
      })
      */

    }
],
// final result callback
function(err, results) {
  console.log(chalk.red('Error: '+err))
  debug('Async final results:', results)
    // results is now equal to ['one', 'two']
});

/*

setInterval(function(){
  arp.poison('192.168.0.100', '192.168.0.1')
}, 6 * 1000)

*/
<|endoftext|>


<commit_before>/*
Copyright 2021 Google LLC

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import { regionOptimizer } from './region-optimizer.js';

let inputs;
let userCoords;
let countries;

async function initializeCountrySelect() {
  await fetch("data/countries.json")
  .then(data => data.json())
  .then(json => countries = json);

  //TODO(sort countries alphabetically)

  const locationsSelect = document.getElementById('locations');
  for(const country of countries) {
    const option = document.createElement("option");
    // Stoe the stringified object as option value.
    // Adding the actual values as data- attribute mighe be nicer.
    option.value = JSON.stringify(country);
    option.text = country.name;
    locationsSelect.add(option);
  }
}

function bindListeners() {
  inputs = document.querySelectorAll('.weight');
  for(const input of inputs) {
    input.addEventListener('input', recommendRegion);
  }

  document.getElementById('locations').addEventListener('change', recommendRegion);
};

function printResults(results) {
  console.log("Results:");
  console.log(results);
  const list = document.getElementById('results');
  const template = document.getElementById('result-row');

  // clean the list
  while (list.firstChild) {
    list.removeChild(list.firstChild);
  }

  // Print top regions
  for(let i = 0; i < Math.min(10, results.length); i++) {
    let row = template.content.cloneNode(true);
    row.querySelector('.region').textContent = results[i].region;
    row.querySelector('.name').textContent = results[i].name;
    list.appendChild(row);
  }

}

function recommendRegion() {
  let params = {
    weights: {},
    locations: [],
  };

  // Add weights
  for(const input of inputs) {
    params.weights[input.name] = parseInt(input.value, 10) / 10;
  }

  // Add current location and any other selected country.
  const locationSelect = document.getElementById('locations')
  for(const option of locationSelect.options) {
    if(option.selected) {
      if(option.value === "--current-location--") {
        if(userCoords) {
          params.locations.push(userCoords);
        } else {
          console.log("Current location not available.");
        }
      } else {
        params.locations.push(JSON.parse(option.value));
      }
    }
  }

  regionOptimizer(params).then(printResults);
};

navigator.geolocation.getCurrentPosition((position) => {
    userCoords = position.coords;
    recommendRegion();
});

initializeCountrySelect();
bindListeners();
recommendRegion();<commit_msg>Sort countries<commit_after>/*
Copyright 2021 Google LLC

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import { regionOptimizer } from './region-optimizer.js';

let inputs;
let userCoords;
let countries;

async function initializeCountrySelect() {
  await fetch("data/countries.json")
  .then(data => data.json())
  .then(json => countries = json);

  // Sort countries by name.
  countries.sort(function(a, b) {
    return a.name.localeCompare(b.name);
  });

  const locationsSelect = document.getElementById('locations');
  for(const country of countries) {
    const option = document.createElement("option");
    // Stoe the stringified object as option value.
    // Adding the actual values as data- attribute mighe be nicer.
    option.value = JSON.stringify(country);
    option.text = country.name;
    locationsSelect.add(option);
  }
}

function bindListeners() {
  inputs = document.querySelectorAll('.weight');
  for(const input of inputs) {
    input.addEventListener('input', recommendRegion);
  }

  document.getElementById('locations').addEventListener('change', recommendRegion);
};

function printResults(results) {
  console.log("Results:");
  console.log(results);
  const list = document.getElementById('results');
  const template = document.getElementById('result-row');

  // clean the list
  while (list.firstChild) {
    list.removeChild(list.firstChild);
  }

  // Print top regions
  for(let i = 0; i < Math.min(10, results.length); i++) {
    let row = template.content.cloneNode(true);
    row.querySelector('.region').textContent = results[i].region;
    row.querySelector('.name').textContent = results[i].name;
    list.appendChild(row);
  }

}

function recommendRegion() {
  let params = {
    weights: {},
    locations: [],
  };

  // Add weights
  for(const input of inputs) {
    params.weights[input.name] = parseInt(input.value, 10) / 10;
  }

  // Add current location and any other selected country.
  const locationSelect = document.getElementById('locations')
  for(const option of locationSelect.options) {
    if(option.selected) {
      if(option.value === "--current-location--") {
        if(userCoords) {
          params.locations.push(userCoords);
        } else {
          console.log("Current location not available.");
        }
      } else {
        params.locations.push(JSON.parse(option.value));
      }
    }
  }

  regionOptimizer(params).then(printResults);
};

navigator.geolocation.getCurrentPosition((position) => {
    userCoords = position.coords;
    recommendRegion();
});

initializeCountrySelect();
bindListeners();
recommendRegion();<|endoftext|>


<commit_before>
/**
 * Module dependencies.
 */

var pressure = require('atmospheric');

/**
 * Density of air using
 * the ideal gas law.
 *
 * @param {k} temperature
 * @param {m} altitude
 * @param {Number} humidity (percentage)
 * @param {kg·m−3}
 * @api public
 */

module.exports = function(temperature, altitude, humidity) {
	return 100 * pressure(altitude || 0) / (287.058 * temperature);
};
<commit_msg>add saturation vapor pressure amd gas constant for water air<commit_after>
/**
 * Module dependencies.
 */

var atmospheric = require('atmospheric');

/**
 * Density of air using
 * the ideal gas law.
 *
 * @param {K} temperature
 * @param {m} altitude
 * @param {Number} humidity (percentage)
 * @param {kg·m−3}
 * @api public
 */

module.exports = function (temperature, altitude, humidity) {
	var pressure = atmospheric(altitude || 0);
	var rh = humidity ? constant(temperature, pressure, humidity) : 287.058;
	return 100 * pressure / (rh * temperature);
};

/**
 * Specific gas constant for water air.
 *
 * @param  {K} temperature
 * @param  {hPa} pressure
 * @param  {%} humidity
 * @return {J.K-1.mol-1}
 * @api private
 */

function constant(temperature, pressure, humidity) {
	var psat = sat(temperature - 273.15);
  return 287.06 / (1 - (humidity * psat/pressure) * (1 - 287.06/461));
}

/**
 * Saturation vapor pressure.
 *
 * @param  {C} temperature
 * @return {hPa}
 * @api private
 */

function sat(temperature) {
	return 611.213 * Math.exp(17.5043 * temperature / (241.2 + temperature));
}<|endoftext|>


<commit_before>
/**
 * Module dependencies.
 */

var Me = require('./lib/me');
var Sites = require('./lib/sites');
var ends = require('./lib/endpoint');
var debug = require('debug')('wpcom');

/**
 * WordPress.com REST API class.
 *
 * @api public
 */

function WPCOM(request){
  if (!(this instanceof WPCOM)) return new WPCOM(request);
  if ('function' !== typeof request) {
    throw new TypeError('a `request` WP.com function must be passed in');
  }
  this.request = request;
}

/**
 * Get me object instance
 *
 * @api public
 */

WPCOM.prototype.me = function(){
  return new Me(this);
};

/**
 * Get site object instance
 *
 * @param {String} id
 * @api public
 */

WPCOM.prototype.sites = function(id){
  return new Sites(id, this);
};

/**
 * List Freshly Pressed Posts
 *
 * @param {Object} params (optional)
 * @param {Function} fn callback function
 * @api public
 */

WPCOM.prototype.freshlyPressed = function(params, fn){
  this.sendRequest('freshly-pressed.get', null, params, fn);
};

/**
 * Request to WordPress REST API
 *
 * @param {String} type endpoint type
 * @param {Object} vars to build endpoint
 * @param {Object} params
 * @param {Function} fn
 * @api private
 */

WPCOM.prototype.sendRequest = function (type, vars, params, fn){
  debug('sendRequest()');
  debug('type: `%s`', type);

  // options object || callback function
  if ('function' == typeof params) {
    fn = params;
    params = {};
  }

  if (!params) params = {};
  if (!fn) fn = function(err){ if (err) throw err; };

  // endpoint config object
  var end = ends(type);

  // request method
  params.method = (params.method || end.method || 'GET').toLowerCase();

  // build endpoint url
  var endpoint = end.path;
  if (vars) {
    for (var k in vars) {
      var rg = new RegExp("%" + k + "%");
      endpoint = endpoint.replace(rg, vars[k]);
    }
  }
  params.path = endpoint;
  debug('endpoint: `%s`', endpoint);

  this.request(params, fn);
};

/**
 * Expose `WPCOM` module
 */

module.exports = WPCOM;
<commit_msg>core: pass query parameter through of params.query<commit_after>
/**
 * Module dependencies.
 */

var Me = require('./lib/me');
var Sites = require('./lib/sites');
var ends = require('./lib/endpoint');
var debug = require('debug')('wpcom');

/**
 * WordPress.com REST API class.
 *
 * @api public
 */

function WPCOM(request){
  if (!(this instanceof WPCOM)) return new WPCOM(request);
  if ('function' !== typeof request) {
    throw new TypeError('a `request` WP.com function must be passed in');
  }
  this.request = request;
}

/**
 * Get me object instance
 *
 * @api public
 */

WPCOM.prototype.me = function(){
  return new Me(this);
};

/**
 * Get site object instance
 *
 * @param {String} id
 * @api public
 */

WPCOM.prototype.sites = function(id){
  return new Sites(id, this);
};

/**
 * List Freshly Pressed Posts
 *
 * @param {Object} params (optional)
 * @param {Function} fn callback function
 * @api public
 */

WPCOM.prototype.freshlyPressed = function(params, fn){
  this.sendRequest('freshly-pressed.get', null, params, fn);
};

/**
 * Request to WordPress REST API
 *
 * @param {String} type endpoint type
 * @param {Object} vars to build endpoint
 * @param {Object} params
 * @param {Function} fn
 * @api private
 */

WPCOM.prototype.sendRequest = function (type, vars, params, fn){
  debug('sendRequest()');
  debug('type: `%s`', type);

  // params.query || callback function
  if ('function' == typeof params.query) {
    fn = params.query;
    params.query = {};
  }

  if (!fn) fn = function(err){ if (err) throw err; };

  // endpoint config object
  var end = ends(type);

  // request method
  params.method = (params.method || end.method || 'GET').toLowerCase();

  // build endpoint url
  var endpoint = end.path;
  if (vars) {
    for (var k in vars) {
      var rg = new RegExp("%" + k + "%");
      endpoint = endpoint.replace(rg, vars[k]);
    }
  }
  params.path = endpoint;
  debug('endpoint: `%s`', endpoint);

  this.request(params, fn);
};

/**
 * Expose `WPCOM` module
 */

module.exports = WPCOM;
<|endoftext|>


<commit_before>var babylonToEspree = require("./babylon-to-espree");
var pick            = require("lodash.pickby");
var Module          = require("module");
var path            = require("path");
var parse           = require("babylon").parse;
var t               = require("babel-types");
var tt              = require("babylon").tokTypes;
var traverse        = require("babel-traverse").default;
var codeFrame       = require("babel-code-frame");

var hasPatched = false;
var eslintOptions = {};

function createModule(filename) {
  var mod = new Module(filename);
  mod.filename = filename;
  mod.paths = Module._nodeModulePaths(path.dirname(filename));
  return mod;
}

function monkeypatch() {
  if (hasPatched) return;
  hasPatched = true;

  var eslintLoc;
  try {
    // avoid importing a local copy of eslint, try to find a peer dependency
    eslintLoc = Module._resolveFilename("eslint", module.parent);
  } catch (err) {
    try {
      // avoids breaking in jest where module.parent is undefined
      eslintLoc = require.resolve("eslint");
    } catch (err) {
      throw new ReferenceError("couldn't resolve eslint");
    }
  }

  // get modules relative to what eslint will load
  var eslintMod = createModule(eslintLoc);
  // contains all the instances of estraverse so we can modify them if necessary
  var estraverses = [];
  // ESLint v1.9.0 uses estraverse directly to work around https://github.com/npm/npm/issues/9663
  var estraverseOfEslint = eslintMod.require("estraverse");
  estraverses.push(estraverseOfEslint);
  Object.assign(estraverseOfEslint.VisitorKeys, t.VISITOR_KEYS);

  estraverses.forEach(function (estraverse) {
    estraverse.VisitorKeys.MethodDefinition.push("decorators");
    estraverse.VisitorKeys.Property.push("decorators");
  });

  // monkeypatch escope
  var escopeLoc = Module._resolveFilename("escope", eslintMod);
  var escopeMod = createModule(escopeLoc);
  var escope  = require(escopeLoc);
  var analyze = escope.analyze;
  escope.analyze = function (ast, opts) {
    opts.ecmaVersion = eslintOptions.ecmaVersion;
    opts.sourceType = eslintOptions.sourceType;
    if (eslintOptions.globalReturn !== undefined) {
      opts.nodejsScope = eslintOptions.globalReturn;
    }

    var results = analyze.call(this, ast, opts);
    return results;
  };

  // monkeypatch escope/referencer
  var referencerLoc;
  try {
    referencerLoc = Module._resolveFilename("./referencer", escopeMod);
  } catch (err) {
    throw new ReferenceError("couldn't resolve escope/referencer");
  }
  var referencerMod = createModule(referencerLoc);
  var referencer = require(referencerLoc);
  if (referencer.__esModule) {
    referencer = referencer.default;
  }

  // reference Definition
  var definitionLoc;
  try {
    definitionLoc = Module._resolveFilename("./definition", referencerMod);
  } catch (err) {
    throw new ReferenceError("couldn't resolve escope/definition");
  }
  var Definition = require(definitionLoc).Definition;

  // if there are decorators, then visit each
  function visitDecorators(node) {
    if (!node.decorators) {
      return;
    }
    for (var i = 0; i < node.decorators.length; i++) {
      if (node.decorators[i].expression) {
        this.visit(node.decorators[i]);
      }
    }
  }

  // iterate through part of t.VISITOR_KEYS
  var visitorKeysMap = pick(t.VISITOR_KEYS, function(k) {
    return t.FLIPPED_ALIAS_KEYS.Flow.concat([
      "ArrayPattern",
      "ClassDeclaration",
      "ClassExpression",
      "FunctionDeclaration",
      "FunctionExpression",
      "Identifier",
      "ObjectPattern",
      "RestElement"
    ]).indexOf(k) === -1;
  });

  var propertyTypes = {
    // loops
    callProperties: { type: "loop", values: ["value"] },
    indexers: { type: "loop", values: ["key", "value"] },
    properties: { type: "loop", values: ["value"] },
    types: { type: "loop" },
    params: { type: "loop" },
    // single property
    argument: { type: "single" },
    elementType: { type: "single" },
    qualification: { type: "single" },
    rest: { type: "single" },
    returnType: { type: "single" },
    // others
    typeAnnotation: { type: "typeAnnotation" },
    typeParameters: { type: "typeParameters" },
    id: { type: "id" }
  };

  function visitTypeAnnotation(node) {
    // get property to check (params, id, etc...)
    var visitorValues = visitorKeysMap[node.type];
    if (!visitorValues) {
      return;
    }

    // can have multiple properties
    for (var i = 0; i < visitorValues.length; i++) {
      var visitorValue = visitorValues[i];
      var propertyType = propertyTypes[visitorValue];
      var nodeProperty = node[visitorValue];
      // check if property or type is defined
      if (propertyType == null || nodeProperty == null) {
        continue;
      }
      if (propertyType.type === "loop") {
        for (var j = 0; j < nodeProperty.length; j++) {
          if (Array.isArray(propertyType.values)) {
            for (var k = 0; k < propertyType.values.length; k++) {
              checkIdentifierOrVisit.call(this, nodeProperty[j][propertyType.values[k]]);
            }
          } else {
            checkIdentifierOrVisit.call(this, nodeProperty[j]);
          }
        }
      } else if (propertyType.type === "single") {
        checkIdentifierOrVisit.call(this, nodeProperty);
      } else if (propertyType.type === "typeAnnotation") {
        visitTypeAnnotation.call(this, node.typeAnnotation);
      } else if (propertyType.type === "typeParameters") {
        for (var l = 0; l < node.typeParameters.params.length; l++) {
          checkIdentifierOrVisit.call(this, node.typeParameters.params[l]);
        }
      } else if (propertyType.type === "id") {
        if (node.id.type === "Identifier") {
          checkIdentifierOrVisit.call(this, node.id);
        } else {
          visitTypeAnnotation.call(this, node.id);
        }
      }
    }
  }

  function checkIdentifierOrVisit(node) {
    if (node.typeAnnotation) {
      visitTypeAnnotation.call(this, node.typeAnnotation);
    } else if (node.type === "Identifier") {
      this.visit(node);
    } else {
      visitTypeAnnotation.call(this, node);
    }
  }

  function nestTypeParamScope(manager, node) {
    var parentScope = manager.__currentScope;
    var scope = new escope.Scope(manager, "type-parameters", parentScope, node, false);
    manager.__nestScope(scope);
    for (var j = 0; j < node.typeParameters.params.length; j++) {
      var name = node.typeParameters.params[j];
      scope.__define(name, new Definition("TypeParameter", name, name));
    }
    scope.__define = function() {
      return parentScope.__define.apply(parentScope, arguments);
    };
    return scope;
  }

  // visit decorators that are in: ClassDeclaration / ClassExpression
  var visitClass = referencer.prototype.visitClass;
  referencer.prototype.visitClass = function(node) {
    visitDecorators.call(this, node);
    var typeParamScope;
    if (node.typeParameters) {
      typeParamScope = nestTypeParamScope(this.scopeManager, node);
    }
    // visit flow type: ClassImplements
    if (node.implements) {
      for (var i = 0; i < node.implements.length; i++) {
        checkIdentifierOrVisit.call(this, node.implements[i]);
      }
    }
    if (node.superTypeParameters) {
      for (var k = 0; k < node.superTypeParameters.params.length; k++) {
        checkIdentifierOrVisit.call(this, node.superTypeParameters.params[k]);
      }
    }
    visitClass.call(this, node);
    if (typeParamScope) {
      this.close(node);
    }
  };

  // visit decorators that are in: Property / MethodDefinition
  var visitProperty = referencer.prototype.visitProperty;
  referencer.prototype.visitProperty = function(node) {
    if (node.value && node.value.type === "TypeCastExpression") {
      visitTypeAnnotation.call(this, node.value);
    }
    visitDecorators.call(this, node);
    visitProperty.call(this, node);
  };

  // visit ClassProperty as a Property.
  referencer.prototype.ClassProperty = function(node) {
    if (node.typeAnnotation) {
      visitTypeAnnotation.call(this, node.typeAnnotation);
    }
    this.visitProperty(node);
  };

  // visit flow type in FunctionDeclaration, FunctionExpression, ArrowFunctionExpression
  var visitFunction = referencer.prototype.visitFunction;
  referencer.prototype.visitFunction = function(node) {
    var typeParamScope;
    if (node.typeParameters) {
      typeParamScope = nestTypeParamScope(this.scopeManager, node);
    }
    if (node.returnType) {
      checkIdentifierOrVisit.call(this, node.returnType);
    }
    // only visit if function parameters have types
    if (node.params) {
      for (var i = 0; i < node.params.length; i++) {
        var param = node.params[i];
        if (param.typeAnnotation) {
          checkIdentifierOrVisit.call(this, param);
        } else if (t.isAssignmentPattern(param)) {
          if (param.left.typeAnnotation) {
            checkIdentifierOrVisit.call(this, param.left);
          }
        }
      }
    }
    // set ArrayPattern/ObjectPattern visitor keys back to their original. otherwise
    // escope will traverse into them and include the identifiers within as declarations
    estraverses.forEach(function (estraverse) {
      estraverse.VisitorKeys.ObjectPattern = ["properties"];
      estraverse.VisitorKeys.ArrayPattern = ["elements"];
    });
    visitFunction.call(this, node);
    // set them back to normal...
    estraverses.forEach(function (estraverse) {
      estraverse.VisitorKeys.ObjectPattern = t.VISITOR_KEYS.ObjectPattern;
      estraverse.VisitorKeys.ArrayPattern = t.VISITOR_KEYS.ArrayPattern;
    });
    if (typeParamScope) {
      this.close(node);
    }
  };

  // visit flow type in VariableDeclaration
  var variableDeclaration = referencer.prototype.VariableDeclaration;
  referencer.prototype.VariableDeclaration = function(node) {
    if (node.declarations) {
      for (var i = 0; i < node.declarations.length; i++) {
        var id = node.declarations[i].id;
        var typeAnnotation = id.typeAnnotation;
        if (typeAnnotation) {
          checkIdentifierOrVisit.call(this, typeAnnotation);
        }
      }
    }
    variableDeclaration.call(this, node);
  };

  function createScopeVariable (node, name) {
    this.currentScope().variableScope.__define(name,
      new Definition(
        "Variable",
        name,
        node,
        null,
        null,
        null
      )
    );
  }

  referencer.prototype.TypeAlias = function(node) {
    createScopeVariable.call(this, node, node.id);
    var typeParamScope;
    if (node.typeParameters) {
      typeParamScope = nestTypeParamScope(this.scopeManager, node);
    }
    if (node.right) {
      visitTypeAnnotation.call(this, node.right);
    }
    if (typeParamScope) {
      this.close(node);
    }
  };

  referencer.prototype.DeclareModule =
  referencer.prototype.DeclareFunction =
  referencer.prototype.DeclareVariable =
  referencer.prototype.DeclareClass = function(node) {
    if (node.id) {
      createScopeVariable.call(this, node, node.id);
    }

    var typeParamScope;
    if (node.typeParameters) {
      typeParamScope = nestTypeParamScope(this.scopeManager, node);
    }
    if (typeParamScope) {
      this.close(node);
    }
  };
}

exports.parse = function (code, options) {
  options = options || {};
  eslintOptions.ecmaVersion = options.ecmaVersion = options.ecmaVersion || 6;
  eslintOptions.sourceType = options.sourceType = options.sourceType || "module";
  eslintOptions.allowImportExportEverywhere = options.allowImportExportEverywhere = options.allowImportExportEverywhere || false;
  if (options.sourceType === "module") {
    eslintOptions.globalReturn = false;
  } else {
    delete eslintOptions.globalReturn;
  }

  try {
    monkeypatch();
  } catch (err) {
    console.error(err.stack);
    process.exit(1);
  }

  return exports.parseNoPatch(code, options);
};

exports.parseNoPatch = function (code, options) {
  var opts = {
    sourceType: options.sourceType,
    allowImportExportEverywhere: options.allowImportExportEverywhere, // consistent with espree
    allowReturnOutsideFunction: true,
    allowSuperOutsideMethod: true,
    plugins: [
      "flow",
      "jsx",
      "asyncFunctions",
      "asyncGenerators",
      "classConstructorCall",
      "classProperties",
      "decorators",
      "doExpressions",
      "exponentiationOperator",
      "exportExtensions",
      "functionBind",
      "functionSent",
      "objectRestSpread",
      "trailingFunctionCommas",
      "dynamicImport"
    ]
  };

  var ast;
  try {
    ast = parse(code, opts);
  } catch (err) {
    if (err instanceof SyntaxError) {
      err.lineNumber = err.loc.line;
      err.column = err.loc.column + 1;

      // remove trailing "(LINE:COLUMN)" acorn message and add in esprima syntax error message start
      err.message = "Line " + err.lineNumber + ": " + err.message.replace(/ \((\d+):(\d+)\)$/, "") +
      // add codeframe
      "\n\n" +
      codeFrame(code, err.lineNumber, err.column, { highlightCode: true });
    }

    throw err;
  }

  // remove EOF token, eslint doesn't use this for anything and it interferes with some rules
  // see https://github.com/babel/babel-eslint/issues/2 for more info
  // todo: find a more elegant way to do this
  ast.tokens.pop();

  // convert tokens
  ast.tokens = babylonToEspree.toTokens(ast.tokens, tt, code);

  // add comments
  babylonToEspree.convertComments(ast.comments);

  // transform esprima and acorn divergent nodes
  babylonToEspree.toAST(ast, traverse, code);

  // ast.program.tokens = ast.tokens;
  // ast.program.comments = ast.comments;
  // ast = ast.program;

  // remove File
  ast.type = "Program";
  ast.sourceType = ast.program.sourceType;
  ast.directives = ast.program.directives;
  ast.body = ast.program.body;
  delete ast.program;
  delete ast._paths;

  babylonToEspree.attachComments(ast, ast.comments, ast.tokens);

  return ast;
};
<commit_msg>use `*` (#421)<commit_after>var babylonToEspree = require("./babylon-to-espree");
var pick            = require("lodash.pickby");
var Module          = require("module");
var path            = require("path");
var parse           = require("babylon").parse;
var t               = require("babel-types");
var tt              = require("babylon").tokTypes;
var traverse        = require("babel-traverse").default;
var codeFrame       = require("babel-code-frame");

var hasPatched = false;
var eslintOptions = {};

function createModule(filename) {
  var mod = new Module(filename);
  mod.filename = filename;
  mod.paths = Module._nodeModulePaths(path.dirname(filename));
  return mod;
}

function monkeypatch() {
  if (hasPatched) return;
  hasPatched = true;

  var eslintLoc;
  try {
    // avoid importing a local copy of eslint, try to find a peer dependency
    eslintLoc = Module._resolveFilename("eslint", module.parent);
  } catch (err) {
    try {
      // avoids breaking in jest where module.parent is undefined
      eslintLoc = require.resolve("eslint");
    } catch (err) {
      throw new ReferenceError("couldn't resolve eslint");
    }
  }

  // get modules relative to what eslint will load
  var eslintMod = createModule(eslintLoc);
  // contains all the instances of estraverse so we can modify them if necessary
  var estraverses = [];
  // ESLint v1.9.0 uses estraverse directly to work around https://github.com/npm/npm/issues/9663
  var estraverseOfEslint = eslintMod.require("estraverse");
  estraverses.push(estraverseOfEslint);
  Object.assign(estraverseOfEslint.VisitorKeys, t.VISITOR_KEYS);

  estraverses.forEach(function (estraverse) {
    estraverse.VisitorKeys.MethodDefinition.push("decorators");
    estraverse.VisitorKeys.Property.push("decorators");
  });

  // monkeypatch escope
  var escopeLoc = Module._resolveFilename("escope", eslintMod);
  var escopeMod = createModule(escopeLoc);
  var escope  = require(escopeLoc);
  var analyze = escope.analyze;
  escope.analyze = function (ast, opts) {
    opts.ecmaVersion = eslintOptions.ecmaVersion;
    opts.sourceType = eslintOptions.sourceType;
    if (eslintOptions.globalReturn !== undefined) {
      opts.nodejsScope = eslintOptions.globalReturn;
    }

    var results = analyze.call(this, ast, opts);
    return results;
  };

  // monkeypatch escope/referencer
  var referencerLoc;
  try {
    referencerLoc = Module._resolveFilename("./referencer", escopeMod);
  } catch (err) {
    throw new ReferenceError("couldn't resolve escope/referencer");
  }
  var referencerMod = createModule(referencerLoc);
  var referencer = require(referencerLoc);
  if (referencer.__esModule) {
    referencer = referencer.default;
  }

  // reference Definition
  var definitionLoc;
  try {
    definitionLoc = Module._resolveFilename("./definition", referencerMod);
  } catch (err) {
    throw new ReferenceError("couldn't resolve escope/definition");
  }
  var Definition = require(definitionLoc).Definition;

  // if there are decorators, then visit each
  function visitDecorators(node) {
    if (!node.decorators) {
      return;
    }
    for (var i = 0; i < node.decorators.length; i++) {
      if (node.decorators[i].expression) {
        this.visit(node.decorators[i]);
      }
    }
  }

  // iterate through part of t.VISITOR_KEYS
  var visitorKeysMap = pick(t.VISITOR_KEYS, function(k) {
    return t.FLIPPED_ALIAS_KEYS.Flow.concat([
      "ArrayPattern",
      "ClassDeclaration",
      "ClassExpression",
      "FunctionDeclaration",
      "FunctionExpression",
      "Identifier",
      "ObjectPattern",
      "RestElement"
    ]).indexOf(k) === -1;
  });

  var propertyTypes = {
    // loops
    callProperties: { type: "loop", values: ["value"] },
    indexers: { type: "loop", values: ["key", "value"] },
    properties: { type: "loop", values: ["value"] },
    types: { type: "loop" },
    params: { type: "loop" },
    // single property
    argument: { type: "single" },
    elementType: { type: "single" },
    qualification: { type: "single" },
    rest: { type: "single" },
    returnType: { type: "single" },
    // others
    typeAnnotation: { type: "typeAnnotation" },
    typeParameters: { type: "typeParameters" },
    id: { type: "id" }
  };

  function visitTypeAnnotation(node) {
    // get property to check (params, id, etc...)
    var visitorValues = visitorKeysMap[node.type];
    if (!visitorValues) {
      return;
    }

    // can have multiple properties
    for (var i = 0; i < visitorValues.length; i++) {
      var visitorValue = visitorValues[i];
      var propertyType = propertyTypes[visitorValue];
      var nodeProperty = node[visitorValue];
      // check if property or type is defined
      if (propertyType == null || nodeProperty == null) {
        continue;
      }
      if (propertyType.type === "loop") {
        for (var j = 0; j < nodeProperty.length; j++) {
          if (Array.isArray(propertyType.values)) {
            for (var k = 0; k < propertyType.values.length; k++) {
              checkIdentifierOrVisit.call(this, nodeProperty[j][propertyType.values[k]]);
            }
          } else {
            checkIdentifierOrVisit.call(this, nodeProperty[j]);
          }
        }
      } else if (propertyType.type === "single") {
        checkIdentifierOrVisit.call(this, nodeProperty);
      } else if (propertyType.type === "typeAnnotation") {
        visitTypeAnnotation.call(this, node.typeAnnotation);
      } else if (propertyType.type === "typeParameters") {
        for (var l = 0; l < node.typeParameters.params.length; l++) {
          checkIdentifierOrVisit.call(this, node.typeParameters.params[l]);
        }
      } else if (propertyType.type === "id") {
        if (node.id.type === "Identifier") {
          checkIdentifierOrVisit.call(this, node.id);
        } else {
          visitTypeAnnotation.call(this, node.id);
        }
      }
    }
  }

  function checkIdentifierOrVisit(node) {
    if (node.typeAnnotation) {
      visitTypeAnnotation.call(this, node.typeAnnotation);
    } else if (node.type === "Identifier") {
      this.visit(node);
    } else {
      visitTypeAnnotation.call(this, node);
    }
  }

  function nestTypeParamScope(manager, node) {
    var parentScope = manager.__currentScope;
    var scope = new escope.Scope(manager, "type-parameters", parentScope, node, false);
    manager.__nestScope(scope);
    for (var j = 0; j < node.typeParameters.params.length; j++) {
      var name = node.typeParameters.params[j];
      scope.__define(name, new Definition("TypeParameter", name, name));
    }
    scope.__define = function() {
      return parentScope.__define.apply(parentScope, arguments);
    };
    return scope;
  }

  // visit decorators that are in: ClassDeclaration / ClassExpression
  var visitClass = referencer.prototype.visitClass;
  referencer.prototype.visitClass = function(node) {
    visitDecorators.call(this, node);
    var typeParamScope;
    if (node.typeParameters) {
      typeParamScope = nestTypeParamScope(this.scopeManager, node);
    }
    // visit flow type: ClassImplements
    if (node.implements) {
      for (var i = 0; i < node.implements.length; i++) {
        checkIdentifierOrVisit.call(this, node.implements[i]);
      }
    }
    if (node.superTypeParameters) {
      for (var k = 0; k < node.superTypeParameters.params.length; k++) {
        checkIdentifierOrVisit.call(this, node.superTypeParameters.params[k]);
      }
    }
    visitClass.call(this, node);
    if (typeParamScope) {
      this.close(node);
    }
  };

  // visit decorators that are in: Property / MethodDefinition
  var visitProperty = referencer.prototype.visitProperty;
  referencer.prototype.visitProperty = function(node) {
    if (node.value && node.value.type === "TypeCastExpression") {
      visitTypeAnnotation.call(this, node.value);
    }
    visitDecorators.call(this, node);
    visitProperty.call(this, node);
  };

  // visit ClassProperty as a Property.
  referencer.prototype.ClassProperty = function(node) {
    if (node.typeAnnotation) {
      visitTypeAnnotation.call(this, node.typeAnnotation);
    }
    this.visitProperty(node);
  };

  // visit flow type in FunctionDeclaration, FunctionExpression, ArrowFunctionExpression
  var visitFunction = referencer.prototype.visitFunction;
  referencer.prototype.visitFunction = function(node) {
    var typeParamScope;
    if (node.typeParameters) {
      typeParamScope = nestTypeParamScope(this.scopeManager, node);
    }
    if (node.returnType) {
      checkIdentifierOrVisit.call(this, node.returnType);
    }
    // only visit if function parameters have types
    if (node.params) {
      for (var i = 0; i < node.params.length; i++) {
        var param = node.params[i];
        if (param.typeAnnotation) {
          checkIdentifierOrVisit.call(this, param);
        } else if (t.isAssignmentPattern(param)) {
          if (param.left.typeAnnotation) {
            checkIdentifierOrVisit.call(this, param.left);
          }
        }
      }
    }
    // set ArrayPattern/ObjectPattern visitor keys back to their original. otherwise
    // escope will traverse into them and include the identifiers within as declarations
    estraverses.forEach(function (estraverse) {
      estraverse.VisitorKeys.ObjectPattern = ["properties"];
      estraverse.VisitorKeys.ArrayPattern = ["elements"];
    });
    visitFunction.call(this, node);
    // set them back to normal...
    estraverses.forEach(function (estraverse) {
      estraverse.VisitorKeys.ObjectPattern = t.VISITOR_KEYS.ObjectPattern;
      estraverse.VisitorKeys.ArrayPattern = t.VISITOR_KEYS.ArrayPattern;
    });
    if (typeParamScope) {
      this.close(node);
    }
  };

  // visit flow type in VariableDeclaration
  var variableDeclaration = referencer.prototype.VariableDeclaration;
  referencer.prototype.VariableDeclaration = function(node) {
    if (node.declarations) {
      for (var i = 0; i < node.declarations.length; i++) {
        var id = node.declarations[i].id;
        var typeAnnotation = id.typeAnnotation;
        if (typeAnnotation) {
          checkIdentifierOrVisit.call(this, typeAnnotation);
        }
      }
    }
    variableDeclaration.call(this, node);
  };

  function createScopeVariable (node, name) {
    this.currentScope().variableScope.__define(name,
      new Definition(
        "Variable",
        name,
        node,
        null,
        null,
        null
      )
    );
  }

  referencer.prototype.TypeAlias = function(node) {
    createScopeVariable.call(this, node, node.id);
    var typeParamScope;
    if (node.typeParameters) {
      typeParamScope = nestTypeParamScope(this.scopeManager, node);
    }
    if (node.right) {
      visitTypeAnnotation.call(this, node.right);
    }
    if (typeParamScope) {
      this.close(node);
    }
  };

  referencer.prototype.DeclareModule =
  referencer.prototype.DeclareFunction =
  referencer.prototype.DeclareVariable =
  referencer.prototype.DeclareClass = function(node) {
    if (node.id) {
      createScopeVariable.call(this, node, node.id);
    }

    var typeParamScope;
    if (node.typeParameters) {
      typeParamScope = nestTypeParamScope(this.scopeManager, node);
    }
    if (typeParamScope) {
      this.close(node);
    }
  };
}

exports.parse = function (code, options) {
  options = options || {};
  eslintOptions.ecmaVersion = options.ecmaVersion = options.ecmaVersion || 6;
  eslintOptions.sourceType = options.sourceType = options.sourceType || "module";
  eslintOptions.allowImportExportEverywhere = options.allowImportExportEverywhere = options.allowImportExportEverywhere || false;
  if (options.sourceType === "module") {
    eslintOptions.globalReturn = false;
  } else {
    delete eslintOptions.globalReturn;
  }

  try {
    monkeypatch();
  } catch (err) {
    console.error(err.stack);
    process.exit(1);
  }

  return exports.parseNoPatch(code, options);
};

exports.parseNoPatch = function (code, options) {
  var opts = {
    sourceType: options.sourceType,
    allowImportExportEverywhere: options.allowImportExportEverywhere, // consistent with espree
    allowReturnOutsideFunction: true,
    allowSuperOutsideMethod: true,
    plugins: ["*"]
  };

  var ast;
  try {
    ast = parse(code, opts);
  } catch (err) {
    if (err instanceof SyntaxError) {
      err.lineNumber = err.loc.line;
      err.column = err.loc.column + 1;

      // remove trailing "(LINE:COLUMN)" acorn message and add in esprima syntax error message start
      err.message = "Line " + err.lineNumber + ": " + err.message.replace(/ \((\d+):(\d+)\)$/, "") +
      // add codeframe
      "\n\n" +
      codeFrame(code, err.lineNumber, err.column, { highlightCode: true });
    }

    throw err;
  }

  // remove EOF token, eslint doesn't use this for anything and it interferes with some rules
  // see https://github.com/babel/babel-eslint/issues/2 for more info
  // todo: find a more elegant way to do this
  ast.tokens.pop();

  // convert tokens
  ast.tokens = babylonToEspree.toTokens(ast.tokens, tt, code);

  // add comments
  babylonToEspree.convertComments(ast.comments);

  // transform esprima and acorn divergent nodes
  babylonToEspree.toAST(ast, traverse, code);

  // ast.program.tokens = ast.tokens;
  // ast.program.comments = ast.comments;
  // ast = ast.program;

  // remove File
  ast.type = "Program";
  ast.sourceType = ast.program.sourceType;
  ast.directives = ast.program.directives;
  ast.body = ast.program.body;
  delete ast.program;
  delete ast._paths;

  babylonToEspree.attachComments(ast, ast.comments, ast.tokens);

  return ast;
};
<|endoftext|>


<commit_before>#!/usr/bin/env node --harmony

console.log('Hello, world!');

const child_process = require('child_process');
child_process.exec("./node_modules/gulp/bin/gulp.js ./node_modules/build-scripts/gulpfile.js", function (error, stdout, stderr) {
	console.log('stdout: ' + stdout);
	console.log('stderr: ' + stderr);
	if (error !== null) {
		console.log('exec error: ' + error);
	}
});
<commit_msg>getting it working<commit_after>#!/usr/bin/env node --harmony

console.log('Hello, world!');

const child_process = require('child_process');
child_process.exec("./node_modules/build-scripts/node_modules/gulp/bin/gulp.js ./node_modules/build-scripts/gulpfile.js", function (error, stdout, stderr) {
	console.log('stdout: ' + stdout);
	console.log('stderr: ' + stderr);
	if (error !== null) {
		console.log('exec error: ' + error);
	}
});
<|endoftext|>


<commit_before>const tweet = require('./lib/tweet.js')

console.log('Running...')
// tweet.run()
setInterval(function () {
  tweet.run()
}, 20 * 60 * 1000) //20 min interval
<commit_msg>no intervals<commit_after>const tweet = require('./lib/tweet.js')

console.log('Running...')
tweet.run()
// setInterval(function () {
//   tweet.run()
// }, 20 * 60 * 1000) //20 min interval
<|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;

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(body);
						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_get') {
		answer = "Die neue Temperatur ist " + nlpJson['entities']['temperature']['0']['value'] + ' ' + nlpJson['entities']['temperature']['0']['type'];
	}
	else if (nlpJson['entities']['intent']['0']['value'] === 'restaurant') {
		answer = "Ich zeige dir eine Liste von Restaurants...";
	}*/
	else {
		answer = "Ich verstehe deine Anfrage nicht. Sorry.";
	}

    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>process first nlp outcomes<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;

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(body);
						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_get') {
		answer = "Die neue Temperatur ist " + nlpJson['entities']['temperature']['0']['value'] + ' ' + nlpJson['entities']['temperature']['0']['type'];
	}
	else if (nlpJson['entities']['intent']['0']['value'] === 'restaurant') {
		answer = "Ich zeige dir eine Liste von Restaurants...";
	}
	else {
		answer = "Ich verstehe deine Anfrage nicht. Sorry.";
	}

    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|>


<commit_before>#! /usr/bin/env node

var https       = require('https')
var http        = require('http')
var fs          = require('fs')
var join        = require('path').join

var btcprogress = require('btcprogress')
var route       = require('tiny-route')
var ecstatic    = require('ecstatic')
var stack       = require('stack')

var redirect    = require('./lib/https-redirect')
var config      = require('./config')
var api         = require('./api')
var views       = require('./views')

var autoApi     = require('./lib/auto-api')

var app = stack(
  route('/badge', btcprogress())
  autoApi(api, views),
  ecstatic(join(__dirname, 'static'))
)

var secure = process.getuid() === 0

if(secure) {

  https.createServer({
   cert: fs.readFileSync(config.cert),
   key : fs.readFileSync(config.key)
  }, app).listen(443)

  http.createServer(redirect()).listen(80)

} else {
  http.createServer(app).listen(config.port)
}
<commit_msg>log error, but don't crash<commit_after>#! /usr/bin/env node

var https       = require('https')
var http        = require('http')
var fs          = require('fs')
var join        = require('path').join

var btcprogress = require('btcprogress')
var route       = require('tiny-route')
var ecstatic    = require('ecstatic')
var stack       = require('stack')

var redirect    = require('./lib/https-redirect')
var config      = require('./config')
var api         = require('./api')
var views       = require('./views')

var autoApi     = require('./lib/auto-api')

var app = stack(
  route('/badge', btcprogress())
  autoApi(api, views),
  ecstatic(join(__dirname, 'static'))
)

var secure = process.getuid() === 0

if(secure) {

  https.createServer({
   cert: fs.readFileSync(config.cert),
   key : fs.readFileSync(config.key)
  }, app).listen(443)

  http.createServer(redirect()).listen(80)

  process.on('uncaughtException', function (err) {
    console.log('*****************************')
    console.error('Error at:', new Date)
    console.error(err.stack)
    console.log('*****************************')
  })

} else {
  http.createServer(app).listen(config.port)
}
<|endoftext|>


<commit_before>/*!
 * ninit <https://github.com/akileez/npinit>
 *
 * Copyright (c) 2015 Keith Williams.
 * Licensed under the ISC license.
 */

var mkdirp      = require('mkdirp')
var meta        = require('./app/meta')
var iterate     = require('toolz/src/async/iterate')
var assert      = require('assert')
// var install     = require('./app/install')
// var initgit     = require('./app/initgit')
// var installdeps = require('./app/installDependencies')
// var iterate     = require('./lib/iterate')
var display      = require('./lib/display')

function proc (opts, argv) {

  var operations = [
    getUserInfo,
    createDir
    // installFiles,
    // installDependencies,
    // initRepo,
  ]

  iterate.series(operations, function (err) {
    assert.ifError(err)
    display.done()
  })

  function getUserInfo (cb) {
    meta(opts, argv, function (res) {
      opts = res
      display.log(res)
      if (argv.dry) {
        display.heading('Options')
        display.dry(res)
        cb(null)
      } else {
        cb(null)
      }
    })
  }

  function createDir (cb) {
    if (!argv.dry) {
      mkdirp(opts.meta.packageName, function (err) {
        process.chdir(opts.meta.packageName)
        cb(null)
      })
    } else {
      cb(null)
    }
  }

  // function installFiles (cb) {
  //   install(opts, function (res) {
  //     // something here maybe?
  //     cb(null)
  //   })
  // }

  // function installDependencies (cb) {
  //   installdeps(opts, function (res) {
  //     cb(null)
  //   })
  // }

  // function initRepo (cb) {
  //   initgit(opts, function (res) {
  //     cb(null)
  //   })
  // }
}

module.exports = proc
<commit_msg>refactor: add templates (installFiles)<commit_after>/*!
 * ninit <https://github.com/akileez/npinit>
 *
 * Copyright (c) 2015 Keith Williams.
 * Licensed under the ISC license.
 */

var mkdirp      = require('mkdirp')
var meta        = require('./app/meta')
var iterate     = require('toolz/src/async/iterate')
var assert      = require('assert')
var tmpls       = require('./app/tmpls')
// var initgit     = require('./app/initgit')
// var installdeps = require('./app/installDependencies')
// var iterate     = require('./lib/iterate')
var display      = require('./lib/display')

function proc (opts, argv) {

  var operations = [
    getUserInfo,
    createDir,
    installFiles
    // installDependencies,
    // initRepo,
  ]

  iterate.series(operations, function (err) {
    assert.ifError(err)
    display.done()
  })

  function getUserInfo (cb) {
    meta(opts, argv, function (res) {
      opts = res
      display.log(res)
      if (argv.dry) {
        display.heading('Options')
        display.dry(res)
        cb(null)
      } else {
        cb(null)
      }
    })
  }

  function createDir (cb) {
    if (!argv.dry) {
      mkdirp(opts.meta.packageName, function (err) {
        process.chdir(opts.meta.packageName)
        cb(null)
      })
    } else {
      cb(null)
    }
  }

  function installFiles (cb) {
    if (!argv.dry) {
      tmpls(opts, function (res) {
        // something here maybe?
        cb(null)
      })
    } else {
      cb(null)
    }
  }

  // function installDependencies (cb) {
  //   installdeps(opts, function (res) {
  //     cb(null)
  //   })
  // }

  // function initRepo (cb) {
  //   initgit(opts, function (res) {
  //     cb(null)
  //   })
  // }
}

module.exports = proc
<|endoftext|>


<commit_before>#!/usr/bin/env node

/**
 * Module dependencies
 */

var repl = require('repl')
  , dom = require('jsdom')
  , Batch = require('batch')
  , es6 = require('es6-transpiler')
  , argv = require('minimist')(process.argv.slice(2))

var exit = process.exit;
var put = console.log.bind(console);
var tasks = new Batch().concurrency(1);
var runtime = null;
var window = null;

// catch signal
process.on('SIGINT', exit);

function help () {
  console.log("usage: w625 [-hV] [src] [--script=script]")
}

tasks.push(function (next) {
  var src = argv._[0] || '';

  if (argv.h || argv.help) {
    help();
    exit(0);
  } else if (argv.V || argv.version) {
    console.log("w625-repl v%s", require('./package').version);
    exit(0);
  }

  runtime = dom.env(src, [].concat(argv.script || []), ready);

  function ready (err, win) {
    if (err) {
      return next(err);
    }

    window = win;
    next();
  }
});

tasks.push(function (next) {
  var r = repl.start({
    prompt: 'dom> ',
    input: process.stdin,
    output: process.stdout,
    useGlobal: false,
    eval: oneval
  });

  r.context = window;
  window.console = console;

  r.on('exit', function () {
    put();
    exit(0);
  });

  function oneval (src, context, filename, done) {
    var hasReferenceError = false;
    var result = null;
    var code = null;

    // extract source
    src = src.slice(1, -2);

    // transform
    try {
      code = es6.run({
        src: src,
        filename: 'repl',
        disallowUnknownReferences: false,
        globals: (
          Object.keys(context)
          .map(function (k) {
            return k;
          })
          .reduce(function (o, k) {
            o[k] = true;
            return o;
          }, {})
        )
      });
    } catch (err) {
      return done(err);
    }

    // evaluate
    try { result = context.eval(code.src); }
    catch (err) { }

    if (code.errors.join(' ').toLowerCase().indexOf('reference') > 0) {
      hasReferenceError = true;
    }

    // if no result attempt to evaluate source
    if (null == result && code.errors.length && true === hasReferenceError) {
      try { result = context.eval(src); }
      catch (err) {
        console.error(err, code.errors)
      }
    }

    done(null, result);
  }
});

// run
tasks.end(function (err) {
  if (err) {
    console.error(err.message);
    exit(1);
  }
});
<commit_msg>fix soure<commit_after>#!/usr/bin/env node

/**
 * Module dependencies
 */

var repl = require('repl')
  , dom = require('jsdom')
  , Batch = require('batch')
  , es6 = require('es6-transpiler')
  , argv = require('minimist')(process.argv.slice(2))

var exit = process.exit;
var put = console.log.bind(console);
var tasks = new Batch().concurrency(1);
var runtime = null;
var window = null;

// catch signal
process.on('SIGINT', exit);

function help () {
  console.log("usage: w625 [-hV] [src] [--script=script]")
}

tasks.push(function (next) {
  var src = argv._[0] || '';

  if (argv.h || argv.help) {
    help();
    exit(0);
  } else if (argv.V || argv.version) {
    console.log("w625-repl v%s", require('./package').version);
    exit(0);
  }

  runtime = dom.env(src, [].concat(argv.script || []), ready);

  function ready (err, win) {
    if (err) {
      return next(err);
    }

    window = win;
    next();
  }
});

tasks.push(function (next) {
  var r = repl.start({
    prompt: 'dom> ',
    input: process.stdin,
    output: process.stdout,
    useGlobal: false,
    eval: oneval
  });

  r.context = window;
  window.console = console;

  r.on('exit', function () {
    put();
    exit(0);
  });

  function oneval (src, context, filename, done) {
    var hasReferenceError = false;
    var result = null;
    var code = null;

    // extract source
    if (src.match(/\n\)$/)) {
      src = src.slice(1, -2);
    }

    // transform
    try {
      code = es6.run({
        src: src,
        filename: 'repl',
        disallowUnknownReferences: false,
        globals: (
          Object.keys(context)
          .map(function (k) {
            return k;
          })
          .reduce(function (o, k) {
            o[k] = true;
            return o;
          }, {})
        )
      });
    } catch (err) {
      return done(err);
    }

    // evaluate
    try { result = context.eval(code.src); }
    catch (err) { }

    if (code.errors.join(' ').toLowerCase().indexOf('reference') > 0) {
      hasReferenceError = true;
    }

    // if no result attempt to evaluate source
    if (null == result && code.errors.length && true === hasReferenceError) {
      try { result = context.eval(src); }
      catch (err) {
        console.error(err, code.errors)
      }
    }

    done(null, result);
  }
});

// run
tasks.end(function (err) {
  if (err) {
    console.error(err.message);
    exit(1);
  }
});
<|endoftext|>


<commit_before>'use strict'

require("babel-core/register")
require("babel-polyfill")

const convert = require('pinyin-convert')
const split = require('pinyin-split')

const execute = () => {
	const text = document.querySelector('#input').value
	if (text) {
		const re = /^[a-züāáǎàēéěèōóǒòūúǔùīíǐì]+$/i
		if (re.test(text)) {
			split(text).then((data) => {
				document.querySelector('#output').innerHTML = data.join(' ')
			}, console.log)
		} else {
			convert(text, {keepSpaces: true}).then((data) => {
				document.querySelector('#output').innerHTML = data
			}, console.log)
		}
	}
}

document.querySelector('#convert').addEventListener('click', execute)

document.querySelector('#input').addEventListener('keyup', (event) => {
	if (event.keyCode == 13) {
		event.preventDefault()
		execute()
	}
})<commit_msg>Update to use new module pinyin-api<commit_after>'use strict'

require("babel-core/register")
require("babel-polyfill")

const pinyin = require('pinyin-api')

const execute = () => {
	const text = document.querySelector('#input').value
	if (text) {
		const re = /^[a-züāáǎàēéěèōóǒòūúǔùīíǐì]+$/i
		if (re.test(text)) {
			pinyin.split(text).then((data) => {
				document.querySelector('#output').innerHTML = data.join(' ')
			}, console.log)
		} else {
			pinyin.convert(text, {keepSpaces: true}).then((data) => {
				document.querySelector('#output').innerHTML = data
			}, console.log)
		}
	}
}

document.querySelector('#convert').addEventListener('click', execute)

document.querySelector('#input').addEventListener('keyup', (event) => {
	if (event.keyCode == 13) {
		event.preventDefault()
		execute()
	}
})
<|endoftext|>


<commit_before>'use strict';

const express = require('express');
const https = require('https');
const bodyParser = require('body-parser');
// const crypto = require('crypto');
const xhub = require('express-x-hub');
const config = require('config');

var app = express();
app.set('port', (process.env.PORT || 5000));
app.listen(app.get('port'));
app.use(xhub({ algorithm: 'sha1', secret: process.env.APP_SECRET }));
app.use(bodyParser.json());
app.use(express.static('public'));

const APP_SECRET = (process.env.NOTIFIER_APP_SECRET) ? process.env.NOTIFIER_APP_SECRET : config.get('appSecret');
const VALIDATION_TOKEN = (process.env.NOTIFIER_VALIDATION_TOKEN) ? (process.env.NOTIFIER_VALIDATION_TOKEN) : config.get('validationToken');
const PAGE_ACCESS_TOKEN = (process.env.NOTIFIER_PAGE_ACCESS_TOKEN) ? (process.env.NOTIFIER_PAGE_ACCESS_TOKEN) : config.get('pageAccessToken');
const SERVER_URL = (process.env.SERVER_URL) ? (process.env.SERVER_URL) : config.get('serverURL');

if (!(APP_SECRET && VALIDATION_TOKEN && PAGE_ACCESS_TOKEN && SERVER_URL)) {
	console.error("Missing config values");
	process.exit(1);
}

app.get('/', function (req, res) {
	if (req.query['hub.mode'] === 'subscribe' && req.query['hub.verify_token'] === VALIDATION_TOKEN) {
		console.log("Validating webhook");
		res.status(200).send(req.query['hub.challenge']);
	} else {
		console.error("Failed validation. Make sure the validation tokens match.");
		res.sendStatus(403);
	}
});

app.post('/webhook', function (req, res) {
	if (req.body.object === 'page') {
		req.body.entry.forEach(function (entry) {
			var pageID = entry.id;
			var timeOfEvent = entry.time;

			entry.messaging.forEach(function (event) {
				if (event.message) {
					receivedMessage(event);
				} else {
					console.log("Webhook received unknown event: ", event);
				}
			});
		});

		res.sendStatus(200);
  }
});

function verifyRequestSignature(req, res, buf) {
	if (req.isXHub()) {
		console.log('request header X-Hub-Signature found, validating');

		if (req.isXHubValid()) {
			console.log('request header X-Hub-Signature validated');
			res.send('Verified!\n');
		}
	} else {
		console.log('Warning - request header X-Hub-Signature not present or invalid');
		res.send('Failed to verify!\n');
	}

	console.log(req.body);
	// res.sendStatus(200);
}

function receivedMessage(event) {
	var senderID = event.sender.id;
	var recipientID = event.recipient.id;
	var timeOfMessage = event.timestamp;
	var message = event.message;

	console.log("Received message for user %d and page %d at %d with message:", senderID, recipientID, timeOfMessage);
	console.log(JSON.stringify(message));

	var messageId = message.mid;
	var messageText = message.text;
	var messageAttachments = message.attachments;

	if (messageText) {
		switch (messageText) {
			case 'generic':
			sendGenericMessage(senderID);
			break;

		default:
			sendTextMessage(senderID, messageText);
		}
	} else if (messageAttachments) {
		sendTextMessage(senderID, "Message with attachment received");
	}
}

function sendGenericMessage(recipientId) {
	sendTextMessage(recipientId, 'This is a response to a message of "generic"');
}

function sendTextMessage(recipientId, messageText) {
	var messageData = {
		recipient: {
			id: recipientId
		},
		message: {
			text: messageText
		}
	};

	callSendAPI(messageData);
}

function callSendAPI(messageData) {
	request({
		uri: 'https://graph.facebook.com/v2.6/me/messages',
		qs: { access_token: PAGE_ACCESS_TOKEN },
		method: 'POST',
		json: messageData
	}, function (error, response, body) {
		if (!error && response.statusCode == 200) {
			var recipientId = body.recipient_id;
			var messageId = body.message_id;

			console.log("Successfully sent generic message with id %s to recipient %s", messageId, recipientId);
		} else {
			console.error("Unable to send message.");
			console.error(response);
			console.error(error);
		}
	});
}

app.listen(app.get('port'), function () {
	console.log('Node app is running on port', app.get('port'));
});

module.exports = app;<commit_msg>constant definition order update<commit_after>'use strict';

// packages

const express = require('express');
const https = require('https');
const bodyParser = require('body-parser');
// const crypto = require('crypto');
const xhub = require('express-x-hub');
const config = require('config');

// pull configuration constants

const APP_SECRET = (process.env.NOTIFIER_APP_SECRET) ? process.env.NOTIFIER_APP_SECRET : config.get('appSecret');
const VALIDATION_TOKEN = (process.env.NOTIFIER_VALIDATION_TOKEN) ? (process.env.NOTIFIER_VALIDATION_TOKEN) : config.get('validationToken');
const PAGE_ACCESS_TOKEN = (process.env.NOTIFIER_PAGE_ACCESS_TOKEN) ? (process.env.NOTIFIER_PAGE_ACCESS_TOKEN) : config.get('pageAccessToken');
const SERVER_URL = (process.env.SERVER_URL) ? (process.env.SERVER_URL) : config.get('serverURL');

var app = express();
app.set('port', (process.env.PORT || 5000));
app.listen(app.get('port'));
app.use(xhub({ algorithm: 'sha1', secret: APP_SECRET }));
app.use(bodyParser.json());
app.use(express.static('public'));

if (!(APP_SECRET && VALIDATION_TOKEN && PAGE_ACCESS_TOKEN && SERVER_URL)) {
	console.error("Missing config values");
	process.exit(1);
}

app.get('/', function (req, res) {
	if (req.query['hub.mode'] === 'subscribe' && req.query['hub.verify_token'] === VALIDATION_TOKEN) {
		console.log("Validating webhook");
		res.status(200).send(req.query['hub.challenge']);
	} else {
		console.error("Failed validation. Make sure the validation tokens match.");
		res.sendStatus(403);
	}
});

app.post('/webhook', function (req, res) {
	if (req.body.object === 'page') {
		req.body.entry.forEach(function (entry) {
			var pageID = entry.id;
			var timeOfEvent = entry.time;

			entry.messaging.forEach(function (event) {
				if (event.message) {
					receivedMessage(event);
				} else {
					console.log("Webhook received unknown event: ", event);
				}
			});
		});

		res.sendStatus(200);
  }
});

function verifyRequestSignature(req, res, buf) {
	if (req.isXHub()) {
		console.log('request header X-Hub-Signature found, validating');

		if (req.isXHubValid()) {
			console.log('request header X-Hub-Signature validated');
			res.send('Verified!\n');
		}
	} else {
		console.log('Warning - request header X-Hub-Signature not present or invalid');
		res.send('Failed to verify!\n');
	}

	console.log(req.body);
	// res.sendStatus(200);
}

function receivedMessage(event) {
	var senderID = event.sender.id;
	var recipientID = event.recipient.id;
	var timeOfMessage = event.timestamp;
	var message = event.message;

	console.log("Received message for user %d and page %d at %d with message:", senderID, recipientID, timeOfMessage);
	console.log(JSON.stringify(message));

	var messageId = message.mid;
	var messageText = message.text;
	var messageAttachments = message.attachments;

	if (messageText) {
		switch (messageText) {
			case 'generic':
			sendGenericMessage(senderID);
			break;

		default:
			sendTextMessage(senderID, messageText);
		}
	} else if (messageAttachments) {
		sendTextMessage(senderID, "Message with attachment received");
	}
}

function sendGenericMessage(recipientId) {
	sendTextMessage(recipientId, 'This is a response to a message of "generic"');
}

function sendTextMessage(recipientId, messageText) {
	var messageData = {
		recipient: {
			id: recipientId
		},
		message: {
			text: messageText
		}
	};

	callSendAPI(messageData);
}

function callSendAPI(messageData) {
	request({
		uri: 'https://graph.facebook.com/v2.6/me/messages',
		qs: { access_token: PAGE_ACCESS_TOKEN },
		method: 'POST',
		json: messageData
	}, function (error, response, body) {
		if (!error && response.statusCode == 200) {
			var recipientId = body.recipient_id;
			var messageId = body.message_id;

			console.log("Successfully sent generic message with id %s to recipient %s", messageId, recipientId);
		} else {
			console.error("Unable to send message.");
			console.error(response);
			console.error(error);
		}
	});
}

app.listen(app.get('port'), function () {
	console.log('Node app is running on port', app.get('port'));
});

module.exports = app;<|endoftext|>


<commit_before>var extend = require('util')._extend
  , request = require('request')
  , cheerio = require('cheerio');

var noop = function () {};

function parseMetadata (opts, html, contentType) {
  var $ = cheerio.load(html)
    , metadata = {};

  if (opts.fields.url) {
    metadata.url = opts.url;
  }

  if (opts.fields.contentType) {
    metadata.contentType = contentType || 'text/html';
  }

  if (opts.fields.meta) {
    metadata.meta = {};

    // parse all <meta> tags and attach to metdata.meta object:
    $('head meta').each(function (index, elem) {
      var $this = $(this)
        , m = {};

      // prioritize key tag by: name, http-equiv, property:
      m.name = $this.attr('name') || $this.attr('http-equiv') || $this.attr('property');
      m.content = $this.attr('content');

      // if there is a name key, add it to the meta object, otherwise discard:
      if (m.name && m.content) {
        metadata.meta[m.name] = m.content;
      }
    });
  }

  if (opts.fields.title) {
    // parse the <title> tag:
    metadata.title = $('head title').last().text();
  }
  return metadata;
}

module.exports = function (opts, cb) {
  var defaultOpts = {
    fields: {
      url: true,
      userAgent: 'metadata request',
      meta: true,
      title: true,
      contentType: true
    }
  };

  // extend the default options with those passed in:
  opts = extend(defaultOpts, opts);
  if (!cb) { cb = noop; }

  // url is required:
  if (!opts.url && !opts.html) {
    process.nextTick(function () { cb('Missing url or html option'); });
    return;
  }

  if (opts.url) {
    // retrieve html for further processing:
    request({url:opts.url, headers: {'User-Agent':opts.userAgent}}, function (err, response, html) {
      if (err) {
        cb('Error Retrieving HTML', err);
        return;
      }

      // complete!
      cb(null, parseMetadata(opts, html, response.headers['content-type']));
    });
  } else {
    // have the HTML, parse and return via callback:
    process.nextTick(function () { cb(null, parseMetadata(opts, opts.html)); });
  }
};
<commit_msg>Moving userAgent option out of default fields<commit_after>var extend = require('util')._extend
  , request = require('request')
  , cheerio = require('cheerio');

var noop = function () {};

function parseMetadata (opts, html, contentType) {
  var $ = cheerio.load(html)
    , metadata = {};

  if (opts.fields.url) {
    metadata.url = opts.url;
  }

  if (opts.fields.contentType) {
    metadata.contentType = contentType || 'text/html';
  }

  if (opts.fields.meta) {
    metadata.meta = {};

    // parse all <meta> tags and attach to metdata.meta object:
    $('head meta').each(function (index, elem) {
      var $this = $(this)
        , m = {};

      // prioritize key tag by: name, http-equiv, property:
      m.name = $this.attr('name') || $this.attr('http-equiv') || $this.attr('property');
      m.content = $this.attr('content');

      // if there is a name key, add it to the meta object, otherwise discard:
      if (m.name && m.content) {
        metadata.meta[m.name] = m.content;
      }
    });
  }

  if (opts.fields.title) {
    // parse the <title> tag:
    metadata.title = $('head title').last().text();
  }
  return metadata;
}

module.exports = function (opts, cb) {
  var defaultOpts = {
    userAgent: 'metadata request'
    fields: {
      url: true,
      meta: true,
      title: true,
      contentType: true
    }
  };

  // extend the default options with those passed in:
  opts = extend(defaultOpts, opts);
  if (!cb) { cb = noop; }

  // url is required:
  if (!opts.url && !opts.html) {
    process.nextTick(function () { cb('Missing url or html option'); });
    return;
  }

  if (opts.url) {
    // retrieve html for further processing:
    request({url:opts.url, headers: {'User-Agent':opts.userAgent}}, function (err, response, html) {
      if (err) {
        cb('Error Retrieving HTML', err);
        return;
      }

      // complete!
      cb(null, parseMetadata(opts, html, response.headers['content-type']));
    });
  } else {
    // have the HTML, parse and return via callback:
    process.nextTick(function () { cb(null, parseMetadata(opts, opts.html)); });
  }
};
<|endoftext|>