<commit_before>#!/usr/bin/env node
"use strict";

//    EXTERNAL DEPENDENCIES
const fs                = require("fs"),
      iq                = require("inquirer"),
      octonode          = require("octonode"),
      gitLabel          = require("git-label");
//    UTILS ARE STANDALONE METHODS WITH NO DEPENDENCIES
const banner            = require("./utils/banners"),
      configGitLabel    = require("./utils/configGitLabel"),
      removeAll         = require("./utils/removeAll");
//    PROMPTS ARE THE PROMPTS ARRAYS FOR VARIOUS QUESTIONS
const prompts           = {
        addCustom:        require("./prompts/addCustom"),
        deleteConfirm:    require("./prompts/deleteConfirm"),
        mainMenu:         require("./prompts/mainMenu")
      };
//    MODULES ARE UTILS WITH DEPENDENCIES
const readRepo          = require("./modules/readRepo"),
      setToken          = require("./modules/setToken"),
      fetchToken        = require("./modules/fetchToken"),
      isGitRepo         = require("./modules/isGitRepo"),
      readGitConfig     = require("./modules/readGitConfig");

/////reset the token fn
const resetToken = () => {
  banner.resetToken();
  return setToken(gitLabelmaker);
};
/////add custom labels fn
const addCustom = (repo, token) => {
  banner.addCustom();
  return doCustomLabelPrompts( [], handleAddPrompts.bind(null, repo, token));
};
/////add labels from package
const addFromPackage = (repo, token, path) => {
  gitLabel.find( removeAll( path, [ "`", '"', "'" ] ) )
    .then((newLabels)=>{
      return gitLabel.add( configGitLabel(repo, token), newLabels )
    })
    .then(console.log)
    .catch(console.warn);
};
/////

//  Recursivly asks if you want to add another new label, then calls a callback when youre all done
const doCustomLabelPrompts = ( newLabels, done ) => {
        iq.prompt( prompts.addCustom, ( answers ) => {
          newLabels.push({ name: answers.labelName, color: answers.labelColor });
          if ( answers.addAnother ){
            doCustomLabelPrompts( newLabels, done );
          }else{
            done( newLabels );
          }
        });
      };

//    TODO: this function is ripe for some refactoring
const doRemovePrompts = ( token, repo ) => {
        octonode.client(token).get('/repos/'+repo+'/labels', (e, status, body) => {
          iq.prompt([{
            name:     "removals",
            type:     "checkbox",
            message:  "Which labels would you like to remove?",
            choices:  body.map((label) => label.name),
            validate: (removals) => {
                return removals.length === 0 ? "Please select at least one label to remove." : true;
            },
            filter:   (removals) => {
              return body.filter((label) => {
                return removals.indexOf(label.name) > -1 ? { name: label.name, color: label.color } : false;
              });
            }
          }], (answers) => {
            //  Tell the user what they're about to lose
            console.log("About to delete the following labels:")
            answers.removals.map((label)=>{
              return " - "+label.name;
            }).forEach((prettyLabel)=>{
              console.log(prettyLabel);
            });
            //  Ya sure ya wanna do this bud?
            iq.prompt([prompts.deleteConfirm], (confirmRemove) => {
              if ( confirmRemove.youSure ) {
                gitLabel.remove( configGitLabel(repo, token), answers.removals )
                .then(console.log)
                .catch(console.warn);
              } else {
                process.exit(1);
              }
            })

          });
        });
      };

//    TODO: could be refactored to return the git.add as a promise..?
const handleAddPrompts = (repo, token, newLabels) => {
        gitLabel.add( configGitLabel(repo, token), newLabels )
          .then(console.log)
          .catch(console.warn);
      };

//    TODO: refactor into some kind of switch statement?
const handleMainPrompts = (repo, token, ans) => {
        if ( ans.main.toLowerCase() === "reset token" ){
          resetToken();
        }
        if ( ans.main.toLowerCase() === "add custom labels" ){
          addCustom(repo, token);
        }
        if ( ans.main.toLowerCase() === "add labels from package" ){
          banner.addFromPackage();
          let packagePath;
          iq.prompt([{
            name: "path",
            type: "input",
            message: "What is the path & name of the package you want to use? (eg: `packages/my-label-pkg.json`)",
            validate: (path) => {
              try {
                if (path.indexOf(".json") < 0) throw "Not a JSON file";
                packagePath = path.indexOf("/") === 0 ? path.replace("/","") : path;
                packagePath = removeAll( packagePath, [ "`", '"', "'" ] );
                if ( fs.statSync( process.cwd()+"/"+packagePath ) ){
                  return true;
                }
              } catch (e){
                return e;
              }
            }
          }], (ans) => {
            addFromPackage( repo, token, ans.path );
          });
        }
        if ( ans.main.toLowerCase() === "remove labels" ){
          banner.removeLabels();
          return doRemovePrompts(token, repo);
        }
      };

//    Kicks things off and arrows program to
const gitLabelmaker = () => {

  Promise.all([ isGitRepo(), readGitConfig(), fetchToken() ])
  .then(( values )=>{
    let repo = readRepo(values[1]);
    let token = values[2];
    banner.welcome();
    iq.prompt( prompts.mainMenu, handleMainPrompts.bind(null, repo, token));
  })
  .catch((e)=>{
    console.warn(e.err);
    if (e.id === "TOKEN") {
      setToken(gitLabelmaker);
    } else {
      process.exit(1);
    }
  });

};

gitLabelmaker();

////////////////////
//  CODE GRAVEYARD
/////////////////////
//    A simple prompt util, returns a promise with the prompt answers
///   NOT IN USE
const prompt = (prompts) => {
        return new Promise((res, rej)=>{
          iq.prompt(prompts, (answers) => {
            if ( !answers ) rej(answers);
            res(answers);
          });
        });
      };

//    A simple util that promisifies our GitHub API call
///   NOT IN USE
const requestLabels = ( token, repo ) => {
        return new Promise((res, rej)=>{
          octonode.client(token).get('/repos/'+repo+'/labels', (e, status, body) => {
            if (e) rej(e);
            res(body);
          });
        });
      };
<commit_msg>More cleanup<commit_after>#!/usr/bin/env node
"use strict";

//    EXTERNAL DEPENDENCIES
const fs                = require("fs"),
      iq                = require("inquirer"),
      octonode          = require("octonode"),
      gitLabel          = require("git-label");
//    UTILS ARE STANDALONE METHODS WITH NO DEPENDENCIES
const alertDeletes      = require("./utils/alertDeletes"),
      banner            = require("./utils/banners"),
      configGitLabel    = require("./utils/configGitLabel"),
      removeAll         = require("./utils/removeAll"),
      validateRemovals  = require("./utils/validateRemovals");
//    PROMPTS ARE THE PROMPTS ARRAYS FOR VARIOUS QUESTIONS
const prompts           = {
        addCustom:        require("./prompts/addCustom"),
        deleteConfirm:    require("./prompts/deleteConfirm"),
        mainMenu:         require("./prompts/mainMenu")
      };
//    MODULES ARE UTILS WITH DEPENDENCIES
const readRepo          = require("./modules/readRepo"),
      setToken          = require("./modules/setToken"),
      fetchToken        = require("./modules/fetchToken"),
      isGitRepo         = require("./modules/isGitRepo"),
      readGitConfig     = require("./modules/readGitConfig"),
      requestLabels     = require("./modules/requestLabels");

/////reset the token fn
const resetToken = () => {
  banner.resetToken();
  return setToken(gitLabelmaker);
};
/////add custom labels fn
const addCustom = (repo, token) => {
  banner.addCustom();
  return doCustomLabelPrompts( [], (newLabels) => {
    gitLabel.add( configGitLabel(repo, token), newLabels )
      .then(console.log)
      .catch(console.warn);
  });
};
/////add labels from package
const addFromPackage = (repo, token, path) => {
  gitLabel.find( removeAll( path, [ "`", '"', "'" ] ) )
    .then((newLabels)=>{
      return gitLabel.add( configGitLabel(repo, token), newLabels )
    })
    .then(console.log)
    .catch(console.warn);
};
/////

//  Recursivly asks if you want to add another new label, then calls a callback when youre all done
const doCustomLabelPrompts = ( newLabels, done ) => {
        iq.prompt( prompts.addCustom, ( answers ) => {
          newLabels.push({ name: answers.labelName, color: answers.labelColor });
          if ( answers.addAnother ){
            doCustomLabelPrompts( newLabels, done );
          }else{
            done( newLabels );
          }
        });
      };

//    TODO: could be refactored to return the git.add as a promise..?
const handleAddPrompts = (repo, token, newLabels) => {
        gitLabel.add( configGitLabel(repo, token), newLabels )
          .then(console.log)
          .catch(console.warn);
      };

//    TODO: refactor into some kind of switch statement?
const handleMainPrompts = (repo, token, ans) => {
        if ( ans.main.toLowerCase() === "reset token" ){
          resetToken();
        }
        if ( ans.main.toLowerCase() === "add custom labels" ){
          addCustom(repo, token);
        }
        if ( ans.main.toLowerCase() === "add labels from package" ){
          banner.addFromPackage();
          let packagePath;
          iq.prompt([{
            name: "path",
            type: "input",
            message: "What is the path & name of the package you want to use? (eg: `packages/my-label-pkg.json`)",
            validate: (path) => {
              try {
                if (path.indexOf(".json") < 0) throw "Not a JSON file";
                packagePath = path.indexOf("/") === 0 ? path.replace("/","") : path;
                packagePath = removeAll( packagePath, [ "`", '"', "'" ] );
                if ( fs.statSync( process.cwd()+"/"+packagePath ) ){
                  return true;
                }
              } catch (e){
                return e;
              }
            }
          }], (ans) => {
            addFromPackage( repo, token, ans.path );
          });
        }
        if ( ans.main.toLowerCase() === "remove labels" ){
          banner.removeLabels();
          requestLabels(repo, token)
            .then((body)=>{
              iq.prompt([{
                name:     "removals",
                type:     "checkbox",
                message:  "Which labels would you like to remove?",
                choices:  body.map((label) => label.name),
                validate: validateRemovals,
                filter:   (removals) => {
                  return body.filter((label) => {
                    return removals.indexOf(label.name) > -1 ? { name: label.name, color: label.color } : false;
                  });
                }
              }], (answers) => {
                //  Tell the user what they're about to lose
                console.log("About to delete the following labels:")
                alertDeletes();// alerts the list of labels to be removed

                //  Ya sure ya wanna do this bud?
                iq.prompt([prompts.deleteConfirm], (confirmRemove) => {
                  if ( confirmRemove.youSure ) {
                    gitLabel.remove( configGitLabel(repo, token), answers.removals )
                      .then(console.log)
                      .catch(console.warn);
                  } else {
                    gitLabelmaker();
                  }
                })
              });
            })
            .catch(console.warn);
        }
      };

//    Kicks things off and arrows program to
const gitLabelmaker = () => {
  //  Checks for three things at once, each will return a nice error obj if they fail
  Promise.all([ isGitRepo(), readGitConfig(), fetchToken() ])
    .then(( values )=>{
      let repo = readRepo(values[1]);
      let token = values[2];
      banner.welcome();
      iq.prompt( prompts.mainMenu, handleMainPrompts.bind(null, repo, token));
    })
    .catch((e)=>{
      console.warn(e.err);
      if (e.id === "TOKEN") {
        setToken(gitLabelmaker);
      } else {
        process.exit(1);
      }
    });
};

gitLabelmaker();

////////////////////
//  CODE GRAVEYARD
/////////////////////
//    A simple prompt util, returns a promise with the prompt answers
///   NOT IN USE
const prompt = (prompts) => {
        return new Promise((res, rej)=>{
          iq.prompt(prompts, (answers) => {
            if ( !answers ) rej(answers);
            res(answers);
          });
        });
      };
<|endoftext|>


<commit_before>var posthtml = require('posthtml');
var fs = require('fs');
var argv = require('yargs')
	.usage('Usage: $0 [--config|-c config.json] [--output|-o output.html] [--input|-i input.html]')
	.example('posthtml -o output.html input.html', 'Default example')
	.config('c', function (configPath) {
		return {
			plugins: getConfig(configPath)
		}
	})
	.alias('c', 'config')
	.alias('i', 'input')
	.alias('o', 'output')
	.requiresArg(['o'])
	.version(function () {
		return [
			'posthtml version',
			require('./node_modules/posthtml/package.json').version
		].join(' ');
	}, 'v')
	.alias('v', 'version')
	.help('h')
	.alias('h', 'help')
	.argv;

function getConfig(configPath) {
	var path = configPath || './package.json';
	return JSON.parse(fs.readFileSync(path, 'utf-8'))
}

var html = fs.readFileSync(argv.input, 'utf8');
var config = argv.plugins ? argv.plugins : getConfig().posthtml;

var plugins = config.require.map(function (name) {
	return require(name)(argv.plugins[name]);
});

posthtml(plugins)
	.process(html)
	.then(function (result) {
		fs.writeFileSync(argv.output, result.html);
	});
<commit_msg>fix xo error report<commit_after>var posthtml = require('posthtml');
var fs = require('fs');
var argv = require('yargs')
	.usage('Usage: $0 [--config|-c config.json] [--output|-o output.html] [--input|-i input.html]')
	.example('posthtml -o output.html input.html', 'Default example')
	.config('c', function (configPath) {
		return {
			plugins: getConfig(configPath)
		};
	})
	.alias('c', 'config')
	.alias('i', 'input')
	.alias('o', 'output')
	.requiresArg(['o'])
	.version(function () {
		return [
			'posthtml version',
			require('./node_modules/posthtml/package.json').version
		].join(' ');
	}, 'v')
	.alias('v', 'version')
	.help('h')
	.alias('h', 'help')
	.argv;

function getConfig(configPath) {
	var path = configPath || './package.json';
	return JSON.parse(fs.readFileSync(path, 'utf-8'));
}

var html = fs.readFileSync(argv.input, 'utf8');
var config = argv.plugins ? argv.plugins : getConfig().posthtml;

var plugins = config.require.map(function (name) {
	return require(name)(argv.plugins[name]);
});

posthtml(plugins)
	.process(html)
	.then(function (result) {
		fs.writeFileSync(argv.output, result.html);
	});
<|endoftext|>


<commit_before>module.exports = {
  name: 'ember-cli-simple-auth-tok',

  included: function(app) {
    this._super.included(app);

    this.app.import(app.bowerDirectory + '/ember-simple-auth-tok/simple-auth-tok.amd.js', {
      exports: {
        '/simple-auth-tok/authenticators/tok': ['default'],
        '/simple-auth-tok/auhorizers/tok': ['default'],
        '/simple-auth-tok/configuration': ['default']
      }
    });
  }
};
<commit_msg>Fix a typo<commit_after>module.exports = {
  name: 'ember-cli-simple-auth-tok',

  included: function(app) {
    this._super.included(app);

    this.app.import(app.bowerDirectory + '/ember-simple-auth-tok/simple-auth-tok.amd.js', {
      exports: {
        '/simple-auth-tok/authenticators/tok': ['default'],
        '/simple-auth-tok/authorizers/tok': ['default'],
        '/simple-auth-tok/configuration': ['default']
      }
    });
  }
};
<|endoftext|>


<commit_before>module.exports = function (req, res, next) {
  var returnTo = req.query.returnTo;
  if(!req.user) return redir(res, returnTo);

  req.logout();
  delete req.session;
  return redir(res, returnTo);

  function redir(res, returnTo) {
    if (returnTo)
      return res.redirect(returnTo);
    else if (next) {
      return next();
    } else {
      return res.send('bye');
    }
  }
};
  <commit_msg>remove next<commit_after>module.exports = function() {
  return function (req, res) {
    var returnTo = req.query.returnTo;
    if(!req.user) return redir(res, returnTo);

    req.logout();
    delete req.session;
    return redir(res, returnTo);

    function redir(res, returnTo) {
      if (returnTo) {
        return res.redirect(returnTo);
      } else {
        return res.send('bye');
      }
    }
  };
};
  <|endoftext|>


<commit_before>var AWS = require('aws-sdk'), ec2 = new AWS.EC2();

module.exports = function(timeout, tags, beforeHook) {
  timeout = timeout || 60 * 60 * 1000;
  beforeHook = beforeHook || function(cb) { cb(); };

  setTimeout(function() {
    beforeHook(terminate.bind(null, tags));
  }, timeout * Math.random());
};

function terminate(tags) {
  var params = {
    Filters: [
      { Name: 'instance-state-name', Values: ['running'] },
      { Name: 'tag-key', Values: tags.names },
      { Name: 'tag-value', Values: tags.values }
    ]
  };

  ec2.describeInstances(params, function(error, data) {
    if (error) return console.log(error);

    var instanceIds = data.Reservations.map(function(reservation) {
      return reservation.Instances[0].InstanceId;
    });

    ec2.terminateInstances({ InstanceIds: instanceIds}, function(err, data) {
      if (error) console.log(err);
      console.log(data);
    });
  });
}
<commit_msg>terminating a random instance that satisfy the prerequisites<commit_after>var AWS = require('aws-sdk'), ec2 = new AWS.EC2();

module.exports = function(timeout, tags, beforeHook) {
  timeout = timeout || 60 * 60 * 1000;
  beforeHook = beforeHook || function(cb) { cb(); };

  setTimeout(function() {
    beforeHook(terminate.bind(null, tags));
  }, timeout * Math.random());
};

function terminate(tags) {
  var params = {
    Filters: [
      { Name: 'instance-state-name', Values: ['running'] },
      { Name: 'tag-key', Values: tags.names },
      { Name: 'tag-value', Values: tags.values }
    ]
  };

  ec2.describeInstances(params, function(error, data) {
    if (error) return console.log(error);

    var instanceIds = data.Reservations.map(function(reservation) {
      return reservation.Instances[0].InstanceId;
    });

    var instanceId = instanceIds[Math.floor(Math.random() * instanceIds.length)];

    ec2.terminateInstances({ InstanceIds: [ instanceId ] }, function(err, data) {
      if (error) console.log(err);
      console.log(data);
    });
  });
}
<|endoftext|>


<commit_before>var restify = require('restify');
var unirest = require('unirest');
var cloudflare = require('cloudflare').createClient({ email: process.env.CLOUDFLARE_EMAIL, token: process.env.CLOUDFLARE_API_KEY });
var nodemailer = require('nodemailer');
var smtpTransport = require('nodemailer-smtp-transport');
var async = require('async');
var config = require('./config');
var transporter = nodemailer.createTransport(smtpTransport({
  host: 'smtp.mandrillapp.com',
  port: 587,
  auth: {
    user: process.env.MANDRILL_USER,
    pass: process.env.MANDRILL_PASS
  }
}));

var stats = { 'status' : 'pending', 'servers' : {} };
var started = false;
var lastSerial = 0;
var serialRevision = 1;
var currentlyChecking = false;
var checks = [];

var Status = {};

Status.setupChecks = function () {
  for (var server in config.servers) {
    var the_server = config.servers[server];
    for (var version in config.versions) {
      var the_version = config.versions[version];
      for (var section in the_version) {
        checks.push({ 'server': server, 'host': the_server.ip, 'version': version, 'section': section, 'path': the_version[section]});
      }
    }
  }
}

Status.call = function (server, uri, callback) {
  var url = 'http://' + server + uri;

  unirest.get(url).headers({ 'User-Agent': 'BukGet-Monitor' }).timeout(5000).end(function (response) {
    if (response.error) {
      return callback(false, response.error);
    }

    return callback(true);
  });
};

Status.check = function () {
  console.log('Running checks');
  currentlyChecking = true;
  var currentCheckResults = [];
  async.eachSeries(checks, function (check, callback) {
    Status.call(check.host, check.path, function (status, error) {
      currentCheckResults.push({ 'server': check.server, 'section': check.section, 'version': check.version, 'status': (error == 'ETIMEDOUT' ? 'warning' : (status ? 'ok' : 'down')) });
      callback();
    });
  }, function (err) {
    if (err) {
      console.log('Error when checking status: ');
      console.trace(err);
    } else {
      console.log('Checks successfully executed');
    }
    var totalErrors = 0;
    for (var i in currentCheckResults) {
      var checkResult = currentCheckResults[i];
      if (checkResult.status == 'down') {
        totalErrors++;
      }
      stats.servers[checkResult.server][checkResult.version][checkResult.section] = checkResult.status;
    }
    var the_status = 'ok';
    if (totalErrors > 3) {
      the_status = 'down';
    } else if (totalErrors > 0) {
      the_status = 'warning';
    }

    currentlyChecking = false;

    var doRefresh = false;

    if (stats.status !== 'down' && the_status === 'down') {
      stats.status = the_status;
      Status.sendEmail('BukGet is down!', JSON.stringify(stats));
      doRefresh = true;
    } else if (stats.status === 'down' && the_status === 'ok') {
      stats.status = the_status;
      Status.sendEmail('BukGet is back up!', JSON.stringify(stats));
      doRefresh = true;
    } else {
      stats.status = the_status;
    }

    if (!started) {
      started = true;
      if (!doRefresh) {
        console.log('Checking initial DNS consistency');
        Status.checkDnsConsistency();
      }
    }

    if (doRefresh) {
      console.log('Refreshing DNS for state: %s', stats.status);
      Status.dnsRefresh();
    }
    setTimeout(function () {
      Status.check();
    }, 1000 * 60);
  });
};

Status.sendEmail = function (title, body) {
  transporter.sendMail({
    from: 'BukGet Monitor <staff@bukget.org>',
    to: 'staff@bukget.org',
    subject: title,
    text: body
  });
};

for (var server in config.servers) {
  stats['servers'][server] = {};
  for (var version in config.versions) {
    stats['servers'][server][version] = {};
    for (var section in config.versions[version]) {
      stats['servers'][server][version][section] = 'pending';
    }
  }
}

Status.updateSerial = function (callback) {
  var now = new Date();
  var newSerial = now.getFullYear() + '' + ('0' + (now.getMonth() + 1)).slice(-2) + ('0' + now.getDate()).slice(-2);
  if (lastSerial != newSerial) {
    serialRevision = 1;
    lastSerial = newSerial;
  }
}

Status.dnsRefresh = function () {
  Status.updateSerial();
  serialRevision++;
  if (serialRevision > 99) {
    serialRevision = 1;
  }

  Status.dnsGetServers(function (callback) {
    Status.updateCloudflare(callback);
    Status.dnsRefreshServers(callback);
  });
}

Status.dnsGetServers = function (callback) {
  var servers = [];
  for (var server in stats['servers']) {
    var downCount = 0;
    for (var i in stats['servers'][server]['v3']) {
      if (stats['servers'][server]['v3'][i] == 'down') {
        downCount++;
      }
    }

    if (downCount == 0) {
      servers.push({ 'name': server, 'ns': server + '.ns.bukget.org', 'api': server + '.api.bukget.org', 'ip': config.servers[server]['ip'], 'region': config.servers[server]['region'] });
    }
  }
  callback(servers);
}

Status.dnsRefreshServers = function (servers) {
  for (var server in config.servers) {
    Status.dnsRefreshServer(server, servers);
  }
}

Status.dnsRefreshServer = function (server, servers) {
  console.log('Updating dns for %s', server);
  unirest.post('http://' + server + '.ns.bukget.org/dnsupdate')
  .headers({ 'Accept': 'application/json' })
  .send({ 'key': process.env.DNS_CHANGER, 'servers': JSON.stringify(servers), 'serial': (lastSerial + '' + ('0' + serialRevision).slice(-2)) })
  .end(function (response) {
    if (response.error || response.code == 500) {
      if (response.error) {
        console.log('Error updating DNS: ');
        console.trace(response.error);
      }
      console.log('Couldn\'t update DNS for %s', server);
    } else {
      console.log('Successfully updated DNS for %s', server);
    }
  });
}

Status.updateCloudflare = function (callback) {
  var toBeAdded = []
  for (var i in callback) {
    toBeAdded.push(callback[i]['ns']);
  }
  cloudflare.listDomainRecords('bukget.org', function (err, domains) {
    if (err) throw err;
    for (var i in domains) {
      var item = domains[i];
      if (item['type'] == 'NS') {
        var exists = false;
        var name = item['content'].split('.')[0];
        for (var server in callback) {
          if (callback[server]['name'] == name) {
            exists = true;
          }
        }
        if (!exists) {
          console.log('Delecting record for %s', item['content']);
          cloudflare.deleteDomainRecord('bukget.org', item['rec_id'], function (err, success) {
            console.log('Deleted record');
          })
        } else {
          var index = toBeAdded.indexOf(item['content']);
          if (index !== -1) {
            toBeAdded.splice(index, 1);
          }
        }
      }
    }
    for (var record in toBeAdded) {
      console.log('Adding record for %s', toBeAdded[record]);
      cloudflare.addDomainRecord('bukget.org', { 'type': 'NS', 'name': 'api', 'content': toBeAdded[record], 'ttl': 300 }, function (err, success) {
        console.log('Added record!');
      });
    }
  });
}

Status.checkDnsConsistency = function () {
  if (currentlyChecking) {
    setTimeout(function () {
      Status.checkDnsConsistency();
    }, 1000 * 20);
    return;
  }
  Status.dnsGetServers(function (callback) {
    Status.updateCloudflare(callback);
    for (var server in config.servers) {
      (function request (server) {
        return Status.needsUpdate(server, function (status, error) {
          if (error) {
            console.log('Couldn\'t get current serial for %s', server);
          }

          if (status) {
            Status.dnsRefreshServer(server, callback);
          }
        })
      })(server);
    }
  });
}

Status.needsUpdate = function (server, callback) {
  unirest.get('http://' + server + '.ns.bukget.org/serial').end(function (response) {
    if (response.error) {
      return callback(false, 'Couldn\'t get serial');
    }

    if (response.body['serial'] != (lastSerial + '' + ('0' + serialRevision).slice(-2))) {
      return callback(true);
    }

    return callback(false);
  });
}

Status.setupChecks();

Status.updateSerial();

Status.check();

setInterval(function () {
  Status.checkDnsConsistency();
}, 1000 * 60 * 30);

setInterval(function () {
  unirest.get('http://monitor.bukget.org').end(function (response) {});
}, 1000 * 60 * 20);

var app = restify.createServer();

app.use(restify.jsonp());

app.use(function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  next();
});

app.get('/', function (req, res, next) {
  res.send(stats);
});

app.get('/currentDNS', function (req, res, next) {
  Status.dnsGetServers(function (callback) {
    res.send({ 'serial': (lastSerial + '' + ('0' + serialRevision).slice(-2)), 'servers': callback })
  });
})

Status.sendEmail('BukGet monitor has started!', 'It has indeed');

app.listen(process.env.PORT || 5000);<commit_msg>Fix typo<commit_after>var restify = require('restify');
var unirest = require('unirest');
var cloudflare = require('cloudflare').createClient({ email: process.env.CLOUDFLARE_EMAIL, token: process.env.CLOUDFLARE_API_KEY });
var nodemailer = require('nodemailer');
var smtpTransport = require('nodemailer-smtp-transport');
var async = require('async');
var config = require('./config');
var transporter = nodemailer.createTransport(smtpTransport({
  host: 'smtp.mandrillapp.com',
  port: 587,
  auth: {
    user: process.env.MANDRILL_USER,
    pass: process.env.MANDRILL_PASS
  }
}));

var stats = { 'status' : 'pending', 'servers' : {} };
var started = false;
var lastSerial = 0;
var serialRevision = 1;
var currentlyChecking = false;
var checks = [];

var Status = {};

Status.setupChecks = function () {
  for (var server in config.servers) {
    var the_server = config.servers[server];
    for (var version in config.versions) {
      var the_version = config.versions[version];
      for (var section in the_version) {
        checks.push({ 'server': server, 'host': the_server.ip, 'version': version, 'section': section, 'path': the_version[section]});
      }
    }
  }
}

Status.call = function (server, uri, callback) {
  var url = 'http://' + server + uri;

  unirest.get(url).headers({ 'User-Agent': 'BukGet-Monitor' }).timeout(5000).end(function (response) {
    if (response.error) {
      return callback(false, response.error);
    }

    return callback(true);
  });
};

Status.check = function () {
  console.log('Running checks');
  currentlyChecking = true;
  var currentCheckResults = [];
  async.eachSeries(checks, function (check, callback) {
    Status.call(check.host, check.path, function (status, error) {
      currentCheckResults.push({ 'server': check.server, 'section': check.section, 'version': check.version, 'status': (error == 'ETIMEDOUT' ? 'warning' : (status ? 'ok' : 'down')) });
      callback();
    });
  }, function (err) {
    if (err) {
      console.log('Error when checking status: ');
      console.trace(err);
    } else {
      console.log('Checks successfully executed');
    }
    var totalErrors = 0;
    for (var i in currentCheckResults) {
      var checkResult = currentCheckResults[i];
      if (checkResult.status == 'down') {
        totalErrors++;
      }
      stats.servers[checkResult.server][checkResult.version][checkResult.section] = checkResult.status;
    }
    var the_status = 'ok';
    if (totalErrors > 3) {
      the_status = 'down';
    } else if (totalErrors > 0) {
      the_status = 'warning';
    }

    currentlyChecking = false;

    var doRefresh = false;

    if (stats.status !== 'down' && the_status === 'down') {
      stats.status = the_status;
      Status.sendEmail('BukGet is down!', JSON.stringify(stats));
      doRefresh = true;
    } else if (stats.status === 'down' && the_status === 'ok') {
      stats.status = the_status;
      Status.sendEmail('BukGet is back up!', JSON.stringify(stats));
      doRefresh = true;
    } else {
      stats.status = the_status;
    }

    if (!started) {
      started = true;
      if (!doRefresh) {
        console.log('Checking initial DNS consistency');
        Status.checkDnsConsistency();
      }
    }

    if (doRefresh) {
      console.log('Refreshing DNS for state: %s', stats.status);
      Status.dnsRefresh();
    }
    setTimeout(function () {
      Status.check();
    }, 1000 * 60);
  });
};

Status.sendEmail = function (title, body) {
  transporter.sendMail({
    from: 'BukGet Monitor <staff@bukget.org>',
    to: 'staff@bukget.org',
    subject: title,
    text: body
  });
};

for (var server in config.servers) {
  stats['servers'][server] = {};
  for (var version in config.versions) {
    stats['servers'][server][version] = {};
    for (var section in config.versions[version]) {
      stats['servers'][server][version][section] = 'pending';
    }
  }
}

Status.updateSerial = function (callback) {
  var now = new Date();
  var newSerial = now.getFullYear() + '' + ('0' + (now.getMonth() + 1)).slice(-2) + ('0' + now.getDate()).slice(-2);
  if (lastSerial != newSerial) {
    serialRevision = 1;
    lastSerial = newSerial;
  }
}

Status.dnsRefresh = function () {
  Status.updateSerial();
  serialRevision++;
  if (serialRevision > 99) {
    serialRevision = 1;
  }

  Status.dnsGetServers(function (callback) {
    Status.updateCloudflare(callback);
    Status.dnsRefreshServers(callback);
  });
}

Status.dnsGetServers = function (callback) {
  var servers = [];
  for (var server in stats['servers']) {
    var downCount = 0;
    for (var i in stats['servers'][server]['v3']) {
      if (stats['servers'][server]['v3'][i] == 'down') {
        downCount++;
      }
    }

    if (downCount == 0) {
      servers.push({ 'name': server, 'ns': server + '.ns.bukget.org', 'api': server + '.api.bukget.org', 'ip': config.servers[server]['ip'], 'region': config.servers[server]['region'] });
    }
  }
  callback(servers);
}

Status.dnsRefreshServers = function (servers) {
  for (var server in config.servers) {
    Status.dnsRefreshServer(server, servers);
  }
}

Status.dnsRefreshServer = function (server, servers) {
  console.log('Updating dns for %s', server);
  unirest.post('http://' + server + '.ns.bukget.org/dnsupdate')
  .headers({ 'Accept': 'application/json' })
  .send({ 'key': process.env.DNS_CHANGER, 'servers': JSON.stringify(servers), 'serial': (lastSerial + '' + ('0' + serialRevision).slice(-2)) })
  .end(function (response) {
    if (response.error || response.code == 500) {
      if (response.error) {
        console.log('Error updating DNS: ');
        console.trace(response.error);
      }
      console.log('Couldn\'t update DNS for %s', server);
    } else {
      console.log('Successfully updated DNS for %s', server);
    }
  });
}

Status.updateCloudflare = function (callback) {
  var toBeAdded = []
  for (var i in callback) {
    toBeAdded.push(callback[i]['ns']);
  }
  cloudflare.listDomainRecords('bukget.org', function (err, domains) {
    if (err) throw err;
    for (var i in domains) {
      var item = domains[i];
      if (item['type'] == 'NS') {
        var exists = false;
        var name = item['content'].split('.')[0];
        for (var server in callback) {
          if (callback[server]['name'] == name) {
            exists = true;
          }
        }
        if (!exists) {
          console.log('Deleting record for %s', item['content']);
          cloudflare.deleteDomainRecord('bukget.org', item['rec_id'], function (err, success) {
            console.log('Deleted record');
          })
        } else {
          var index = toBeAdded.indexOf(item['content']);
          if (index !== -1) {
            toBeAdded.splice(index, 1);
          }
        }
      }
    }
    for (var record in toBeAdded) {
      console.log('Adding record for %s', toBeAdded[record]);
      cloudflare.addDomainRecord('bukget.org', { 'type': 'NS', 'name': 'api', 'content': toBeAdded[record], 'ttl': 300 }, function (err, success) {
        console.log('Added record!');
      });
    }
  });
}

Status.checkDnsConsistency = function () {
  if (currentlyChecking) {
    setTimeout(function () {
      Status.checkDnsConsistency();
    }, 1000 * 20);
    return;
  }
  Status.dnsGetServers(function (callback) {
    Status.updateCloudflare(callback);
    for (var server in config.servers) {
      (function request (server) {
        return Status.needsUpdate(server, function (status, error) {
          if (error) {
            console.log('Couldn\'t get current serial for %s', server);
          }

          if (status) {
            Status.dnsRefreshServer(server, callback);
          }
        })
      })(server);
    }
  });
}

Status.needsUpdate = function (server, callback) {
  unirest.get('http://' + server + '.ns.bukget.org/serial').end(function (response) {
    if (response.error) {
      return callback(false, 'Couldn\'t get serial');
    }

    if (response.body['serial'] != (lastSerial + '' + ('0' + serialRevision).slice(-2))) {
      return callback(true);
    }

    return callback(false);
  });
}

Status.setupChecks();

Status.updateSerial();

Status.check();

setInterval(function () {
  Status.checkDnsConsistency();
}, 1000 * 60 * 30);

setInterval(function () {
  unirest.get('http://monitor.bukget.org').end(function (response) {});
}, 1000 * 60 * 20);

var app = restify.createServer();

app.use(restify.jsonp());

app.use(function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  next();
});

app.get('/', function (req, res, next) {
  res.send(stats);
});

app.get('/currentDNS', function (req, res, next) {
  Status.dnsGetServers(function (callback) {
    res.send({ 'serial': (lastSerial + '' + ('0' + serialRevision).slice(-2)), 'servers': callback })
  });
})

Status.sendEmail('BukGet monitor has started!', 'It has indeed');

app.listen(process.env.PORT || 5000);<|endoftext|>


<commit_before>var flat = module.exports = {}

var flatten = flat.flatten = function (target, opts) {
    var output = {}
      , opts = opts || {}
      , delimiter = opts.delimiter || '.'

    function getkey(key, prev) {
        return prev ? prev + delimiter + key : key
    };

    function step(object, prev) {
        Object.keys(object).forEach(function(key) {
            var isarray = opts.safe && Array.isArray(object[key])
              , type = Object.prototype.toString.call(object[key])
              , isobject = (type === "[object Object]" || type === "[object Array]")

            if (!isarray && isobject) {
                return step(object[key]
                    , getkey(key, prev)
                )
            }

            output[getkey(key, prev)] = object[key]
        });
    };

    step(target)

    return output
};

var unflatten = flat.unflatten = function (target, opts) {
    var opts = opts || {}, delimiter = opts.delimiter || '.', result = {};

    if (Object.prototype.toString.call(target) !== '[object Object]') {
        return target;
    }

    function getkey(key) {
        var parsedKey = parseInt(key);
        return (isNaN(parsedKey) ? key : parsedKey);
    }

    Object.keys(target).forEach(function(key) {
        var split = key.split(delimiter), firstNibble, secondNibble, recipient = result;

        firstNibble = getkey(split.shift());
        secondNibble = getkey(split[0]);
        while (secondNibble !== undefined) {
            if (recipient[firstNibble] === undefined) {
                recipient[firstNibble] = ((typeof secondNibble === 'number') ? [] : {});
            }

            recipient = recipient[firstNibble];
            if (split.length > 0) {
                firstNibble = getkey(split.shift());
                secondNibble = getkey(split[0]);
            }
        }

        //unflatten again for 'messy objects' //@see test
        recipient[firstNibble] = unflatten(target[key]);
    });
    return result;
};<commit_msg>style consistency<commit_after>var flat = module.exports = {}

var flatten = flat.flatten = function (target, opts) {
    var output = {}
      , opts = opts || {}
      , delimiter = opts.delimiter || '.'

    function getkey(key, prev) {
        return prev ? prev + delimiter + key : key
    };

    function step(object, prev) {
        Object.keys(object).forEach(function(key) {
            var isarray = opts.safe && Array.isArray(object[key])
              , type = Object.prototype.toString.call(object[key])
              , isobject = (type === "[object Object]" || type === "[object Array]")

            if (!isarray && isobject) {
                return step(object[key]
                    , getkey(key, prev)
                )
            }

            output[getkey(key, prev)] = object[key]
        });
    };

    step(target)

    return output
};

var unflatten = flat.unflatten = function (target, opts) {
    var opts = opts || {}
      , delimiter = opts.delimiter || '.'
      , result = {}

    if (Object.prototype.toString.call(target) !== '[object Object]') {
        return target
    }

    function getkey(key) {
        var parsedKey = parseInt(key)
        return (isNaN(parsedKey) ? key : parsedKey)
    };

    Object.keys(target).forEach(function(key) {
        var split = key.split(delimiter)
          , firstNibble
          , secondNibble
          , recipient = result

        firstNibble = getkey(split.shift())
        secondNibble = getkey(split[0])

        while (secondNibble !== undefined) {
            if (recipient[firstNibble] === undefined) {
                recipient[firstNibble] = ((typeof secondNibble === 'number') ? [] : {})
            }

            recipient = recipient[firstNibble]
            if (split.length > 0) {
                firstNibble = getkey(split.shift())
                secondNibble = getkey(split[0])
            }
        }

        // unflatten again for 'messy objects'
        recipient[firstNibble] = unflatten(target[key])
    });

    return result
};
<|endoftext|>


<commit_before>module.exports = require('./lib');
<commit_msg>Fix wrong path<commit_after>module.exports = require('./lib/crlfHelper');
<|endoftext|>


<commit_before>require('dotenv').config();

process.on('unhandledRejection', (error) => {
	console.error(error);
});

const {RtmClient, WebClient, CLIENT_EVENTS} = require('@slack/client');

const plugins = [
	/*
	require('./mahjong'),
	require('./pocky'),
	require('./esolang-rankmaker'),
	require('./emoji-notifier'),
	require('./sushi-bot'),
	*/
	require('./imagenet'),
];

const rtmClient = new RtmClient(process.env.SLACK_TOKEN);
const webClient = new WebClient(process.env.SLACK_TOKEN);

for (const plugin of plugins) {
	plugin({rtmClient, webClient});
}

rtmClient.on(CLIENT_EVENTS.RTM.AUTHENTICATED, (data) => {
	console.log(`Logged in as ${data.self.name} of team ${data.team.name}`);
});

rtmClient.start();
<commit_msg>Uncomment out codes<commit_after>require('dotenv').config();

process.on('unhandledRejection', (error) => {
	console.error(error);
});

const {RtmClient, WebClient, CLIENT_EVENTS} = require('@slack/client');

const plugins = [
	require('./mahjong'),
	require('./pocky'),
	require('./esolang-rankmaker'),
	require('./emoji-notifier'),
	require('./sushi-bot'),
	require('./imagenet'),
];

const rtmClient = new RtmClient(process.env.SLACK_TOKEN);
const webClient = new WebClient(process.env.SLACK_TOKEN);

for (const plugin of plugins) {
	plugin({rtmClient, webClient});
}

rtmClient.on(CLIENT_EVENTS.RTM.AUTHENTICATED, (data) => {
	console.log(`Logged in as ${data.self.name} of team ${data.team.name}`);
});

rtmClient.start();
<|endoftext|>


<commit_before>exports.core = {
    Product : require('./src/core/product'),
};<commit_msg>change index<commit_after>exports.core = {
    Product : require('./src/core/product'),
    Buyer : require('./src/core/buyer')
};<|endoftext|>


<commit_before>var request = require('request')
var xpath = require('xpath')
var dom = require('xmldom').DOMParser
var unescape = require('unescape')

module.exports = function (username, skipPinnedTweets = false, cb) {

  var url = 'https://twitter.com/' + username

  // oh yeah //extreme fragility//
  if (process.browser) {
    url = 'http://cors.io/?' + url
  }

  request(url, function (err, res, body) {
    if (err) {
      cb(err)
    } else {
      var res = []

      var doc = new dom({errorHandler: function() {}}).parseFromString(body)

      if(skipPinnedTweets){
          var tweets = xpath.select('//li[contains(@class, \'js-stream-item\') and not(contains(@class,\'js-pinned\'))]', doc)
      } else {
          var tweets = xpath.select('//li[contains(@class, \'js-stream-item\')]', doc)
      }

      tweets.forEach(function (n) {
        var tweet = xpath.select('./div[contains(@class, \'tweet\')]/div[contains(@class, \'content\')]', n)[0]
        if (!tweet) {
          // bad tweet?
          return
        }

        var header = xpath.select('./div[contains(@class, \'stream-item-header\')]', tweet)[0]
        var body = xpath.select('*/p[contains(@class, \'tweet-text\')]/text()', tweet)[0]
        var fullname = xpath.select('.//strong[contains(@class, "fullname")]/text()', header)[0]
        if (body) body = nodeToText(body)
        var imageContainer = xpath.select('.//div[contains(@class, \'js-adaptive-photo\')]/@data-image-url', tweet)[0]
        var img = imageContainer?imageContainer.value:null;

        let mentions = (body.match(/\s([@][\w_-]+)/gi)||[]).map( str => str.trim() )
        let hashtags = (body.match(/\s([#][\w_-]+)/gi)||[]).map( str => str.trim() )
        let links = (body.match(/(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9]\.[^\s]{2,})/g)||[]).map( str => str.trim() )

        var item = {
          username: '@' + xpath.select('./a/span[contains(@class, \'username\')]/b/text()', header)[0].data,
          body: body,
          fullname: fullname ? fullname.data : '',
          avatar: xpath.select('./a/img[contains(@class, "avatar")]/@src', header)[0].value,
          url: 'https://twitter.com' + xpath.select('./small[contains(@class, "time")]/a[contains(@class, "tweet-timestamp")]/@href', header)[0].value,
          image: img,
          timestamp: xpath.select('./small[contains(@class, "time")]/a[contains(@class, "tweet-timestamp")]/span/@data-time', header)[0].value,
          mentions: mentions,
          hashtags: hashtags,
          links: links
        }

        var date = new Date(1970, 0, 1)
        date.setSeconds(item.timestamp)
        item.timestamp = date.toISOString()

        res.push({
          username: item.username,
          fullname: item.fullname,
          retweet: item.username.toLowerCase() !== '@'+username.toLowerCase(),
          url: item.url,
          image: item.image,
          content: item.body,
          date: date,
          mentions: item.mentions,
          hashtags: item.hashtags,
          links: item.links
        })
      })

      cb(null, res)
    }
  })
}

function unescapeHarder (txt) {
  return unescape(txt)
    .replace(' ', ' ')
    .replace('…', '')
    .replace('\\n', ' ')
    .replace('http', ' http')
}

function nodeToText (node) {
  if (!node) {
    return ''
  }
  return unescapeHarder(node.nodeValue || '')
    + nodeToText(node.firstChild)
    + nodeToText(node.nextSibling)
}
<commit_msg>bugfix<commit_after>var request = require('request')
var xpath = require('xpath')
var dom = require('xmldom').DOMParser
var unescape = require('unescape')

module.exports = function (username, skipPinnedTweets, cb) {

  var url = 'https://twitter.com/' + username

  // oh yeah //extreme fragility//
  if (process.browser) {
    url = 'http://cors.io/?' + url
  }

  request(url, function (err, res, body) {
    if (err) {
      cb(err)
    } else {
      var res = []

      var doc = new dom({errorHandler: function() {}}).parseFromString(body)

      if(skipPinnedTweets){
          var tweets = xpath.select('//li[contains(@class, \'js-stream-item\') and not(contains(@class,\'js-pinned\'))]', doc)
      } else {
          var tweets = xpath.select('//li[contains(@class, \'js-stream-item\')]', doc)
      }

      tweets.forEach(function (n) {
        var tweet = xpath.select('./div[contains(@class, \'tweet\')]/div[contains(@class, \'content\')]', n)[0]
        if (!tweet) {
          // bad tweet?
          return
        }

        var header = xpath.select('./div[contains(@class, \'stream-item-header\')]', tweet)[0]
        var body = xpath.select('*/p[contains(@class, \'tweet-text\')]/text()', tweet)[0]
        var fullname = xpath.select('.//strong[contains(@class, "fullname")]/text()', header)[0]
        if (body) body = nodeToText(body)
        var imageContainer = xpath.select('.//div[contains(@class, \'js-adaptive-photo\')]/@data-image-url', tweet)[0]
        var img = imageContainer?imageContainer.value:null;

        let mentions = (body.match(/\s([@][\w_-]+)/gi)||[]).map( str => str.trim() )
        let hashtags = (body.match(/\s([#][\w_-]+)/gi)||[]).map( str => str.trim() )
        let links = (body.match(/(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9]\.[^\s]{2,})/g)||[]).map( str => str.trim() )

        var item = {
          username: '@' + xpath.select('./a/span[contains(@class, \'username\')]/b/text()', header)[0].data,
          body: body,
          fullname: fullname ? fullname.data : '',
          avatar: xpath.select('./a/img[contains(@class, "avatar")]/@src', header)[0].value,
          url: 'https://twitter.com' + xpath.select('./small[contains(@class, "time")]/a[contains(@class, "tweet-timestamp")]/@href', header)[0].value,
          image: img,
          timestamp: xpath.select('./small[contains(@class, "time")]/a[contains(@class, "tweet-timestamp")]/span/@data-time', header)[0].value,
          mentions: mentions,
          hashtags: hashtags,
          links: links
        }

        var date = new Date(1970, 0, 1)
        date.setSeconds(item.timestamp)
        item.timestamp = date.toISOString()

        res.push({
          username: item.username,
          fullname: item.fullname,
          retweet: item.username.toLowerCase() !== '@'+username.toLowerCase(),
          url: item.url,
          image: item.image,
          content: item.body,
          date: date,
          mentions: item.mentions,
          hashtags: item.hashtags,
          links: item.links
        })
      })

      cb(null, res)
    }
  })
}

function unescapeHarder (txt) {
  return unescape(txt)
    .replace(' ', ' ')
    .replace('…', '')
    .replace('\\n', ' ')
    .replace('http', ' http')
}

function nodeToText (node) {
  if (!node) {
    return ''
  }
  return unescapeHarder(node.nodeValue || '')
    + nodeToText(node.firstChild)
    + nodeToText(node.nextSibling)
}
<|endoftext|>


<commit_before>var express = require('express');
var math = require('mathjs');
var bodyParser = require('body-parser');
var app = express();

app.set('port', (process.env.PORT || 8080));

app.use(bodyParser.urlencoded({ extended: true }));

app.listen(app.get('port'), function () {
  console.log('app starting at port '+ app.get('port'));
});

var mathParser = new math.parser();

app.get('/eval', function(req, resp) {
	resp.send('/eval only currently accept POST requests.');
});

app.post('/eval', function(req, resp) {
  var result = {};
  var post = req.body;
  var expr = post.text;
  var trigger = post.trigger_word;

  // do not respond to bot-users
  if(post.user_name == 'slackbot'){
  	resp.end();
  	return;
  }

  if (!expr) {
  	result.ok = false;
  	result.text = 'No message sent.';
    resp.json(result);
    return;
  }

  if (trigger) {
  	expr = expr.slice(trigger.length);
  }

  result.text = '';

  try {
    result.ok = true;
    var answer = mathParser.eval(expr);
    result.attachments = [{
    	color: 'good',
    	text: '@' + post.user_name + ' ans = *' + answer + '*',
    	mrkdwn_in: ['text']
    }];
    mathParser.scope.ans = answer;
  } catch (err) {
    result.ok = false;
    result.attachments = [{
    	color: 'danger',
    	text: '@' + post.user_name + ' ' + err.toString(),
    	mrkdwn_in: ['text']
    }];
    result.error = {
      type: err.name,
      message: err.message
    };
  }

  resp.json(result);

});
<commit_msg>Revert "expri without response text"<commit_after>var express = require('express');
var math = require('mathjs');
var bodyParser = require('body-parser');
var app = express();

app.set('port', (process.env.PORT || 8080));

app.use(bodyParser.urlencoded({ extended: true }));

app.listen(app.get('port'), function () {
  console.log('app starting at port '+ app.get('port'));
});

var mathParser = new math.parser();

app.get('/eval', function(req, resp) {
	resp.send('/eval only currently accept POST requests.');
});

app.post('/eval', function(req, resp) {
  var result = {};
  var post = req.body;
  var expr = post.text;
  var trigger = post.trigger_word;

  // do not respond to bot-users
  if(post.user_name == 'slackbot'){
  	resp.end();
  	return;
  }

  if (!expr) {
  	result.ok = false;
  	result.text = 'No message sent.';
    resp.json(result);
    return;
  }

  if (trigger) {
  	expr = expr.slice(trigger.length);
  }

  result.text = '  ';

  try {
    result.ok = true;
    var answer = mathParser.eval(expr);
    result.attachments = [{
    	color: 'good',
    	text: '@' + post.user_name + ' ans = *' + answer + '*',
    	mrkdwn_in: ['text']
    }];
    mathParser.scope.ans = answer;
  } catch (err) {
    result.ok = false;
    result.attachments = [{
    	color: 'danger',
    	text: '@' + post.user_name + ' ' + err.toString(),
    	mrkdwn_in: ['text']
    }];
    result.error = {
      type: err.name,
      message: err.message
    };
  }

  resp.json(result);

});
<|endoftext|>


<commit_before>var app = require('app');
var BrowserWindow = require('browser-window');

app.on('ready', function() {

  var mainWindow = new BrowserWindow({
    width: 1000,
    height: 600
  })

});
<commit_msg>load html file<commit_after>var app = require('app');
var BrowserWindow = require('browser-window');

app.on('ready', function() {

  var win = new BrowserWindow({
    width: 1000,
    height: 600
  });

  win.loadUrl('file://'+__dirname+'/views/index.html')

});
<|endoftext|>


<commit_before>console.log("Started");

var express = require('express');
var bodyParser = require('body-parser')
var app = express();
app.use(bodyParser.json());

var sqlite3	= require('sqlite3').verbose();
var dbName = './test.db';
var db = new sqlite3.Database(dbName);

app.get('/', function (req, res) {
  res.send('Hello World!');
});

//Returns all users except for the user given by the request
app.get('/users', function(req, res) {
	console(req.body);
	db.all("SELECT id FROM users WHERE id != " + req.body.id, function(err, rows) {
		console.log(rows);
		var json = JSON.stringify(rows);
		console.log(json);

		res.type('text/plain');
  		res.send(json);
	});
});

//Adds user if user doesn't exist. Updates user if user exists
app.post('/user', function(req, res){
	console.log(req.body);

	var stmt = db.prepare("INSERT OR REPLACE INTO users (id,name,x,y) VALUES (?, ?, ?, ?)");
	stmt.run(req.body.id, req.body.name, req.body.x, req.body.y);
	stmt.finalize();

	//console.log("Added User");

	// db.each("SELECT id, name, x, y FROM users", function(err, row) {
	//   console.log(row.id + ": " + row.name + " loc: " + row.x + ", " + row.y);
	// });

	res.send(req.body);
});

app.post('/test', function (req, res) {
	console.log(req.body);

	res.send(req.body);
});

var server = app.listen(80, function () {
  var host = server.address().address;
  var port = server.address().port;
  console.log('Example app listening at http://%s:%s', host, port);
});<commit_msg>Removing debugging<commit_after>console.log("Started");

var express = require('express');
var bodyParser = require('body-parser')
var app = express();
app.use(bodyParser.json());

var sqlite3	= require('sqlite3').verbose();
var dbName = './test.db';
var db = new sqlite3.Database(dbName);

app.get('/', function (req, res) {
  res.send('Hello World!');
});

//Returns all users except for the user given by the request
app.get('/users', function(req, res) {
	console(req.body);
	db.all("SELECT id FROM users WHERE id != " + req.body.id, function(err, rows) {
		console.log(rows);
		var json = JSON.stringify(rows);
		console.log(json);

		res.type('text/plain');
  		res.send(json);
	});
});

//Adds user if user doesn't exist. Updates user if user exists
app.post('/user', function(req, res){
	var stmt = db.prepare("INSERT OR REPLACE INTO users (id,name,x,y) VALUES (?, ?, ?, ?)");
	stmt.run(req.body.id, req.body.name, req.body.x, req.body.y);
	stmt.finalize();

	//console.log("Added User");

	// db.each("SELECT id, name, x, y FROM users", function(err, row) {
	//   console.log(row.id + ": " + row.name + " loc: " + row.x + ", " + row.y);
	// });

	res.send(req.body);
});

app.post('/test', function (req, res) {
	console.log(req.body);

	res.send(req.body);
});

var server = app.listen(80, function () {
  var host = server.address().address;
  var port = server.address().port;
  console.log('Example app listening at http://%s:%s', host, port);
});<|endoftext|>


<commit_before>(function () {
    'use strict';

    // The initialize function must be run each time a new page is loaded
    Office.initialize = function (reason) {
        $(document).ready(function () {
            app.initialize();

            sendRequest();
        });
    };

    function getSubjectRequest(id) {
        // Return a GetItem operation request for the subject of the specified item.
        var result =
     '<?xml version="1.0" encoding="utf-8"?>' +
     '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"' +
     '               xmlns:xsd="http://www.w3.org/2001/XMLSchema"' +
     '               xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"' +
     '               xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">' +
     '  <soap:Header>' +
     '    <RequestServerVersion Version="Exchange2013" xmlns="http://schemas.microsoft.com/exchange/services/2006/types" soap:mustUnderstand="0" />' +
     '  </soap:Header>' +
     '  <soap:Body>' +
     '    <GetItem xmlns="http://schemas.microsoft.com/exchange/services/2006/messages">' +
     '      <ItemShape>' +
     '        <t:BaseShape>IdOnly</t:BaseShape>' +
     '        <t:AdditionalProperties>' +
     '            <t:FieldURI FieldURI="item:Subject"/>' +
     '        </t:AdditionalProperties>' +
     '      </ItemShape>' +
     '      <ItemIds><t:ItemId Id="' + id + '"/></ItemIds>' +
     '    </GetItem>' +
     '  </soap:Body>' +
     '</soap:Envelope>';

        return result;
    }

    function sendRequest() {
        var mailbox = Office.context.mailbox;
        mailbox.makeEwsRequestAsync(getSubjectRequest(mailbox.item.itemId), callback);
    }

    function callback(asyncResult) {
        var result = asyncResult.value;
        var context = asyncResult.context;

        console.log(result);
        console.log(context);
    }

})();
<commit_msg>blah2<commit_after>(function () {
    'use strict';

    // The initialize function must be run each time a new page is loaded
    Office.initialize = function (reason) {
        $(document).ready(function () {
            app.initialize();

            sendRequest();
        });
    };

    function getSubjectRequest(id) {
        // Return a GetItem operation request for the subject of the specified item.
        var result =
     '<?xml version="1.0" encoding="utf-8"?>' +
     '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"' +
     '               xmlns:xsd="http://www.w3.org/2001/XMLSchema"' +
     '               xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"' +
     '               xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">' +
     '  <soap:Header>' +
     '    <RequestServerVersion Version="Exchange2013" xmlns="http://schemas.microsoft.com/exchange/services/2006/types" soap:mustUnderstand="0" />' +
     '  </soap:Header>' +
     '  <soap:Body>' +
     '    <GetItem xmlns="http://schemas.microsoft.com/exchange/services/2006/messages">' +
     '      <ItemShape>' +
     '        <t:BaseShape>IdOnly</t:BaseShape>' +
     '        <t:AdditionalProperties>' +
     '            <t:FieldURI FieldURI="item:Body"/>' +
     '        </t:AdditionalProperties>' +
     '      </ItemShape>' +
     '      <ItemIds><t:ItemId Id="' + id + '"/></ItemIds>' +
     '    </GetItem>' +
     '  </soap:Body>' +
     '</soap:Envelope>';

        return result;
    }

    function sendRequest() {
        var mailbox = Office.context.mailbox;
        mailbox.makeEwsRequestAsync(getSubjectRequest(mailbox.item.itemId), callback);
    }

    function callback(asyncResult) {
        var result = asyncResult.value;
        var context = asyncResult.context;

        console.log(result);
        console.log(context);
    }

})();
<|endoftext|>


<commit_before>var path = require('path');
var accord = require('accord');
var gutil = require('gulp-util');
var through2 = require('through2');
var css = require('css');

var PluginError = gutil.PluginError;
var less = accord.load('less');

module.exports = function (options) {

    return through2.obj(function (file, enc, callback) {

        if (file.isNull()) {
            return callback(null, file);
        }

        if (file.isStream()) {
            return callback(new PluginError('gulp-less-branding-js', 'Streaming not supported.'));
        }

        var variableRegex = /(@[A-Za-z0-9\-_]+)(?=:)/g;
        var contentsStr = file.contents.toString();
        var variables = contentsStr.match(variableRegex).map(function (obj) {
            return obj.slice(1);
        });

        variables.forEach(function (variable) {
            // TODO: class these with 'gulp-less-branding-' or something to stop it from colliding with existing things
            var clazz = ['.', variable, ' { color: @', variable, '; }\r\n'].join('');
            contentsStr = contentsStr.concat(clazz);
        });

        console.log(contentsStr);

        var opts = {filename: file.path, compress: false};
        less.render(contentsStr, opts).then(function (res) {

            var compiledCss = res.result;
            var ast = css.parse(compiledCss);

            // TODO: pull out all of the rules with selectors that match the variable names

            var rules = ast.stylesheet.rules.filter(function (rule) {
                // This line is ballsy and stupid
                // but for the sake of proving this out I'm leaving it for now and will fix later
                // TODO: Fix this
                var name = rule.selectors[0].slice(1);

                return rule.type === 'rule' && variables.indexOf(name) > -1;
            });

            // TODO: now pull out the color declaration and save it

            rules.forEach(function (rule) {
                var colorDecs = rule.declarations.filter(function (declaration) {
                    return declaration.property === 'color';
                });

                if (colorDecs && colorDecs.length > 0) {
                    var color = colorDecs[0].value;

                }
            });

            //file.contents = new Buffer(res.result);
            file.contents = new Buffer('TODO PUT THE STUFF BACK!')

            return file;
        }).then(function (file) {
            callback(null, file);
        }).catch(function (err) {
            console.log(err);
            throw new PluginError('gulp-less-branding-js', err);
        }).done(undefined, callback);
    });

}<commit_msg>Added output filename option and pulled out color resource.<commit_after>var path = require('path');
var accord = require('accord');
var gutil = require('gulp-util');
var through2 = require('through2');
var css = require('css');

var PluginError = gutil.PluginError;
var less = accord.load('less');

module.exports = function (options) {

    return through2.obj(function (file, enc, callback) {

        if (file.isNull()) {
            return callback(null, file);
        }

        if (file.isStream()) {
            return callback(new PluginError('gulp-less-branding-js', 'Streaming not supported.'));
        }

        var variableRegex = /(@[A-Za-z0-9\-_]+)(?=:)/g;
        var contentsStr = file.contents.toString();
        var variables = contentsStr.match(variableRegex).map(function (obj) {
            return obj.slice(1);
        });

        variables.forEach(function (variable) {
            // TODO: class these with 'gulp-less-branding-' or something to stop it from colliding with existing things
            var clazz = ['.', variable, ' { color: @', variable, '; }\r\n'].join('');
            contentsStr = contentsStr.concat(clazz);
        });

        var opts = {filename: file.path, compress: false};
        less.render(contentsStr, opts).then(function (res) {

            var ast = css.parse(res.result);

            var colorKvps = ast.stylesheet.rules
                .filter(function (rule) {
                    // This line is ballsy and stupid
                    // but for the sake of proving this out I'm leaving it for now and will fix later
                    // TODO: Fix this
                    var name = rule.selectors[0].slice(1);

                    return rule.type === 'rule' && variables.indexOf(name) > -1;
                })
                .map(function (rule) {
                    var colorDecs = rule.declarations.filter(function (declaration) {
                        return declaration.property === 'color';
                    });

                    if (colorDecs && colorDecs.length > 0) {
                        var color = colorDecs[0].value;

                        return {
                            // TODO: And here it is again!
                            key: rule.selectors[0].slice(1),
                            value: color
                        }
                    }
                });

            var colorResource = {};

            colorKvps.forEach(function (kvp) {
                colorResource[kvp.key] = kvp.value;
            });

            console.log(JSON.stringify(colorResource));

            file.contents = new Buffer('TODO PUT THE STUFF BACK!')

            return file;
        }).then(function (file) {
            callback(null, file);
        }).catch(function (err) {
            console.log(err);
            throw new PluginError('gulp-less-branding-js', err);
        }).done(undefined, callback);
    });

}<|endoftext|>


<commit_before>var fs = require("fs");
var tmp = require("tmp");
var path = require("path");
var compile = require("node-elm-compiler").compile;
var jsEmitterFilename = "emitter.js";
var cp = require("node-cp");
var replaceStream = require("replacestream");

var templatesDir = path.join(__dirname, "templates", "emitter");
var elmPackageFilename = "elm-package.json";
var elmPackageSrc = path.join(templatesDir, elmPackageFilename);
var emitterFilename = "Emitter.elm"
var emitterSrc = path.join(templatesDir, emitterFilename);

// elmModuleName is optional, and is by default inferred based on the filename.
module.exports = function(srcElmFile, destCssFile, elmModuleName) {
  return new Promise(function(resolve, reject) {
    var originalWorkingDir = process.cwd();

    tmp.dir(function (err, tmpDirPath) {
      if (err) {
        return reject(err);
      }

      if (!elmModuleName) {
        elmModuleName = path.basename(srcElmFile, ".elm");
      }

      process.chdir(tmpDirPath);

      return generateCssFile(
        tmpDirPath, srcElmFile, elmModuleName, destCssFile
      ).then(function(result) {
        process.chdir(originalWorkingDir);
        resolve(result);
      }, function(err) {
        process.chdir(originalWorkingDir);
        reject(result);
      });
    });
  });
}

function generateCssFile(tmpDirPath, srcElmFile, elmModuleName, destCssFile) {
  return new Promise(function(resolve, reject) {
    var elmPackageDest = path.join(tmpDirPath, elmPackageFilename);
    var emitterDest = path.join(tmpDirPath, emitterFilename);
    var jsEmitterDest = path.join(tmpDirPath, jsEmitterFilename);

    return Promise.all([
      prepareElmPackageJson(elmPackageSrc, elmPackageDest, srcElmFile),
      prepareEmitter(emitterSrc, emitterDest, elmModuleName)
    ]).then(function(){
      return emit(emitterDest, jsEmitterDest).then(function(content) {
        fs.writeFile(destCssFile, content + "\n", function(err, file) {
          return err ? reject(err) : resolve(file);
        });
      }, reject);
    }, reject);
  });
}

function prepareElmPackageJson(src, dest, srcElmFile) {
  return new Promise(function(resolve, reject) {
    // Substitute the target source dir into our temporary elm-package.json
    fs.createReadStream(src)
      .pipe(replaceStream(
          "$nameOfTargetSourceDirectoryGoesHere",

          // BEGIN HACKY WORKAROUND
          //
          // once elm-css has been published,
          // templates/emitter/elm-package.json can include this
          // as a depdencency: "rtfeldman/elm-css": "1.0.0 <= v < 2.0.0"
          // - but until then, we hack it into the sources list like so:
          path.join(__dirname, "src\",\n        \"") +
          // ...but once it's been published and we can add that dependency
          // to elm-package.json, we can chop out this workaround.
          //
          // END HACKY WORKAROUND

          path.dirname(srcElmFile),
          { limit: 1 }
        )
      )
      .pipe(fs.createWriteStream(dest))
      .on("close", resolve)
      .on("error", reject);
  });
}

function prepareEmitter(src, dest, elmModuleName) {
  return new Promise(function(resolve, reject) {
    // Substitute the target module name into our temporary Emitter.elm
    fs.createReadStream(src)
      .pipe(replaceStream("NameOfSourceModuleGoesHere", elmModuleName, {limit: 1}))
      .pipe(fs.createWriteStream(dest))
      .on("close", resolve)
      .on("error", reject);
  });
}

function emit(src, dest) {
  return new Promise(function(resolve, reject) {
    // Compile the temporary file.
    compileEmitter(src, {output: dest, yes: true}).then(function() {
      // Make the compiled emitter.js Node-friendly.
      fs.appendFile(dest, "\nmodule.exports = Elm;", function(err) {
        if (err) {
          return reject(err);
        }

        var Elm = require(dest);
        var result = Elm.worker(Elm.Emitter).ports.cssOutput;

        return result.success
          ? resolve(result.content)
          : reject("Compilation error: " + result.content);
      });
    }, reject);
  });
}

function compileEmitter(src, options) {
  return new Promise(function(resolve, reject) {
    compile(src, options)
      .on("close", function(exitCode) {
        if (exitCode === 0) {
          resolve();
        } else {
          reject("Errored with exit code " + exitCode);
        }
      });
  });
}
<commit_msg>Remove obsolete cp require<commit_after>var fs = require("fs");
var tmp = require("tmp");
var path = require("path");
var compile = require("node-elm-compiler").compile;
var jsEmitterFilename = "emitter.js";
var replaceStream = require("replacestream");

var templatesDir = path.join(__dirname, "templates", "emitter");
var elmPackageFilename = "elm-package.json";
var elmPackageSrc = path.join(templatesDir, elmPackageFilename);
var emitterFilename = "Emitter.elm"
var emitterSrc = path.join(templatesDir, emitterFilename);

// elmModuleName is optional, and is by default inferred based on the filename.
module.exports = function(srcElmFile, destCssFile, elmModuleName) {
  return new Promise(function(resolve, reject) {
    var originalWorkingDir = process.cwd();

    tmp.dir(function (err, tmpDirPath) {
      if (err) {
        return reject(err);
      }

      if (!elmModuleName) {
        elmModuleName = path.basename(srcElmFile, ".elm");
      }

      process.chdir(tmpDirPath);

      return generateCssFile(
        tmpDirPath, srcElmFile, elmModuleName, destCssFile
      ).then(function(result) {
        process.chdir(originalWorkingDir);
        resolve(result);
      }, function(err) {
        process.chdir(originalWorkingDir);
        reject(result);
      });
    });
  });
}

function generateCssFile(tmpDirPath, srcElmFile, elmModuleName, destCssFile) {
  return new Promise(function(resolve, reject) {
    var elmPackageDest = path.join(tmpDirPath, elmPackageFilename);
    var emitterDest = path.join(tmpDirPath, emitterFilename);
    var jsEmitterDest = path.join(tmpDirPath, jsEmitterFilename);

    return Promise.all([
      prepareElmPackageJson(elmPackageSrc, elmPackageDest, srcElmFile),
      prepareEmitter(emitterSrc, emitterDest, elmModuleName)
    ]).then(function(){
      return emit(emitterDest, jsEmitterDest).then(function(content) {
        fs.writeFile(destCssFile, content + "\n", function(err, file) {
          return err ? reject(err) : resolve(file);
        });
      }, reject);
    }, reject);
  });
}

function prepareElmPackageJson(src, dest, srcElmFile) {
  return new Promise(function(resolve, reject) {
    // Substitute the target source dir into our temporary elm-package.json
    fs.createReadStream(src)
      .pipe(replaceStream(
          "$nameOfTargetSourceDirectoryGoesHere",

          // BEGIN HACKY WORKAROUND
          //
          // once elm-css has been published,
          // templates/emitter/elm-package.json can include this
          // as a depdencency: "rtfeldman/elm-css": "1.0.0 <= v < 2.0.0"
          // - but until then, we hack it into the sources list like so:
          path.join(__dirname, "src\",\n        \"") +
          // ...but once it's been published and we can add that dependency
          // to elm-package.json, we can chop out this workaround.
          //
          // END HACKY WORKAROUND

          path.dirname(srcElmFile),
          { limit: 1 }
        )
      )
      .pipe(fs.createWriteStream(dest))
      .on("close", resolve)
      .on("error", reject);
  });
}

function prepareEmitter(src, dest, elmModuleName) {
  return new Promise(function(resolve, reject) {
    // Substitute the target module name into our temporary Emitter.elm
    fs.createReadStream(src)
      .pipe(replaceStream("NameOfSourceModuleGoesHere", elmModuleName, {limit: 1}))
      .pipe(fs.createWriteStream(dest))
      .on("close", resolve)
      .on("error", reject);
  });
}

function emit(src, dest) {
  return new Promise(function(resolve, reject) {
    // Compile the temporary file.
    compileEmitter(src, {output: dest, yes: true}).then(function() {
      // Make the compiled emitter.js Node-friendly.
      fs.appendFile(dest, "\nmodule.exports = Elm;", function(err) {
        if (err) {
          return reject(err);
        }

        var Elm = require(dest);
        var result = Elm.worker(Elm.Emitter).ports.cssOutput;

        return result.success
          ? resolve(result.content)
          : reject("Compilation error: " + result.content);
      });
    }, reject);
  });
}

function compileEmitter(src, options) {
  return new Promise(function(resolve, reject) {
    compile(src, options)
      .on("close", function(exitCode) {
        if (exitCode === 0) {
          resolve();
        } else {
          reject("Errored with exit code " + exitCode);
        }
      });
  });
}
<|endoftext|>


<commit_before>var http = require('http'),
	qs = require('querystring');

function Request(options, body) {
	options = options || {};

	options.host = options.host || options.hostname || 'localhost';
	options.path = options.path || '/';
	options.port = options.port || 80;
	options.timeout = options.timeout || 15000;
	options.method = options.method.toUpperCase() || 'GET';

	return new Promise(function(resolve, reject) {
		request(resolve, reject, options, body);
	});
}

function request(resolve, reject, options, body) {
	var data = null;

	options.headers = options.headers || {};
	options.expect && (options.headers['Expect'] = '100-Continue');
	options.query && (options.path += '?' + qs.stringify(options.query));

	if (body) {
		if (typeof body == 'object') {
			try {
				data = JSON.stringify(body);
				data = Buffer(data, null, 2);

				options.headers['Content-Type'] = 'application/json';
				(!options.headers['Accept']) && (options.headers['Accept'] = 'application/json,text/plain');
			} catch(e) {
				console.error(e);
				return ;
			}
		} else {
			data = Buffer(data + '');
			options.headers['Content-Type'] = 'text/plain';
		}

		options.headers['Content-Length'] = data.length;
	}

	var req = http.request(options);

	if (options.timeout && options.timeout > 0) {
		req.on('socket', function(socket) {
			socket.setTimeout(options.timeout);
			socket.on('timeout', function() {
				req.abort();
				reject('Error: timeout');
			});
		});
	}

	req.on('error', function(err) {
		reject(err);
	});

	req.on('abort', function() {
		reject('Error: The request was aborted!');
	});

	req.on('response', function(res) {
		res.setEncoding('utf8');

		res.data = '';
		res.on('data', function(d) {
			res.data += d.toString('utf8');
		});

		res.on('end', function() {
			try {
				res.body = JSON.parse(res.data);
			} catch(e) {
				console.error(e);
				return ;
			};
			resolve(res.data);
		});
	});

	if (data) {
		options.expect && req.on('continue', function() {
			req.write(data);
			req.end();
		});

		(!options.expect) && (function() {
			req.write(data);
			req.end();
		})();
	} else {
		req.end();
	}
};

module.exports = Request;<commit_msg>fix the `options.method.toUpperCase()` error when options.method is not set<commit_after>var http = require('http'),
	qs = require('querystring');

function Request(options, body) {
	options = options || {};

	options.host = options.host || options.hostname || 'localhost';
	options.path = options.path || '/';
	options.port = options.port || 80;
	options.timeout = options.timeout || 15000;
	options.method = options.method ? options.method.toUpperCase() : 'GET';

	return new Promise(function(resolve, reject) {
		request(resolve, reject, options, body);
	});
}

function request(resolve, reject, options, body) {
	var data = null;

	options.headers = options.headers || {};
	options.expect && (options.headers['Expect'] = '100-Continue');
	options.query && (options.path += '?' + qs.stringify(options.query));

	if (body) {
		if (typeof body == 'object') {
			try {
				data = JSON.stringify(body);
				data = Buffer(data, null, 2);

				options.headers['Content-Type'] = 'application/json';
				(!options.headers['Accept']) && (options.headers['Accept'] = 'application/json,text/plain');
			} catch(e) {
				console.error(e);
				return ;
			}
		} else {
			data = Buffer(data + '');
			options.headers['Content-Type'] = 'text/plain';
		}

		options.headers['Content-Length'] = data.length;
	}

	var req = http.request(options);

	if (options.timeout && options.timeout > 0) {
		req.on('socket', function(socket) {
			socket.setTimeout(options.timeout);
			socket.on('timeout', function() {
				req.abort();
				reject('Error: timeout');
			});
		});
	}

	req.on('error', function(err) {
		reject(err);
	});

	req.on('abort', function() {
		reject('Error: The request was aborted!');
	});

	req.on('response', function(res) {
		res.setEncoding('utf8');

		res.data = '';
		res.on('data', function(d) {
			res.data += d.toString('utf8');
		});

		res.on('end', function() {
			try {
				res.body = JSON.parse(res.data);
			} catch(e) {
				console.error(e);
				return ;
			};
			resolve(res.data);
		});
	});

	if (data) {
		options.expect && req.on('continue', function() {
			req.write(data);
			req.end();
		});

		(!options.expect) && (function() {
			req.write(data);
			req.end();
		})();
	} else {
		req.end();
	}
};

module.exports = Request;<|endoftext|>


<commit_before>'use strict'

var fs = require('fs')
var xmlNodes = require('xml-nodes')
var xmlObjects = require('xml-objects')
var through2 = require('through2')
var splitStyle = require('inline-style-2-json')

module.exports = function pdftk2json (inputFile, node) {
  var all = []

  fs.createReadStream(__dirname + '/' + inputFile)
    .pipe(xmlNodes(node))
    .pipe(xmlObjects({explicitRoot: false, explicitArray: false, mergeAttrs: true}))
    .pipe(through2.obj(function (chunk, enc, callback) {
      chunk.style = splitStyle(chunk.style)
      this.push(chunk)
      callback()
    }))
    .on('data', function (data) {
      all.push(data)
    })
    .on('end', function (data) {
      if (all.length !== 0) {
        process.stdout.write(JSON.stringify(all) + '\n')
      }
    })
}
<commit_msg>Added opportunity for abs path, closes #1<commit_after>'use strict'

var fs = require('fs')
var xmlNodes = require('xml-nodes')
var xmlObjects = require('xml-objects')
var through2 = require('through2')
var splitStyle = require('inline-style-2-json')

module.exports = function pdftk2json (inputFile, node) {
  var all = []

  if (inputFile[0] !== '/') {
    inputFile = __dirname + '/' + inputFile
  }

  fs.createReadStream(inputFile)
    .pipe(xmlNodes(node))
    .pipe(xmlObjects({explicitRoot: false, explicitArray: false, mergeAttrs: true}))
    .pipe(through2.obj(function (chunk, enc, callback) {
      chunk.style = splitStyle(chunk.style)
      this.push(chunk)
      callback()
    }))
    .on('data', function (data) {
      all.push(data)
    })
    .on('end', function (data) {
      if (all.length !== 0) {
        process.stdout.write(JSON.stringify(all) + '\n')
      }
    })
}
<|endoftext|>


<commit_before>var Botkit = require('botkit')
var Witbot = require('node-wit')

var token = process.env.SLACK_TOKEN
var witToken = process.env.WIT_TOKEN

var controller = Botkit .slackbot({
  // reconnect to Slack RTM when connection goes bad
  retry: Infinity,
  debug: false
})

// Assume single team mode if we have a SLACK_TOKEN
if (token) {
  console.log('Starting in single-team mode')
  controller.spawn({
    token: token,
    retry: Infinity
  }).startRTM(function (err, bot, payload) {
    if (err) {
      throw new Error(err)
    }

    console.log('Connected to Slack RTM')
  })
// Otherwise assume multi-team mode - setup beep boop resourcer connection
} else {
  console.log('Starting in Beep Boop multi-team mode')
  require('beepboop-botkit').start(controller, { debug: true })
}

var witbot = Witbot.Wit({accessToken: witToken})

witbot.message('hello', {})
    .then((data) => {
    console.log('Yay, got Wit.ai response: ' + JSON.stringify(data))
})
.catch(console.error)<commit_msg>wit.ai intent test<commit_after>var Botkit = require('botkit')
var Witbot = require('node-wit')

var token = process.env.SLACK_TOKEN
var witToken = process.env.WIT_TOKEN

var controller = Botkit .slackbot({
  // reconnect to Slack RTM when connection goes bad
  retry: Infinity,
  debug: false
})

// Assume single team mode if we have a SLACK_TOKEN
if (token) {
  console.log('Starting in single-team mode')
  controller.spawn({
    token: token,
    retry: Infinity
  }).startRTM(function (err, bot, payload) {
    if (err) {
      throw new Error(err)
    }

    console.log('Connected to Slack RTM')
  })
// Otherwise assume multi-team mode - setup beep boop resourcer connection
} else {
  console.log('Starting in Beep Boop multi-team mode')
  require('beepboop-botkit').start(controller, { debug: true })
}

var witbot = Witbot.Wit({accessToken: witToken})

witbot.message('hi', {})
    .then((data) => {
    console.log('Yay, got Wit.ai response: ' + JSON.stringify(data))
})
.catch(console.error)<|endoftext|>


<commit_before>var express = require('express');
var app = express();

var PORT = process.env.PORT || 3000;

app.use(express.static('public'));

var server = app.listen(PORT, function () {
  var host = server.address().address;
  var port = server.address().port;

  console.log('quickfix listening at http://%s:%s', host, port);
});
<commit_msg>Add standard security headers.<commit_after>var express = require('express');
var app = express();

var PORT = process.env.PORT || 3000;

app.use(function(req, res, next) {
  res.setHeader('Strict-Transport-Security', 'max-age=600');
  res.setHeader('Content-Security-Policy', "script-src 'self'");
  res.setHeader('X-Frame-Options', 'SAMEORIGIN');
  res.setHeader('X-Xss-Protection', '1; mode=block');
  res.setHeader('X-Content-Type-Options', 'nosniff');
  next();
});

app.use(express.static('public'));

var server = app.listen(PORT, function () {
  var host = server.address().address;
  var port = server.address().port;

  console.log('quickfix listening at http://%s:%s', host, port);
});
<|endoftext|>


<commit_before>var xhr = require('corslite'),
    csv2geojson = require('csv2geojson'),
    wellknown = require('wellknown'),
    topojson = require('topojson'),
    toGeoJSON = require('togeojson');

module.exports.geojson = geojsonLoad;

module.exports.topojson = topojsonLoad;
module.exports.topojson.parse = topojsonParse;

module.exports.csv = csvLoad;
module.exports.csv.parse = csvParse;

module.exports.gpx = gpxLoad;
module.exports.gpx.parse = gpxParse;

module.exports.kml = kmlLoad;
module.exports.kml.parse = kmlParse;

module.exports.wkt = wktLoad;
module.exports.wkt.parse = wktParse;

function geojsonLoad(url, options) {
    var layer = L.geoJson(null, geojson);
    xhr(url, function(err, response) {
        if (err) return layer.fire('error', { error: err });
        layer.addData(JSON.parse(response.responseText));
        layer.fire('ready');
    });
    return layer;
}

function topojsonLoad(url, options) {
    var layer = L.geoJson(null, geojson);
    xhr(url, onload);
    function onload(err, response) {
        if (err) return layer.fire('error', { error: err });
        layer.addData(topojsonParse(response.responseText));
        layer.fire('ready');
    }
    return layer;
}

function topojsonParse(data) {
    var o = typeof data === 'string' ?
        JSON.parse(data) : data;
    var features = [];
    for (var i in o.objects) {
        var ft = topojson.feature(o, o.objects[i]);
        if (ft.features) features = features.concat(ft.features);
        else features = features.concat([ft]);
    }
    return features;
}

function csvLoad(url, options) {
    var layer = L.geoJson(null, geojson);
    xhr(url, onload);
    function onload(err, response) {
        var error;
        if (err) return layer.fire('error', { error: err });
        function avoidReady() {
            error = true;
        }
        layer.on('error', avoidReady);
        csvParse(response.responseText, options, layer);
        layer.off('error', avoidReady);
        if (!error) layer.fire('ready');
    }
    return layer;
}

function csvParse(csv, options, layer) {
    layer = layer || L.geoJson(null, geojson);
    options = options || {};
    csv2geojson.csv2geojson(csv, options, onparse);
    function onparse(err, geojson) {
        if (err) return layer.fire('error', { error: err });
        layer.addData(geojson);
    }
    return layer;
}

function gpxLoad(url, options) {
    var layer = L.geoJson(null, geojson);
    xhr(url, onload);
    function onload(err, response) {
        var error;
        if (err) return layer.fire('error', { error: err });
        function avoidReady() {
            error = true;
        }
        layer.on('error', avoidReady);
        gpxParse(response.responseXML || response.responseText, options, layer);
        layer.off('error', avoidReady);
        if (!error) layer.fire('ready');
    }
    return layer;
}

function gpxParse(gpx, options, layer) {
    var xml = parseXML(gpx);
    if (!xml) return layer.fire('error', {
        error: 'Could not parse GPX'
    });
    layer = layer || L.geoJson(null, geojson);
    var geojson = toGeoJSON.gpx(xml);
    layer.addData(geojson);
    return layer;
}

function kmlLoad(url, options) {
    var layer = L.geoJson(null, geojson);
    xhr(url, onload);
    function onload(err, response) {
        var error;
        if (err) return layer.fire('error', { error: err });
        function avoidReady() {
            error = true;
        }
        layer.on('error', avoidReady);
        kmlParse(response.responseXML || response.responseText, options, layer);
        layer.off('error', avoidReady);
        if (!error) layer.fire('ready');
    }
    return layer;
}

function kmlParse(gpx, options, layer) {
    var xml = parseXML(gpx);
    if (!xml) return layer.fire('error', {
        error: 'Could not parse GPX'
    });
    layer = layer || L.geoJson(null, geojson);
    var geojson = toGeoJSON.kml(xml);
    layer.addData(geojson);
    return layer;
}

function wktLoad(url, options) {
    var layer = L.geoJson(null, geojson);
    xhr(url, onload);
    function onload(err, response) {
        if (err) return layer.fire('error', { error: err });
        wktParse(response.responseText, options, layer);
        layer.fire('ready');
    }
    return layer;
}

function wktParse(wkt, options, layer) {
    layer = layer || L.geoJson(null, geojson);
    var geojson = wellknown(wkt);
    layer.addData(geojson);
    return layer;
}

function parseXML(str) {
    if (typeof str === 'string') {
        return (new DOMParser()).parseFromString(str, 'text/xml');
    } else {
        return str;
    }
}
<commit_msg>I meant options<commit_after>var xhr = require('corslite'),
    csv2geojson = require('csv2geojson'),
    wellknown = require('wellknown'),
    topojson = require('topojson'),
    toGeoJSON = require('togeojson');

module.exports.geojson = geojsonLoad;

module.exports.topojson = topojsonLoad;
module.exports.topojson.parse = topojsonParse;

module.exports.csv = csvLoad;
module.exports.csv.parse = csvParse;

module.exports.gpx = gpxLoad;
module.exports.gpx.parse = gpxParse;

module.exports.kml = kmlLoad;
module.exports.kml.parse = kmlParse;

module.exports.wkt = wktLoad;
module.exports.wkt.parse = wktParse;

function geojsonLoad(url, options) {
    var layer = L.geoJson(null, options);
    xhr(url, function(err, response) {
        if (err) return layer.fire('error', { error: err });
        layer.addData(JSON.parse(response.responseText));
        layer.fire('ready');
    });
    return layer;
}

function topojsonLoad(url, options) {
    var layer = L.geoJson(null, options);
    xhr(url, onload);
    function onload(err, response) {
        if (err) return layer.fire('error', { error: err });
        layer.addData(topojsonParse(response.responseText));
        layer.fire('ready');
    }
    return layer;
}

function topojsonParse(data) {
    var o = typeof data === 'string' ?
        JSON.parse(data) : data;
    var features = [];
    for (var i in o.objects) {
        var ft = topojson.feature(o, o.objects[i]);
        if (ft.features) features = features.concat(ft.features);
        else features = features.concat([ft]);
    }
    return features;
}

function csvLoad(url, options) {
    var layer = L.geoJson(null, options);
    xhr(url, onload);
    function onload(err, response) {
        var error;
        if (err) return layer.fire('error', { error: err });
        function avoidReady() {
            error = true;
        }
        layer.on('error', avoidReady);
        csvParse(response.responseText, options, layer);
        layer.off('error', avoidReady);
        if (!error) layer.fire('ready');
    }
    return layer;
}

function csvParse(csv, options, layer) {
    layer = layer || L.geoJson(null, options);
    options = options || {};
    csv2geojson.csv2geojson(csv, options, onparse);
    function onparse(err, geojson) {
        if (err) return layer.fire('error', { error: err });
        layer.addData(geojson);
    }
    return layer;
}

function gpxLoad(url, options) {
    var layer = L.geoJson(null, options);
    xhr(url, onload);
    function onload(err, response) {
        var error;
        if (err) return layer.fire('error', { error: err });
        function avoidReady() {
            error = true;
        }
        layer.on('error', avoidReady);
        gpxParse(response.responseXML || response.responseText, options, layer);
        layer.off('error', avoidReady);
        if (!error) layer.fire('ready');
    }
    return layer;
}

function gpxParse(gpx, options, layer) {
    var xml = parseXML(gpx);
    if (!xml) return layer.fire('error', {
        error: 'Could not parse GPX'
    });
    layer = layer || L.geoJson(null, options);
    var geojson = toGeoJSON.gpx(xml);
    layer.addData(geojson);
    return layer;
}

function kmlLoad(url, options) {
    var layer = L.geoJson(null, options);
    xhr(url, onload);
    function onload(err, response) {
        var error;
        if (err) return layer.fire('error', { error: err });
        function avoidReady() {
            error = true;
        }
        layer.on('error', avoidReady);
        kmlParse(response.responseXML || response.responseText, options, layer);
        layer.off('error', avoidReady);
        if (!error) layer.fire('ready');
    }
    return layer;
}

function kmlParse(gpx, options, layer) {
    var xml = parseXML(gpx);
    if (!xml) return layer.fire('error', {
        error: 'Could not parse GPX'
    });
    layer = layer || L.geoJson(null, options);
    var geojson = toGeoJSON.kml(xml);
    layer.addData(geojson);
    return layer;
}

function wktLoad(url, options) {
    var layer = L.geoJson(null, options);
    xhr(url, onload);
    function onload(err, response) {
        if (err) return layer.fire('error', { error: err });
        wktParse(response.responseText, options, layer);
        layer.fire('ready');
    }
    return layer;
}

function wktParse(wkt, options, layer) {
    layer = layer || L.geoJson(null, options);
    var geojson = wellknown(wkt);
    layer.addData(geojson);
    return layer;
}

function parseXML(str) {
    if (typeof str === 'string') {
        return (new DOMParser()).parseFromString(str, 'text/xml');
    } else {
        return str;
    }
}
<|endoftext|>


<commit_before>'use strict'

const config  = require('config')
const Bot     = require('node-telegram-bot-api')
const so      = require('so')
const station = require('vbb-stations-autocomplete')

const lib     = require('./lib')
const render  = require('./lib/render')

const token = config.telegramToken
const bot = new Bot(token, {polling: true})

const log = (msg) => console.info(
	  msg.from.username
	, render.time(msg.date)
	, msg.text
)

const instructions = `\
You can use this bot to check public transport departures in Berlin & Brandenburg.

\`/departure <station>\` – Show the next departures.
\`/route <a> to <b>\` – Get routes from A to B.

If you send a location, it will respond with the closest stations.
`
const help = (bot) => (msg) =>
	bot.sendMessage(msg.chat.id, instructions, {parse_mode: 'Markdown'})

const dep = (bot) => (msg, match) => so(function* (msg, match) {
	log(msg)
	const stations = station(match[1], 1)
	if (stations.length === 0) return bot.sendMessage(msg.chat.id,
		'Could\'t find this station.')

	const deps = yield lib.deps(stations[0].id)
	bot.sendMessage(msg.chat.id, render.deps(stations[0], deps), {
		parse_mode: 'Markdown'
	})
})(msg, match).catch((err) => console.error(err.stack))

const nearby = (bot) => (msg) => so(function* (msg) {
	log(msg)
	const lat = msg.location.latitude, lon = msg.location.longitude
	const closest = yield lib.closest(lat, lon, 2000, 3)
	bot.sendMessage(msg.chat.id, render.nearby(closest), {
		parse_mode: 'Markdown'
	})
})(msg).catch((err) => console.error(err.stack))

const route = (bot) => (msg, matches) => so(function* (msg) {
	log(msg)
	const from = station(matches[1], 1)[0]
	if (!from) return bot.sendMessage(msg.chat.id,
		'Could\'t find the first station.')
	const to = station(matches[2], 1)[0]
	if (!to) return bot.sendMessage(msg.chat.id,
		'Could\'t find the second station.')

	const routes = yield lib.routes(from.id, to.id)
	console.log(require('util').inspect(routes[3], {depth: null}))
	bot.sendMessage(msg.chat.id, routes
		.map((route) => render.route(from, to, route))
		.join('\n\n---\n\n')
	, {parse_mode: 'Markdown'})
})(msg).catch((err) => console.error(err.stack))

bot.onText(/\/(?:dep|departure|abfahrt) (.+)/i, dep(bot))
bot.onText(/\/(?:start|help|hilfe)/i, help(bot))
bot.onText(/\/(?:route|journey) (.+) to (.+)/i, route(bot))
bot.on('message', (msg) => {
	if (!msg.text && msg.location) nearby(bot)(msg)
})
<commit_msg>new command names<commit_after>'use strict'

const config  = require('config')
const Bot     = require('node-telegram-bot-api')
const so      = require('so')
const station = require('vbb-stations-autocomplete')

const lib     = require('./lib')
const render  = require('./lib/render')

const token = config.telegramToken
const bot = new Bot(token, {polling: true})

const log = (msg) => console.info(
	  msg.from.username
	, render.time(msg.date)
	, msg.text
)

const instructions = `\
You can use this bot to check public transport departures in Berlin & Brandenburg.

\`/a(bfahrt) <station> \` – Show the next departures.
\`/r(oute)   <a> to <b>\` – Get routes from A to B.

If you send a location, it will respond with the closest stations.
`
const help = (bot) => (msg) =>
	bot.sendMessage(msg.chat.id, instructions, {parse_mode: 'Markdown'})

const departure = (bot) => (msg, match) => so(function* (msg, match) {
	log(msg)
	const stations = station(match[1], 1)
	if (stations.length === 0) return bot.sendMessage(msg.chat.id,
		'Could\'t find this station.')

	const deps = yield lib.deps(stations[0].id)
	bot.sendMessage(msg.chat.id, render.deps(stations[0], deps), {
		parse_mode: 'Markdown'
	})
})(msg, match).catch((err) => console.error(err.stack))

const nearby = (bot) => (msg) => so(function* (msg) {
	log(msg)
	const lat = msg.location.latitude, lon = msg.location.longitude
	const closest = yield lib.closest(lat, lon, 2000, 3)
	bot.sendMessage(msg.chat.id, render.nearby(closest), {
		parse_mode: 'Markdown'
	})
})(msg).catch((err) => console.error(err.stack))

const route = (bot) => (msg, matches) => so(function* (msg) {
	log(msg)
	const from = station(matches[1], 1)[0]
	if (!from) return bot.sendMessage(msg.chat.id,
		'Could\'t find the first station.')
	const to = station(matches[2], 1)[0]
	if (!to) return bot.sendMessage(msg.chat.id,
		'Could\'t find the second station.')

	const routes = yield lib.routes(from.id, to.id)
	console.log(require('util').inspect(routes[3], {depth: null}))
	bot.sendMessage(msg.chat.id, routes
		.map((route) => render.route(from, to, route))
		.join('\n\n---\n\n')
	, {parse_mode: 'Markdown'})
})(msg).catch((err) => console.error(err.stack))

bot.onText(/\/(?:a|abfahrt) (.+)/i, departure(bot))
bot.onText(/\/(?:start|help|hilfe)/i, help(bot))
bot.onText(/\/(?:r|route) (.+) to (.+)/i, route(bot))
bot.on('message', (msg) => {
	if (!msg.text && msg.location) nearby(bot)(msg)
})
<|endoftext|>