<commit_before>/**
 * Imports
 */
// through2 is a thin wrapper around node transform streams
var through = require('through2'),
	gutil = require('gulp-util'),
	fs = require('fs'),
	path = require('path'),
	_ = require('lodash'),
	PluginError = gutil.PluginError;

/**
 * Variables
 */
// read item template file
var itemsCollection = [],
	dir,
	itemTemplate = fs.readFileSync(__dirname + '/templates/item.html').toString(),
	navTemplate = fs.readFileSync(__dirname + '/templates/nav.html').toString();

// consts
const PLUGIN_NAME = 'concat-html';

// Used to replace anything within a start and end tag.
var replaceRegExp = /<!--\s*?styleguide\s*?-->[\s\S]*?<!--\s*?endstyleguide\s*?-->/g;

// Used to remove start and end tags.
var removeRegExp = / *?<!--\s*?styleguide\s*?--> *\n?| *?<!--\s*?endstyleguide\s*?--> *\n?/g;

var navRegExp = /<!--\s*?sg-nav\s*?-->[\s\S]*?<!--\s*?endsg-nav\s*?-->/g;

/**
 * Build each item
 * @return {Stream} NodeJS Stream
  */
function build() {
	var contentHtml = '';

	// creating a stream through which each file will pass
	var stream = through.obj(function(file, enc, cb) {
		var data = {
			code: file.contents.toString().replace(/\</gi, '<'),
			contents: file.contents.toString(),
			name: path.basename(file.relative, '.html'),
			file: 'item.html'
		};

		var currentDir = path.dirname(file.relative);

		if (dir !== currentDir) {
			itemsCollection.push({
				name: currentDir,
				items: []
			});
		}

		// add items list (nav)
		itemsCollection[itemsCollection.length-1].items.push(data.name);

		dir = currentDir;

		// parse item template
		contentHtml = gutil.template(itemTemplate, data);

		file.contents = new Buffer(contentHtml);

		this.push(file);

		return cb();
	});

	// returning the file stream
	return stream;
}

/**
 * Replaces <!-- styleguide --> with the generated content
 * @param  {String} source - HTML template
 * @param  {String} dest - Generated HTML
 * @return {Stream} NodeJS Stream
 */
function replaceHtml(source, dest) {
	// read index file
	var index = fs.readFileSync(source).toString();

	if (!dest) {
		throw new PluginError(PLUGIN_NAME, 'Missing index path!');
	}

	// creating a stream through which each file will pass
	var stream = through.obj(function(file, enc, cb) {

		if (file.isNull()) {
			 // do nothing if no contents
		}

		index = index.replace(replaceRegExp, file.contents.toString());

		// create nav
		var nav = _.template(navTemplate, {
			folders: itemsCollection,
		});

		index = index.replace(navRegExp, nav);

		// create new file
		var processedFile = new gutil.File({
			path: dest,
			contents: new Buffer(index)
		});

		this.push(processedFile);

		return cb();
	});

	// returning the file stream
	return stream;
};

var concatHtml = {
	replaceHtml: replaceHtml,
	build: build
};

// exporting the plugin main function
module.exports = concatHtml;<commit_msg>implemented refactor: reading contents using cheerio<commit_after>/**
 * Imports
 */
// through2 is a thin wrapper around node transform streams
var through = require('through2'),
	gutil = require('gulp-util'),
	fs = require('fs'),
	path = require('path'),
	_ = require('lodash'),
	cheerio = require('cheerio'),
	PluginError = gutil.PluginError;

/**
 * Variables
 */
// read item template file
var itemsCollection = [],
	dir,
	itemTemplate = fs.readFileSync(__dirname + '/templates/item.html').toString(),
	navTemplate = fs.readFileSync(__dirname + '/templates/nav.html').toString();

// consts
var PLUGIN_NAME = 'concat-html';

// Used to replace anything within a start and end tag.
var replaceRegExp = /<!--\s*?styleguide\s*?-->[\s\S]*?<!--\s*?endstyleguide\s*?-->/g;

// Used to remove start and end tags.
var removeRegExp = / *?<!--\s*?styleguide\s*?--> *\n?| *?<!--\s*?endstyleguide\s*?--> *\n?/g;

var navRegExp = /<!--\s*?sg-nav\s*?-->[\s\S]*?<!--\s*?endsg-nav\s*?-->/g;

/**
 * Build each item
 * @return {Stream} NodeJS Stream
  */
function build() {
	var contentHtml = '';

	// creating a stream through which each file will pass
	var stream = through.obj(function(file, enc, cb) {
		var data = {
			code: file.contents.toString().replace(/\</gi, '<'),
			contents: file.contents.toString(),
			name: path.basename(file.relative, '.html'),
			file: 'item.html'
		};

		$ = cheerio.load(file.contents.toString());

		if ($(".sg-code").length) {
			data.code = $(".sg-code").html().toString().replace(/\</gi, '<');
		}

		if ($(".sg-example").length) {
			data.contents = $(".sg-example").html().toString();
		}

		var currentDir = path.dirname(file.relative);

		if (dir !== currentDir) {
			itemsCollection.push({
				name: currentDir,
				items: []
			});
		}

		// add items list (nav)
		itemsCollection[itemsCollection.length-1].items.push(data.name);

		dir = currentDir;

		// parse item template
		contentHtml = gutil.template(itemTemplate, data);

		file.contents = new Buffer(contentHtml);

		this.push(file);

		return cb();
	});

	// returning the file stream
	return stream;
}

/**
 * Replaces <!-- styleguide --> with the generated content
 * @param  {String} source - HTML template
 * @param  {String} dest - Generated HTML
 * @return {Stream} NodeJS Stream
 */
function replaceHtml(source, dest) {
	// read index file
	var index = fs.readFileSync(source).toString();

	if (!dest) {
		throw new PluginError(PLUGIN_NAME, 'Missing index path!');
	}

	// creating a stream through which each file will pass
	var stream = through.obj(function(file, enc, cb) {

		if (file.isNull()) {
			 // do nothing if no contents
		}

		index = index.replace(replaceRegExp, file.contents.toString());

		// create nav
		var nav = _.template(navTemplate, {
			folders: itemsCollection,
		});

		index = index.replace(navRegExp, nav);

		// create new file
		var processedFile = new gutil.File({
			path: dest,
			contents: new Buffer(index)
		});

		this.push(processedFile);

		return cb();
	});

	// returning the file stream
	return stream;
}

var concatHtml = {
	replaceHtml: replaceHtml,
	build: build
};

// exporting the plugin main function
module.exports = concatHtml;<|endoftext|>


<commit_before>var express = require('express');
var app = express();
var rquest = require('request');
app.set('port', (process.env.PORT || 5000));

app.use(express.static(__dirname + '/public'));

var bodyParser = require('body-parser')
app.use( bodyParser.json() );       // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
  extended: true
}));

// views is directory for all template files
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');

app.get('/', function(request, response) {
  response.render('pages/index');
});

app.post('/', function(request, response) {
  if(request.body['command'] == "/onenoteurl"){
      var url = request.body['text'];

var decodedUrl = decodeURIComponent(url);
console.log(decodedUrl);
var first = decodedUrl.indexOf(".one|")+ 5
;
console.log(" first = " + first);
var second = decodedUrl.indexOf("/", first);
console.log(" second = " + second);
var third = decodedUrl.lastIndexOf("|");
console.log(" third = " + third);
var actualName = decodedUrl.substr(second, third-second);

var name = actualName+" (Webview)";
      var responseUrl = request.body['response_url'];
      var returnVal = {
    "response_type": "in_channel",
    "text": "A OneNote link to page was pasted",
    "attachments": [
        {
            "title": name + "<WebView>",
            "title_link": url
        }
    ]
};
}
    response.send({"response_type": "ephemeral",
    "text": "A OneNote link to page was pasted",

    });

    rquest({
      url: request.body['response_url'],
      method: 'POST',
      body: returnVal,
      json: true
    }, function () {
      response.end();
    });

//     console.log(request.body['response_url']);

//   //  request.post('http://service.com/upload', {form:{key:'value'}})
//     rquest.post(request.body['response_url'], returnVal);
//     // request.url = request.body['response_url'];
//     // request.send(returnVal);
}

);

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

<commit_msg>fixed up the naming of the link<commit_after>var express = require('express');
var app = express();
var rquest = require('request');
app.set('port', (process.env.PORT || 5000));

app.use(express.static(__dirname + '/public'));

var bodyParser = require('body-parser')
app.use( bodyParser.json() );       // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
  extended: true
}));

// views is directory for all template files
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');

app.get('/', function(request, response) {
  response.render('pages/index');
});

app.post('/', function(request, response) {
  if(request.body['command'] == "/onenoteurl"){
      var url = request.body['text'];

var decodedUrl = decodeURIComponent(url);
console.log(decodedUrl);
var first = decodedUrl.indexOf(".one|")+ 5
;
console.log(" first = " + first);
var second = decodedUrl.indexOf("/", first);
console.log(" second = " + second);
var third = decodedUrl.lastIndexOf("|");
console.log(" third = " + third);
var actualName = decodedUrl.substr(second, third-second);

var name = actualName+" (Webview)";
      var responseUrl = request.body['response_url'];
      var returnVal = {
    "response_type": "in_channel",
    "text": "A OneNote link to page was pasted",
    "attachments": [
        {
            "title": name,
            "title_link": url
        }
    ]
};
}
    response.send({"response_type": "ephemeral",
        "text": "Going to minimize the url for easy reading :D",

    });

    rquest({
      url: request.body['response_url'],
      method: 'POST',
      body: returnVal,
      json: true
    }, function () {
      response.end();
    });
}

);

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

<|endoftext|>


<commit_before>(function() {

  var crypto = require('crypto');
  var BigInteger = require('jsbn');
  var converters = require('./util/converters.js');
  var curve25519 = require('./util/curve25519.js');
  var NxtAddress = require('./util/nxtaddress.js');

  var epochNum = 1385294400;

  /**
   * Public functions
   */
  function getNxtTime() {
    return Math.floor(Date.now() / 1000) - epochNum;
  };

  function secretPhraseToPublicKey(secretPhrase) {
    var secretPhraseBytes = converters.stringToByteArray(secretPhrase);
    var digest = simpleHash(secretPhraseBytes);
    var pubKey = curve25519.keygen(digest).p;
    return converters.byteArrayToHexString(pubKey);
  };

  function publicKeyToAccountId(publicKey, numeric) {

    var hex = converters.hexStringToByteArray(publicKey);
    var buf = Buffer.from(hex)
    var account = crypto.createHash('sha256').update(buf).digest();

    account = converters.byteArrayToHexString(account);
    var slice = (converters.hexStringToByteArray(account)).slice(0, 8);
    var accountId = byteArrayToBigInteger(slice).toString();

    if (numeric) {
      return accountId;
    }
    var address = new NxtAddress();
    if (!address.set(accountId)) {
      return '';
    }
    return address.toString();
  };

  function secretPhraseToAccountId(secretPhrase, numeric) {
    var pubKey = secretPhraseToPublicKey(secretPhrase);
    return publicKeyToAccountId(pubKey, numeric);
  };

  function signTransactionBytes(data, secretPhrase) {

    var unsignedBytes = converters.hexStringToByteArray(data);
    var sig = signBytes(unsignedBytes, secretPhrase);

    var signed = unsignedBytes.slice(0,96);
    signed = signed.concat(sig);
    signed = signed.concat(unsignedBytes.slice(96 + 64));

    return converters.byteArrayToHexString(signed);
  };

  function createToken(websiteString, secretPhrase) {
    var hexwebsite = converters.stringToHexString(websiteString);
    var website = converters.hexStringToByteArray(hexwebsite);
    var data = [];
    data = website.concat(getPublicKey(secretPhrase));
    var unix = Math.round(+new Date() / 1000);
    var timestamp = unix - epochNum;
    var timestamparray = toByteArray(timestamp);
    data = data.concat(timestamparray);

    var token = [];
    token = getPublicKey(secretPhrase).concat(timestamparray);

    var sig = signBytes(data, secretPhrase);

    token = token.concat(sig);

    var buf = '';
    for (var ptr = 0; ptr < 100; ptr += 5) {

      var nbr = [];
      nbr[0] = token[ptr] & 0xFF;
      nbr[1] = token[ptr + 1] & 0xFF;
      nbr[2] = token[ptr + 2] & 0xFF;
      nbr[3] = token[ptr + 3] & 0xFF;
      nbr[4] = token[ptr + 4] & 0xFF;
      var number = byteArrayToBigInteger(nbr);

      if (number < 32) {
        buf += '0000000';
      } else if (number < 1024) {
        buf += '000000';
      } else if (number < 32768) {
        buf += '00000';
      } else if (number < 1048576) {
        buf += '0000';
      } else if (number < 33554432) {
        buf += '000';
      } else if (number < 1073741824) {
        buf += '00';
      } else if (number < 34359738368) {
        buf += '0';
      }
      buf += number.toString(32);
    }

    return buf;
  };

  function parseToken(tokenString, website) {
    var websiteBytes = converters.stringToByteArray(website);
    var tokenBytes = [];
    var i = 0;
    var j = 0;

    for (; i < tokenString.length; i += 8, j += 5) {

      var number = new BigInteger(tokenString.substring(i, i + 8), 32);
      var part = converters.hexStringToByteArray(number.toRadix(16));

      tokenBytes[j] = part[4];
      tokenBytes[j + 1] = part[3];
      tokenBytes[j + 2] = part[2];
      tokenBytes[j + 3] = part[1];
      tokenBytes[j + 4] = part[0];
    }

    if (i != 160) {
      return new Error('tokenString parsed to invalid size');
    }
    var publicKey = [];
    publicKey = tokenBytes.slice(0, 32);
    var timebytes = [
      tokenBytes[32],
      tokenBytes[33],
      tokenBytes[34],
      tokenBytes[35],
    ];

    var timestamp = toIntVal(timebytes);
    var signature = tokenBytes.slice(36, 100);

    var data = websiteBytes.concat(tokenBytes.slice(0, 36));

    var isValid = verifyBytes(signature, data, publicKey);

    var ret = {};
    ret.isValid = isValid;
    ret.timestamp = timestamp;
    ret.publicKey = converters.byteArrayToHexString(publicKey);
    ret.accountRS = publicKeyToAccountId(ret.publicKey);

    return ret;
  };

  /**
   * Private functions
   */

  function simpleHash(message) {
    var buf = Buffer.from(message);
    var hash = crypto.createHash('sha256').update(buf).digest('hex');
    return converters.hexStringToByteArray(hash)
  };

  function byteArrayToBigInteger(byteArray, startIndex) {
    var value = new BigInteger('0', 10);
    var temp1, temp2;
    for (var i = byteArray.length - 1; i >= 0; i--) {
      temp1 = value.multiply(new BigInteger('256', 10));
      temp2 = temp1.add(new BigInteger(byteArray[i].toString(10), 10));
      value = temp2;
    }
    return value;
  };

  function toByteArray(long) {
    // We want to represent the input as a 8-bytes array
    var byteArray = [0, 0, 0, 0];
    for (var index = 0; index < byteArray.length; index ++) {
      var byte = long & 0xff;
      byteArray [ index ] = byte;
      long = (long - byte) / 256 ;
    }
    return byteArray;
  };

  function toIntVal(byteArray) {
    // We want to represent the input as a 8-bytes array
    var intval = 0;
    for (var index = 0; index < byteArray.length; index ++) {
      var byt = byteArray[index] & 0xFF;
      var value = byt * Math.pow(256, index);
      intval += value;
    }
    return intval;
  };

  function areByteArraysEqual(bytes1, bytes2) {
    if (bytes1.length !== bytes2.length) {
      return false;
    }
    for (var i = 0; i < bytes1.length; ++i) {
      if (bytes1[i] !== bytes2[i]) {
        return false;
      }
    }
    return true;
  };

  function getPublicKey(secretPhrase) {
    var hash = crypto.createHash('sha256').update(secretPhrase);
    var ky = converters.byteArrayToHexString(
      curve25519.keygen(
        hash.digest()
      ).p
    );
    return converters.hexStringToByteArray(ky);
  };

  function signBytes(message, secretPhrase) {
    var messageBytes = message;
    var secretPhraseBytes = converters.stringToByteArray(secretPhrase);

    var digest = simpleHash(secretPhraseBytes);
    var s = curve25519.keygen(digest).s;
    var m = simpleHash(messageBytes);

    var hash = crypto.createHash('sha256');
    var mBuf = Buffer.from(m);
    var sBuf = Buffer.from(s);
    hash.update(mBuf)
    hash.update(sBuf)
    var x = hash.digest()

    var y = curve25519.keygen(x).p;

    hash = crypto.createHash('sha256');
    var yBuf = Buffer.from(y)
    hash.update(mBuf)
    hash.update(yBuf)
    var h = converters.hexStringToByteArray(
      hash.digest('hex')
    );

    var v = curve25519.sign(h, x, s);
    return v.concat(h);
  };

  function verifyBytes(signature, message, publicKey) {
    var signatureBytes = signature;
    var messageBytes = message;
    var publicKeyBytes = publicKey;
    var v = signatureBytes.slice(0, 32);
    var h = signatureBytes.slice(32);
    var y = Buffer.from(
      curve25519.verify(v, h, publicKeyBytes)
    );

    var m = Buffer.from(simpleHash(messageBytes));
    var hash = crypto.createHash('sha256');
    hash.update(m);
    hash.update(y);
    var h2 = hash.digest();

    return areByteArraysEqual(h, h2);
  };

  module.exports = {
    getNxtTime: getNxtTime,
    secretPhraseToPublicKey: secretPhraseToPublicKey,
    publicKeyToAccountId: publicKeyToAccountId,
    secretPhraseToAccountId: secretPhraseToAccountId,
    signTransactionBytes: signTransactionBytes,
    createToken: createToken,
    parseToken: parseToken,
  };

})();
<commit_msg>reduce use of converters<commit_after>(function() {

  var crypto = require('crypto');
  var BigInteger = require('jsbn');
  var converters = require('./util/converters.js');
  var curve25519 = require('./util/curve25519.js');
  var NxtAddress = require('./util/nxtaddress.js');

  var epochNum = 1385294400;

  /**
   * Public functions
   */
  function getNxtTime() {
    return Math.floor(Date.now() / 1000) - epochNum;
  };

  function secretPhraseToPublicKey(secretPhrase) {
    var hash = converters.hexStringToByteArray(
      simpleHash(secretPhrase, 'hex')
    );
    var pubKey = curve25519.keygen(hash).p;
    return converters.byteArrayToHexString(pubKey);
  };

  function publicKeyToAccountId(publicKey, numeric) {
    var arr = converters.hexStringToByteArray(publicKey);
    var account = simpleHash(arr, 'hex');

    var slice = (converters.hexStringToByteArray(account)).slice(0, 8);
    var accountId = byteArrayToBigInteger(slice).toString();

    if (numeric) {
      return accountId;
    }
    var address = new NxtAddress();
    if (!address.set(accountId)) {
      return '';
    }
    return address.toString();
  };

  function secretPhraseToAccountId(secretPhrase, numeric) {
    var pubKey = secretPhraseToPublicKey(secretPhrase);
    return publicKeyToAccountId(pubKey, numeric);
  };

  function signTransactionBytes(data, secretPhrase) {

    var unsignedBytes = converters.hexStringToByteArray(data);
    var sig = signBytes(unsignedBytes, secretPhrase);

    var signed = unsignedBytes.slice(0,96);
    signed = signed.concat(sig);
    signed = signed.concat(unsignedBytes.slice(96 + 64));

    return converters.byteArrayToHexString(signed);
  };

  function createToken(websiteString, secretPhrase) {
    var hexwebsite = converters.stringToHexString(websiteString);
    var website = converters.hexStringToByteArray(hexwebsite);
    var data = [];
    data = website.concat(getPublicKey(secretPhrase));
    var unix = Math.round(+new Date() / 1000);
    var timestamp = unix - epochNum;
    var timestamparray = toByteArray(timestamp);
    data = data.concat(timestamparray);

    var token = [];
    token = getPublicKey(secretPhrase).concat(timestamparray);

    var sig = signBytes(data, secretPhrase);

    token = token.concat(sig);

    var buf = '';
    for (var ptr = 0; ptr < 100; ptr += 5) {

      var nbr = [];
      nbr[0] = token[ptr] & 0xFF;
      nbr[1] = token[ptr + 1] & 0xFF;
      nbr[2] = token[ptr + 2] & 0xFF;
      nbr[3] = token[ptr + 3] & 0xFF;
      nbr[4] = token[ptr + 4] & 0xFF;
      var number = byteArrayToBigInteger(nbr);

      if (number < 32) {
        buf += '0000000';
      } else if (number < 1024) {
        buf += '000000';
      } else if (number < 32768) {
        buf += '00000';
      } else if (number < 1048576) {
        buf += '0000';
      } else if (number < 33554432) {
        buf += '000';
      } else if (number < 1073741824) {
        buf += '00';
      } else if (number < 34359738368) {
        buf += '0';
      }
      buf += number.toString(32);
    }

    return buf;
  };

  function parseToken(tokenString, website) {
    var websiteBytes = converters.stringToByteArray(website);
    var tokenBytes = [];
    var i = 0;
    var j = 0;

    for (; i < tokenString.length; i += 8, j += 5) {

      var number = new BigInteger(tokenString.substring(i, i + 8), 32);
      var part = converters.hexStringToByteArray(number.toRadix(16));

      tokenBytes[j] = part[4];
      tokenBytes[j + 1] = part[3];
      tokenBytes[j + 2] = part[2];
      tokenBytes[j + 3] = part[1];
      tokenBytes[j + 4] = part[0];
    }

    if (i != 160) {
      return new Error('tokenString parsed to invalid size');
    }
    var publicKey = [];
    publicKey = tokenBytes.slice(0, 32);
    var timebytes = [
      tokenBytes[32],
      tokenBytes[33],
      tokenBytes[34],
      tokenBytes[35],
    ];

    var timestamp = toIntVal(timebytes);
    var signature = tokenBytes.slice(36, 100);

    var data = websiteBytes.concat(tokenBytes.slice(0, 36));

    var isValid = verifyBytes(signature, data, publicKey);

    var ret = {};
    ret.isValid = isValid;
    ret.timestamp = timestamp;
    ret.publicKey = converters.byteArrayToHexString(publicKey);
    ret.accountRS = publicKeyToAccountId(ret.publicKey);

    return ret;
  };

  /**
   * Private functions
   */
  function simpleHash(message, encoding) {
    if (message instanceof Array) {
      message = Buffer.from(message);
    }
    return crypto.createHash('sha256').update(message).digest(encoding);
  };

  function byteArrayToBigInteger(byteArray, startIndex) {
    var value = new BigInteger('0', 10);
    var temp1, temp2;
    for (var i = byteArray.length - 1; i >= 0; i--) {
      temp1 = value.multiply(new BigInteger('256', 10));
      temp2 = temp1.add(new BigInteger(byteArray[i].toString(10), 10));
      value = temp2;
    }
    return value;
  };

  function toByteArray(long) {
    // We want to represent the input as a 8-bytes array
    var byteArray = [0, 0, 0, 0];
    for (var index = 0; index < byteArray.length; index ++) {
      var byte = long & 0xff;
      byteArray [ index ] = byte;
      long = (long - byte) / 256 ;
    }
    return byteArray;
  };

  function toIntVal(byteArray) {
    // We want to represent the input as a 8-bytes array
    var intval = 0;
    for (var index = 0; index < byteArray.length; index ++) {
      var byt = byteArray[index] & 0xFF;
      var value = byt * Math.pow(256, index);
      intval += value;
    }
    return intval;
  };

  function areByteArraysEqual(bytes1, bytes2) {
    if (bytes1.length !== bytes2.length) {
      return false;
    }
    for (var i = 0; i < bytes1.length; ++i) {
      if (bytes1[i] !== bytes2[i]) {
        return false;
      }
    }
    return true;
  };

  function getPublicKey(secretPhrase) {
    var hash = crypto.createHash('sha256').update(secretPhrase);
    var ky = converters.byteArrayToHexString(
      curve25519.keygen(
        hash.digest()
      ).p
    );
    return converters.hexStringToByteArray(ky);
  };

  function signBytes(message, secretPhrase) {
    var messageBytes = message;
    var secretPhraseBytes = converters.stringToByteArray(secretPhrase);

    var digest = simpleHash(secretPhraseBytes);
    var s = curve25519.keygen(digest).s;
    var m = simpleHash(messageBytes);

    var hash = crypto.createHash('sha256');
    var mBuf = Buffer.from(m);
    var sBuf = Buffer.from(s);
    hash.update(mBuf)
    hash.update(sBuf)
    var x = hash.digest()

    var y = curve25519.keygen(x).p;

    hash = crypto.createHash('sha256');
    var yBuf = Buffer.from(y)
    hash.update(mBuf)
    hash.update(yBuf)
    var h = converters.hexStringToByteArray(
      hash.digest('hex')
    );

    var v = curve25519.sign(h, x, s);
    return v.concat(h);
  };

  function verifyBytes(signature, message, publicKey) {
    var signatureBytes = signature;
    var messageBytes = message;
    var publicKeyBytes = publicKey;
    var v = signatureBytes.slice(0, 32);
    var h = signatureBytes.slice(32);
    var y = Buffer.from(
      curve25519.verify(v, h, publicKeyBytes)
    );

    var m = Buffer.from(simpleHash(messageBytes));
    var hash = crypto.createHash('sha256');
    hash.update(m);
    hash.update(y);
    var h2 = hash.digest();

    return areByteArraysEqual(h, h2);
  };

  module.exports = {
    getNxtTime: getNxtTime,
    secretPhraseToPublicKey: secretPhraseToPublicKey,
    publicKeyToAccountId: publicKeyToAccountId,
    secretPhraseToAccountId: secretPhraseToAccountId,
    signTransactionBytes: signTransactionBytes,
    createToken: createToken,
    parseToken: parseToken,
  };

})();
<|endoftext|>


<commit_before>module.exports = {
  "env": {
    "node": true
  },

  "rules": {

    /**
     * Possible Errors
     * The following rules point out areas where you might have made mistakes.
     */

    // disallow or enforce trailing commas
    "comma-dangle": [1, "never"],

    // disallow assignment in conditional expressions
    "no-cond-assign": 2,

    // disallow use of console (off by default in the node environment)
    "no-console": 2,

    // disallow use of constant expressions in conditions
    "no-constant-condition": 1,

    // disallow control characters in regular expressions
    "no-control-regex": 2,

    // disallow use of debugger
    "no-debugger": 2,

    // disallow duplicate arguments in functions
    "no-dupe-args": 2,

    // disallow duplicate keys when creating object literals
    "no-dupe-keys": 2,

    // disallow a duplicate case label.
    "no-duplicate-case": 2,

    // disallow empty statements
    "no-empty": 2,

    // disallow the use of empty character classes in regular expressions
    "no-empty-character-class": 2,

    // disallow assigning to the exception in a catch block
    "no-ex-assign": 2,

    // disallow double-negation boolean casts in a boolean context
    "no-extra-boolean-cast": 2,

    // disallow unnecessary parentheses (off by default)
    "no-extra-parens": 2,

    // disallow unnecessary semicolons
    "no-extra-semi": 2,

    // disallow overwriting functions written as function declarations
    "no-func-assign": 2,

    // disallow function or variable declarations in nested blocks
    "no-inner-declarations": 2,

    // disallow invalid regular expression strings in the RegExp constructor
    "no-invalid-regexp": 2,

    // disallow irregular whitespace outside of strings and comments
    "no-irregular-whitespace": 2,

    // disallow negation of the left operand of an in expression
    "no-negated-in-lhs": 2,

    // disallow the use of object properties of the global object (Math and JSON) as functions
    "no-obj-calls": 2,

    // disallow multiple spaces in a regular expression literal
    "no-regex-spaces": 2,

    // disallow sparse arrays
    "no-sparse-arrays": 2,

    // disallow unreachable statements after a return, throw, continue, or break statement
    "no-unreachable": 2,

    // disallow comparisons with the value NaN
    "use-isnan": 2,

    // Ensure JSDoc comments are valid (off by default)
    "valid-jsdoc": [
      2,
      {
        "prefer": {
          "returns": "return"
        },
        "requireReturn": false,
        "requireParamDescription": false,
        "requireReturnDescription": false
      }
    ],

    // Ensure that the results of typeof are compared against a valid string
    "valid-typeof": 2,

    // Avoid code that looks like two expressions but is actually one (off by default)
    "no-unexpected-multiline": 2,

    /**
     * Best Practices
     * These are rules designed to prevent you from making mistakes.
     * They either prescribe a better way of doing something or help you avoid footguns.
     */

    // enforces getter/setter pairs in objects (off by default)
    "accessor-pairs": 0,

    // treat var statements as if they were block scoped (off by default)
    "block-scoped-var": 2,

    // specify the maximum cyclomatic complexity allowed in a program (off by default)
    "complexity": 0,

    // require return statements to either always or never specify values
    "consistent-return": 2,

    // specify curly brace conventions for all control statements
    "curly": [2, "all"],

    // require default case in switch statements (off by default)
    "default-case": 2,

    // encourages use of dot notation whenever possible
    "dot-notation": 2,

    // enforces consistent newlines before or after dots (off by default)
    "dot-location": [2, "property"],

    // require the use of === and !==
    "eqeqeq": 2,

    // make sure for-in loops have an if statement (off by default)
    "guard-for-in": 2,

    // disallow the use of alert, confirm, and prompt
    "no-alert": 2,

    // disallow use of arguments.caller or arguments.callee
    "no-caller": 2,

    // disallow division operators explicitly at beginning of regular expression (off by default)
    "no-div-regex": 2,

    // disallow else after a return in an if (off by default)
    "no-else-return": 2,

    // disallow use of labels for anything other then loops and switches
    "no-empty-label": 2,

    // disallow comparisons to null without a type-checking operator (off by default)
    "no-eq-null": 2,

    // disallow use of eval()
    "no-eval": 2,

    // disallow adding to native types
    "no-extend-native": 2,

    // disallow unnecessary function binding
    "no-extra-bind": 2,

    // disallow fallthrough of case statements
    "no-fallthrough": 2,

    // disallow the use of leading or trailing decimal points in numeric literals (off by default)
    "no-floating-decimal": 2,

    // disallow use of eval()-like methods
    "no-implied-eval": 2,

    // disallow usage of __iterator__ property
    "no-iterator": 2,

    // disallow use of labeled statements
    "no-labels": 2,

    // disallow unnecessary nested blocks
    "no-lone-blocks": 2,

    // disallow creation of functions within loops
    "no-loop-func": 2,

    // disallow use of multiple spaces
    "no-multi-spaces": 2,

    // disallow use of multiline strings
    "no-multi-str": 2,

    // disallow reassignments of native objects
    "no-native-reassign": 2,

    // disallow use of new operator when not part of the assignment or comparison
    "no-new": 2,

    // disallow use of new operator for Function object
    "no-new-func": 2,

    // disallows creating new instances of String, Number and Boolean
    "no-new-wrappers": 2,

    // disallow use of octal literals
    "no-octal": 2,

    // disallow use of octal escape sequences in string literals, such as var foo = "Copyright \251";
    "no-octal-escape": 2,

    // disallow reassignment of function parameters (off by default)
    "no-param-reassign": 2,

    // disallow use of process.env (off by default)
    "no-process-env": 0,

    // disallow usage of __proto__ property
    "no-proto": 2,

    // disallow declaring the same variable more then once
    "no-redeclare": 2,

    // disallow use of assignment in return statement
    "no-return-assign": [2, "always"],

    // disallow use of javascript: urls.
    "no-script-url": 2,

    // disallow comparisons where both sides are exactly the same (off by default)
    "no-self-compare": 2,

    // disallow use of comma operator
    "no-sequences": 2,

    // restrict what can be thrown as an exception (off by default)
    "no-throw-literal": 2,

    // disallow usage of expressions in statement position
    "no-unused-expressions": 2,

    // disallow usage of configurable warning terms in comments, e.g. TODO or FIXME (off by default)
    "no-warning-comments": 1,

    // disallow use of the with statement
    "no-with": 2,

    // require use of the second argument for parseInt() (off by default)
    "radix": 2,

    // requires to declare all vars on top of their containing scope (off by default)
    "vars-on-top": 0,

    // require immediate function invocation to be wrapped in parentheses (off by default)
    "wrap-iife": 2,

    // require or disallow Yoda conditions
    "yoda": [2, "never"],

    /**
     * Strict Mode
     * These rules relate to using strict mode.
     */

    // controls location of Use Strict Directives
    "strict": [2, "global"],

    /**
     * Variables
     * These rules have to do with variable declarations.
     */

    // disallow the catch clause parameter name being the same as a variable in the outer scope (off by default in the node environment)
    "no-catch-shadow": 0,

    // disallow deletion of variables
    "no-delete-var": 2,

    // disallow labels that share a name with a variable
    "no-label-var": 2,

    // disallow declaration of variables already declared in the outer scope
    "no-shadow": 2,

    // disallow shadowing of names such as arguments
    "no-shadow-restricted-names": 2,

    // disallow use of undeclared variables unless mentioned in a /*global */ block
    "no-undef": 2,

    // disallow use of undefined when initializing variables
    "no-undef-init": 2,

    // disallow use of undefined variable (off by default)
    "no-undefined": 0,

    // disallow declaration of variables that are not used in the code
    "no-unused-vars": [
      2,
      {
        // checks all variables for usage, including those in the global scope
        "vars": "all",
        // do not check arguments
        "args": "none"
      }
    ],

    // disallow use of variables before they are defined
    "no-use-before-define": [2, "nofunc"],

    /**
     * Node.js
     * These rules are specific to JavaScript running on Node.js.
     */

    // enforces error handling in callbacks (off by default) (on by default in the node environment)
    "handle-callback-err": [2, "^(.+_)?err(or)?$"],

    // disallow mixing regular variable and require declarations (off by default) (on by default in the node environment)
    "no-mixed-requires": [2, true],

    // disallow use of new operator with the require function (off by default) (on by default in the node environment)
    "no-new-require": 2,

    // disallow string concatenation with __dirname and __filename (off by default) (on by default in the node environment)
    "no-path-concat": 2,

    // disallow process.exit() (on by default in the node environment)
    "no-process-exit": 2,

    // restrict usage of specified node modules (off by default)
    "no-restricted-modules": [1, "chai", "should", "should-http", "should-promised", "should-sinon", "sinon", "sinon-chai"],

    // disallow use of synchronous methods (off by default)
    "no-sync": 1,

    /**
     * Stylistic Issues
     * These rules are purely matters of style and are quite subjective.
     */

    // enforce spacing inside array brackets (off by default)
    "arrays-bracket-spacing": [2, "never"],

    // this option sets a specific tab width for your code (off by default)
    "indent": [2, 2, { "indentSwitchCase": true }],

    // enforce one true brace style (off by default)
    "brace-style": [2, "stroustrup"],

    // require camel case names
    "camelcase": 0,

    // enforce spacing before and after comma
    "comma-spacing": [
      2,
      {
        "before": false,
        "after": true
      }
    ],

    // enforce one true comma style (off by default)
    "comma-style": [2, "last"],

    // require or disallow padding inside computed properties (off by default)
    "computed-property-spacing": [2, "never"],

    // enforces consistent naming when capturing the current execution context (off by default)
    "consistent-this": [1, "self"],

    // enforce newline at the end of file, with no multiple empty lines
    "eol-last": 2,

    // require function expressions to have a name (off by default)
    "func-names": 0,

    // enforces use of function declarations or expressions (off by default)
    "func-style": [2, "declaration"],

    // enforces spacing between keys and values in object literal properties
    "key-spacing": [
      2,
      {
        "beforeColon": false,
        "afterColon": true
      }
    ],

    // enforces empty lines around comments (off by default)
    "lines-around-comment": 0,

    // disallow mixed "LF" and "CRLF" as linebreaks (off by default)
    "linebreak-style": [2, "unix"],

    // specify the maximum depth callbacks can be nested (off by default)
    "max-nested-callbacks": [1, 4],

    // require a capital letter for constructors
    "new-cap": [
      2,
      {
        // When true, rule checks if all new operators are called only with uppercase-started functions.
        "newIsCap": true,
        // When true, rule checks if all uppercase-started functions are called only with new operator.
        "capIsNew": true,
        // Array of lowercase function names that are permitted to be used with the new operator.
        // "newIsCapExceptions": [],
        // Array of uppercase-starting function names that are permitted to be used without the new operator.
        "capIsNewExceptions": ["Array", "Boolean", "Number", "String", "Symbol"]
      }
    ],

    // disallow the omission of parentheses when invoking a constructor with no arguments
    "new-parens": 2,

    // allow/disallow an empty newline after var statement (off by default)
    "newline-after-var": 0,

    // disallow use of the Array constructor
    "no-array-constructor": 2,

    // disallow use of the continue statement (off by default)
    "no-continue": 0,

    // disallow comments inline after code (off by default)
    "no-inline-comments": 0,

    // disallow if as the only statement in an else block (off by default)
    "no-lonely-if": 2,

    // disallow mixed spaces and tabs for indentation
    "no-mixed-spaces-and-tabs": 2,

    // disallow multiple empty lines (off by default)
    "no-multiple-empty-lines": [2, { "max": 3 }],

    // disallow nested ternary expressions (off by default)
    "no-nested-ternary": 2,

    // disallow use of the Object constructor
    "no-new-object": 2,

    // disallow space between function identifier and application
    "no-spaced-func": 2,

    // disallow the use of ternary operators (off by default)
    "no-ternary": 0,

    // disallow trailing whitespace at the end of lines
    "no-trailing-spaces": 2,

    // disallow dangling underscores in identifiers
    "no-underscore-dangle": 0,

    // disallow the use of Boolean literals in conditional expressions (off by default)
    "no-unneeded-ternary": 2,

    // require or disallow padding inside curly braces (off by default)
    "object-curly-spacing": [2, "always"],

    // allow just one var statement per function (off by default)
    "one-var": 0,

    // require assignment operator shorthand where possible or prohibit it entirely (off by default)
    "operator-assignment": 0,

    // enforce operators to be placed before or after line breaks (off by default)
    "operator-linebreak": [2, "after"],

    // enforce padding within blocks (off by default)
    "padded-blocks": [2, "never"],

    // require quotes around object literal property names (off by default)
    "quote-props": [2, "as-needed"],

    // specify whether double or single quotes should be used
    "quotes": [2, "single", "avoid-escape"],

    // require or disallow use of semicolons instead of ASI
    "semi": [2, "always"],

    // enforce spacing before and after semicolons
    "semi-spacing": [
      2,
      {
        "before": false,
        "after": true
      }
    ],

    // sort variables within the same declaration block (off by default)
    "sort-vars": 0,

    // require a space after certain keywords (off by default)
    "space-after-keywords": [2, "always"],

    // require or disallow space before blocks (off by default)
    "space-before-blocks": [2, "always"],

    // require or disallow space before function opening parenthesis (off by default)
    "space-before-function-paren": [2, "never"],

    // require or disallow spaces inside parentheses (off by default)
    "space-in-parens": [2, "never"],

    // require spaces around operators
    "space-infix-ops": 2,

    // require a space after return, throw, and case
    "space-return-throw-case": 2,

    // Require or disallow spaces before/after unary operators (words on by default, nonwords off by default)
    "space-unary-ops": 2,

    // require or disallow a space immediately following the // or /* in a comment (off by default)
    "spaced-comment": 0,

    // require regex literals to be wrapped in parentheses (off by default)
    "wrap-regex": 1

  }
};
<commit_msg>Fix a spelling error in one of the rules<commit_after>module.exports = {
  "env": {
    "node": true
  },

  "rules": {

    /**
     * Possible Errors
     * The following rules point out areas where you might have made mistakes.
     */

    // disallow or enforce trailing commas
    "comma-dangle": [1, "never"],

    // disallow assignment in conditional expressions
    "no-cond-assign": 2,

    // disallow use of console (off by default in the node environment)
    "no-console": 2,

    // disallow use of constant expressions in conditions
    "no-constant-condition": 1,

    // disallow control characters in regular expressions
    "no-control-regex": 2,

    // disallow use of debugger
    "no-debugger": 2,

    // disallow duplicate arguments in functions
    "no-dupe-args": 2,

    // disallow duplicate keys when creating object literals
    "no-dupe-keys": 2,

    // disallow a duplicate case label.
    "no-duplicate-case": 2,

    // disallow empty statements
    "no-empty": 2,

    // disallow the use of empty character classes in regular expressions
    "no-empty-character-class": 2,

    // disallow assigning to the exception in a catch block
    "no-ex-assign": 2,

    // disallow double-negation boolean casts in a boolean context
    "no-extra-boolean-cast": 2,

    // disallow unnecessary parentheses (off by default)
    "no-extra-parens": 2,

    // disallow unnecessary semicolons
    "no-extra-semi": 2,

    // disallow overwriting functions written as function declarations
    "no-func-assign": 2,

    // disallow function or variable declarations in nested blocks
    "no-inner-declarations": 2,

    // disallow invalid regular expression strings in the RegExp constructor
    "no-invalid-regexp": 2,

    // disallow irregular whitespace outside of strings and comments
    "no-irregular-whitespace": 2,

    // disallow negation of the left operand of an in expression
    "no-negated-in-lhs": 2,

    // disallow the use of object properties of the global object (Math and JSON) as functions
    "no-obj-calls": 2,

    // disallow multiple spaces in a regular expression literal
    "no-regex-spaces": 2,

    // disallow sparse arrays
    "no-sparse-arrays": 2,

    // disallow unreachable statements after a return, throw, continue, or break statement
    "no-unreachable": 2,

    // disallow comparisons with the value NaN
    "use-isnan": 2,

    // Ensure JSDoc comments are valid (off by default)
    "valid-jsdoc": [
      2,
      {
        "prefer": {
          "returns": "return"
        },
        "requireReturn": false,
        "requireParamDescription": false,
        "requireReturnDescription": false
      }
    ],

    // Ensure that the results of typeof are compared against a valid string
    "valid-typeof": 2,

    // Avoid code that looks like two expressions but is actually one (off by default)
    "no-unexpected-multiline": 2,

    /**
     * Best Practices
     * These are rules designed to prevent you from making mistakes.
     * They either prescribe a better way of doing something or help you avoid footguns.
     */

    // enforces getter/setter pairs in objects (off by default)
    "accessor-pairs": 0,

    // treat var statements as if they were block scoped (off by default)
    "block-scoped-var": 2,

    // specify the maximum cyclomatic complexity allowed in a program (off by default)
    "complexity": 0,

    // require return statements to either always or never specify values
    "consistent-return": 2,

    // specify curly brace conventions for all control statements
    "curly": [2, "all"],

    // require default case in switch statements (off by default)
    "default-case": 2,

    // encourages use of dot notation whenever possible
    "dot-notation": 2,

    // enforces consistent newlines before or after dots (off by default)
    "dot-location": [2, "property"],

    // require the use of === and !==
    "eqeqeq": 2,

    // make sure for-in loops have an if statement (off by default)
    "guard-for-in": 2,

    // disallow the use of alert, confirm, and prompt
    "no-alert": 2,

    // disallow use of arguments.caller or arguments.callee
    "no-caller": 2,

    // disallow division operators explicitly at beginning of regular expression (off by default)
    "no-div-regex": 2,

    // disallow else after a return in an if (off by default)
    "no-else-return": 2,

    // disallow use of labels for anything other then loops and switches
    "no-empty-label": 2,

    // disallow comparisons to null without a type-checking operator (off by default)
    "no-eq-null": 2,

    // disallow use of eval()
    "no-eval": 2,

    // disallow adding to native types
    "no-extend-native": 2,

    // disallow unnecessary function binding
    "no-extra-bind": 2,

    // disallow fallthrough of case statements
    "no-fallthrough": 2,

    // disallow the use of leading or trailing decimal points in numeric literals (off by default)
    "no-floating-decimal": 2,

    // disallow use of eval()-like methods
    "no-implied-eval": 2,

    // disallow usage of __iterator__ property
    "no-iterator": 2,

    // disallow use of labeled statements
    "no-labels": 2,

    // disallow unnecessary nested blocks
    "no-lone-blocks": 2,

    // disallow creation of functions within loops
    "no-loop-func": 2,

    // disallow use of multiple spaces
    "no-multi-spaces": 2,

    // disallow use of multiline strings
    "no-multi-str": 2,

    // disallow reassignments of native objects
    "no-native-reassign": 2,

    // disallow use of new operator when not part of the assignment or comparison
    "no-new": 2,

    // disallow use of new operator for Function object
    "no-new-func": 2,

    // disallows creating new instances of String, Number and Boolean
    "no-new-wrappers": 2,

    // disallow use of octal literals
    "no-octal": 2,

    // disallow use of octal escape sequences in string literals, such as var foo = "Copyright \251";
    "no-octal-escape": 2,

    // disallow reassignment of function parameters (off by default)
    "no-param-reassign": 2,

    // disallow use of process.env (off by default)
    "no-process-env": 0,

    // disallow usage of __proto__ property
    "no-proto": 2,

    // disallow declaring the same variable more then once
    "no-redeclare": 2,

    // disallow use of assignment in return statement
    "no-return-assign": [2, "always"],

    // disallow use of javascript: urls.
    "no-script-url": 2,

    // disallow comparisons where both sides are exactly the same (off by default)
    "no-self-compare": 2,

    // disallow use of comma operator
    "no-sequences": 2,

    // restrict what can be thrown as an exception (off by default)
    "no-throw-literal": 2,

    // disallow usage of expressions in statement position
    "no-unused-expressions": 2,

    // disallow usage of configurable warning terms in comments, e.g. TODO or FIXME (off by default)
    "no-warning-comments": 1,

    // disallow use of the with statement
    "no-with": 2,

    // require use of the second argument for parseInt() (off by default)
    "radix": 2,

    // requires to declare all vars on top of their containing scope (off by default)
    "vars-on-top": 0,

    // require immediate function invocation to be wrapped in parentheses (off by default)
    "wrap-iife": 2,

    // require or disallow Yoda conditions
    "yoda": [2, "never"],

    /**
     * Strict Mode
     * These rules relate to using strict mode.
     */

    // controls location of Use Strict Directives
    "strict": [2, "global"],

    /**
     * Variables
     * These rules have to do with variable declarations.
     */

    // disallow the catch clause parameter name being the same as a variable in the outer scope (off by default in the node environment)
    "no-catch-shadow": 0,

    // disallow deletion of variables
    "no-delete-var": 2,

    // disallow labels that share a name with a variable
    "no-label-var": 2,

    // disallow declaration of variables already declared in the outer scope
    "no-shadow": 2,

    // disallow shadowing of names such as arguments
    "no-shadow-restricted-names": 2,

    // disallow use of undeclared variables unless mentioned in a /*global */ block
    "no-undef": 2,

    // disallow use of undefined when initializing variables
    "no-undef-init": 2,

    // disallow use of undefined variable (off by default)
    "no-undefined": 0,

    // disallow declaration of variables that are not used in the code
    "no-unused-vars": [
      2,
      {
        // checks all variables for usage, including those in the global scope
        "vars": "all",
        // do not check arguments
        "args": "none"
      }
    ],

    // disallow use of variables before they are defined
    "no-use-before-define": [2, "nofunc"],

    /**
     * Node.js
     * These rules are specific to JavaScript running on Node.js.
     */

    // enforces error handling in callbacks (off by default) (on by default in the node environment)
    "handle-callback-err": [2, "^(.+_)?err(or)?$"],

    // disallow mixing regular variable and require declarations (off by default) (on by default in the node environment)
    "no-mixed-requires": [2, true],

    // disallow use of new operator with the require function (off by default) (on by default in the node environment)
    "no-new-require": 2,

    // disallow string concatenation with __dirname and __filename (off by default) (on by default in the node environment)
    "no-path-concat": 2,

    // disallow process.exit() (on by default in the node environment)
    "no-process-exit": 2,

    // restrict usage of specified node modules (off by default)
    "no-restricted-modules": [1, "chai", "should", "should-http", "should-promised", "should-sinon", "sinon", "sinon-chai"],

    // disallow use of synchronous methods (off by default)
    "no-sync": 1,

    /**
     * Stylistic Issues
     * These rules are purely matters of style and are quite subjective.
     */

    // enforce spacing inside array brackets (off by default)
    "array-bracket-spacing": [2, "never"],

    // this option sets a specific tab width for your code (off by default)
    "indent": [2, 2, { "indentSwitchCase": true }],

    // enforce one true brace style (off by default)
    "brace-style": [2, "stroustrup"],

    // require camel case names
    "camelcase": 0,

    // enforce spacing before and after comma
    "comma-spacing": [
      2,
      {
        "before": false,
        "after": true
      }
    ],

    // enforce one true comma style (off by default)
    "comma-style": [2, "last"],

    // require or disallow padding inside computed properties (off by default)
    "computed-property-spacing": [2, "never"],

    // enforces consistent naming when capturing the current execution context (off by default)
    "consistent-this": [1, "self"],

    // enforce newline at the end of file, with no multiple empty lines
    "eol-last": 2,

    // require function expressions to have a name (off by default)
    "func-names": 0,

    // enforces use of function declarations or expressions (off by default)
    "func-style": [2, "declaration"],

    // enforces spacing between keys and values in object literal properties
    "key-spacing": [
      2,
      {
        "beforeColon": false,
        "afterColon": true
      }
    ],

    // enforces empty lines around comments (off by default)
    "lines-around-comment": 0,

    // disallow mixed "LF" and "CRLF" as linebreaks (off by default)
    "linebreak-style": [2, "unix"],

    // specify the maximum depth callbacks can be nested (off by default)
    "max-nested-callbacks": [1, 4],

    // require a capital letter for constructors
    "new-cap": [
      2,
      {
        // When true, rule checks if all new operators are called only with uppercase-started functions.
        "newIsCap": true,
        // When true, rule checks if all uppercase-started functions are called only with new operator.
        "capIsNew": true,
        // Array of lowercase function names that are permitted to be used with the new operator.
        // "newIsCapExceptions": [],
        // Array of uppercase-starting function names that are permitted to be used without the new operator.
        "capIsNewExceptions": ["Array", "Boolean", "Number", "String", "Symbol"]
      }
    ],

    // disallow the omission of parentheses when invoking a constructor with no arguments
    "new-parens": 2,

    // allow/disallow an empty newline after var statement (off by default)
    "newline-after-var": 0,

    // disallow use of the Array constructor
    "no-array-constructor": 2,

    // disallow use of the continue statement (off by default)
    "no-continue": 0,

    // disallow comments inline after code (off by default)
    "no-inline-comments": 0,

    // disallow if as the only statement in an else block (off by default)
    "no-lonely-if": 2,

    // disallow mixed spaces and tabs for indentation
    "no-mixed-spaces-and-tabs": 2,

    // disallow multiple empty lines (off by default)
    "no-multiple-empty-lines": [2, { "max": 3 }],

    // disallow nested ternary expressions (off by default)
    "no-nested-ternary": 2,

    // disallow use of the Object constructor
    "no-new-object": 2,

    // disallow space between function identifier and application
    "no-spaced-func": 2,

    // disallow the use of ternary operators (off by default)
    "no-ternary": 0,

    // disallow trailing whitespace at the end of lines
    "no-trailing-spaces": 2,

    // disallow dangling underscores in identifiers
    "no-underscore-dangle": 0,

    // disallow the use of Boolean literals in conditional expressions (off by default)
    "no-unneeded-ternary": 2,

    // require or disallow padding inside curly braces (off by default)
    "object-curly-spacing": [2, "always"],

    // allow just one var statement per function (off by default)
    "one-var": 0,

    // require assignment operator shorthand where possible or prohibit it entirely (off by default)
    "operator-assignment": 0,

    // enforce operators to be placed before or after line breaks (off by default)
    "operator-linebreak": [2, "after"],

    // enforce padding within blocks (off by default)
    "padded-blocks": [2, "never"],

    // require quotes around object literal property names (off by default)
    "quote-props": [2, "as-needed"],

    // specify whether double or single quotes should be used
    "quotes": [2, "single", "avoid-escape"],

    // require or disallow use of semicolons instead of ASI
    "semi": [2, "always"],

    // enforce spacing before and after semicolons
    "semi-spacing": [
      2,
      {
        "before": false,
        "after": true
      }
    ],

    // sort variables within the same declaration block (off by default)
    "sort-vars": 0,

    // require a space after certain keywords (off by default)
    "space-after-keywords": [2, "always"],

    // require or disallow space before blocks (off by default)
    "space-before-blocks": [2, "always"],

    // require or disallow space before function opening parenthesis (off by default)
    "space-before-function-paren": [2, "never"],

    // require or disallow spaces inside parentheses (off by default)
    "space-in-parens": [2, "never"],

    // require spaces around operators
    "space-infix-ops": 2,

    // require a space after return, throw, and case
    "space-return-throw-case": 2,

    // Require or disallow spaces before/after unary operators (words on by default, nonwords off by default)
    "space-unary-ops": 2,

    // require or disallow a space immediately following the // or /* in a comment (off by default)
    "spaced-comment": 0,

    // require regex literals to be wrapped in parentheses (off by default)
    "wrap-regex": 1

  }
};
<|endoftext|>


<commit_before>let stage;
let playerScore;
let hitPadUp, hitPadDown, hitPadLeft, hitPadRight;
let circleUp, circleDown, circleLeft, circleRight;
let circleRadius = 50, hitPadRadius = 60;
let heldKeys = {};
let center = { 'x' : 500, 'y' : 300};
let interval = 1000;
let list = [];
let index = 0;

function init() {
	stage = new createjs.Stage("demoCanvas");

	playerScore = new createjs.Text('0', 'bold 20px Arial', '#A3FF24');
	playerScore.x = 211;
	playerScore.y = 20;
	stage.addChild(playerScore);

	viewSetting();

	// for (var i = 0; i < 10; i++){
	// 	list.push();
	// }

	stage.addChild(circleUp);
	stage.addChild(circleDown);
	stage.addChild(circleLeft);
	stage.addChild(circleRight);

	createjs.Tween.get(circleUp, {loop: true})
	  .to({y: -100}, interval);
	createjs.Tween.get(circleDown, {loop: true})
	  .to({y: 700}, interval);
	createjs.Tween.get(circleLeft, {loop: true})
	  .to({x: -100}, interval);
	createjs.Tween.get(circleRight, {loop: true})
	  .to({x: 1100}, interval);
	createjs.Ticker.setFPS(60);
	createjs.Ticker.addEventListener("tick", stage);

};

// Function
function getCircle(mode) {
	let tmp = new createjs.Shape();
	switch (mode) {
		case "up":
			tmp.graphics.beginFill("Crimson").drawCircle(0, 0, 50);
			break;
		case "down":
			tmp.graphics.beginFill("Yellow").drawCircle(0, 0, 50);
			break;
		case "left":
			tmp.graphics.beginFill("Green").drawCircle(0, 0, 50);
			break;
		case "right":
			tmp.graphics.beginFill("Blue").drawCircle(0, 0, 50);
			break;
	}
	tmp.x = center.x;
	tmp.y = center.y;
	return tmp;
}

function viewSetting() {
	hitPadUp = new createjs.Shape();
	hitPadUp.graphics.beginFill("Pink").drawCircle(0, 0, 60);
	hitPadUp.x = 500;
	hitPadUp.y = 60;
	hitPadUp.alpha = 0.5;
	stage.addChild(hitPadUp);

	hitPadDown = new createjs.Shape();
	hitPadDown.graphics.beginFill("Pink").drawCircle(0, 0, 60);
	hitPadDown.x = 500;
	hitPadDown.y = 540;
	hitPadDown.alpha = 0.5;
	stage.addChild(hitPadDown);

	hitPadLeft = new createjs.Shape();
	hitPadLeft.graphics.beginFill("Pink").drawCircle(0, 0, 60);
	hitPadLeft.x = 60;
	hitPadLeft.y = 300;
	hitPadLeft.alpha = 0.5;
	stage.addChild(hitPadLeft);

	hitPadRight = new createjs.Shape();
	hitPadRight.graphics.beginFill("Pink").drawCircle(0, 0, 60);
	hitPadRight.x = 940;
	hitPadRight.y = 300;
	hitPadRight.alpha = 0.5;
	stage.addChild(hitPadRight);
}

// Key Setting
document.onkeydown = function(e) {
	console.log(heldKeys[e.keyCode]);
	if (heldKeys[e.keyCode] == true) {
		return;
	}
	heldKeys[e.keyCode] = true;
	switch(e.keyCode) {
		case 37:
			console.log("left");
			if(circleLeft.x+circleRadius>=hitPadLeft.x-hitPadRadius && circleLeft.x-circleRadius<=hitPadLeft.x+hitPadRadius) {
				playerScore.text = parseInt(playerScore.text + 1);
				stage.removeChild(circleLeft);
				circleLeft = null;
			}
			break;
		case 38:
			console.log("up");
			if(circleUp.y+circleRadius>=hitPadUp.y-hitPadRadius && circleUp.y-circleRadius<=hitPadUp.y+hitPadRadius) {
				playerScore.text = parseInt(playerScore.text + 1);
				stage.removeChild(circleUp);
				circleUp = null;
			}
			break;
		case 39:
			console.log("right");
			if(circleRight.x+circleRadius>=hitPadRight.x-hitPadRadius && circleRight.x-circleRadius<=hitPadRight.x+hitPadRadius) {
				playerScore.text = parseInt(playerScore.text + 1);
				stage.removeChild(circleRight);
				circleRight = null;
			}
			break;
		case 40:
			console.log("down");
			if(circleDown.y+circleRadius>=hitPadDown.y-hitPadRadius && circleDown.x-circleRadius<=hitPadDown.x+hitPadRadius) {
				playerScore.text = parseInt(playerScore.text + 1);
				stage.removeChild(circleDown);
				circleDown = null;
			}
	}
};

document.onkeyup = function(e) {
	console.log(heldKeys[e.keyCode]);
	delete heldKeys[e.keyCode];
};
<commit_msg>add combo effect<commit_after>let stage;
let playerScore, perfectCombo, goodCombo;
let hitPadUp, hitPadDown, hitPadLeft, hitPadRight;
let circleUp, circleDown, circleLeft, circleRight;
let circleRadius = 50, hitPadRadius = 60;
let heldKeys = {};
let center = { 'x' : 500, 'y' : 300};
let interval = 1000;
let list = [];
let index = 0;

function init() {
	stage = new createjs.Stage("demoCanvas");

	playerScore = new createjs.Text('0', 'bold 20px Arial', '#A3FF24');
	playerScore.x = 211;
	playerScore.y = 20;
	stage.addChild(playerScore);

	perfectCombo = new createjs.Text('Perfect', 'bold 50px Arial', '#A3FF24');
	perfectCombo.x = 400;
	perfectCombo.y = 200;

	goodCombo = new createjs.Text('Good', 'bold 50px Arial', '#A3FF24');
	goodCombo.x = 400;
	goodCombo.y = 200;

	viewSetting();

	circleUp = getCircle("up");
	circleDown = getCircle("down");
	circleLeft = getCircle("left");
	circleRight = getCircle("right");
	stage.addChild(circleUp);
	stage.addChild(circleDown);
	stage.addChild(circleLeft);
	stage.addChild(circleRight);

	createjs.Tween.get(circleUp, {loop: true})
	  .to({y: -100}, interval);
	createjs.Tween.get(circleDown, {loop: true})
	  .to({y: 700}, interval);
	createjs.Tween.get(circleLeft, {loop: true})
	  .to({x: -100}, interval);
	createjs.Tween.get(circleRight, {loop: true})
	  .to({x: 1100}, interval);
	createjs.Ticker.setFPS(60);
	createjs.Ticker.addEventListener("tick", stage);

};

// Function
function getCircle(mode) {
	let tmp = new createjs.Shape();
	switch (mode) {
		case "up":
			tmp.graphics.beginFill("Crimson").drawCircle(0, 0, 50);
			break;
		case "down":
			tmp.graphics.beginFill("Yellow").drawCircle(0, 0, 50);
			break;
		case "left":
			tmp.graphics.beginFill("Green").drawCircle(0, 0, 50);
			break;
		case "right":
			tmp.graphics.beginFill("Blue").drawCircle(0, 0, 50);
			break;
	}
	tmp.x = center.x;
	tmp.y = center.y;
	return tmp;
}

function viewSetting() {
	hitPadUp = new createjs.Shape();
	hitPadUp.graphics.beginFill("Pink").drawCircle(0, 0, 60);
	hitPadUp.x = 500;
	hitPadUp.y = 70;
	hitPadUp.shadow = new createjs.Shadow("#f44295", 0, 5, 10);
	stage.addChild(hitPadUp);

	hitPadDown = new createjs.Shape();
	hitPadDown.graphics.beginFill("Pink").drawCircle(0, 0, 60);
	hitPadDown.x = 500;
	hitPadDown.y = 530;
	hitPadDown.shadow = new createjs.Shadow("#f44295", 0, 5, 10);
	stage.addChild(hitPadDown);

	hitPadLeft = new createjs.Shape();
	hitPadLeft.graphics.beginFill("Pink").drawCircle(0, 0, 60);
	hitPadLeft.x = 70;
	hitPadLeft.y = 300;
	hitPadLeft.shadow = new createjs.Shadow("#f44295", 0, 5, 10);
	stage.addChild(hitPadLeft);

	hitPadRight = new createjs.Shape();
	hitPadRight.graphics.beginFill("Pink").drawCircle(0, 0, 60);
	hitPadRight.x = 930;
	hitPadRight.y = 300;
	hitPadRight.shadow = new createjs.Shadow("#f44295", 0, 5, 10);
	stage.addChild(hitPadRight);
}
function removePerfectCombo() {
	stage.removeChild(perfectCombo);
}
function removeGoodCombo() {
	stage.removeChild(goodCombo);
}
function comboEffect(circle, hitPad, coord) {
	var perfect = 20;
	var good = 40;
	if(coord=="x") {
		if(circle.x<=hitPad.x+perfect && circle.x>=hitPad.x-perfect) {
			console.log("perfect");
			stage.addChild(perfectCombo);
			createjs.Tween.get(perfectCombo).wait(500).call( removePerfectCombo );
			playerScore.text = parseInt(playerScore.text + 1);
			return true;
		}
		else if(circle.x<=hitPad.x+good && circle.x>=hitPad.x-good) {
			console.log("good");
			stage.addChild(goodCombo);
			createjs.Tween.get(goodCombo).wait(500).call( removeGoodCombo );
			playerScore.text = parseInt(playerScore.text + 1);
			return true;
		}
		else if(circle.x+circleRadius>=hitPad.x-hitPadRadius && circle.x-circleRadius<=hitPad.x+hitPadRadius) {	//normal
			playerScore.text = parseInt(playerScore.text + 1);
			return true;
		}
	}
	else if(coord=="y") {
		if(circle.y<=hitPad.y+perfect && circle.y>=hitPad.y-perfect) {
			console.log("perfect");
			stage.addChild(perfectCombo);
			createjs.Tween.get(perfectCombo).wait(500).call( removePerfectCombo );
			playerScore.text = parseInt(playerScore.text + 1);
			return true;
		}
		else if(circle.y<=hitPad.y+good && circle.y>=hitPad.y-good) {
			console.log("good");
			stage.addChild(goodCombo);
			createjs.Tween.get(goodCombo).wait(500).call( removeGoodCombo );
			playerScore.text = parseInt(playerScore.text + 1);
			return true;
		}
		else if(circle.y+circleRadius>=hitPad.y-hitPadRadius && circle.y-circleRadius<=hitPad.y+hitPadRadius) {	//normal
			playerScore.text = parseInt(playerScore.text + 1);
			return true;
		}
	}
	return false;
}

// Key Setting
document.onkeydown = function(e) {
	//console.log(heldKeys[e.keyCode]);
	if (heldKeys[e.keyCode] == true) {
		return;
	}
	heldKeys[e.keyCode] = true;
	switch(e.keyCode) {
		case 37:
			console.log("left");
			hitPadLeft.shadow = null;
			comboEffect(circleLeft, hitPadLeft, "x")
			/*if( comboEffect(circleLeft, hitPadLeft, "x") ) {
				stage.removeChild(circleLeft);
				circleLeft = null;
			}*/
			break;
		case 38:
			console.log("up");
			hitPadUp.shadow = null;
			comboEffect(circleUp, hitPadUp, "y");
			/*if( comboEffect(circleUp, hitPadUp, "y") ) {
				stage.removeChild(circleUp);
				circleUp = null;
			}*/
			break;
		case 39:
			console.log("right");
			hitPadRight.shadow = null;
			comboEffect(circleRight, hitPadRight, "x");
			/*if( comboEffect(circleRight, hitPadRight, "x") ) {
				stage.removeChild(circleRight);
				circleRight = null;
			}*/
			break;
		case 40:
			console.log("down");
			hitPadDown.shadow = null;
			comboEffect(circleDown, hitPadDown, "y");
			/*if( comboEffect(circleDown, hitPadDown, "y") ) {
				stage.removeChild(circleDown);
				circleDown = null;
			}*/
			break;
	}
};

document.onkeyup = function(e) {
	//console.log(heldKeys[e.keyCode]);
	delete heldKeys[e.keyCode];
	switch(e.keyCode) {
		case 37:
			hitPadLeft.shadow = new createjs.Shadow("#f44295", 0, 5, 10);
			break;
		case 38:
			hitPadUp.shadow = new createjs.Shadow("#f44295", 0, 5, 10);
			break;
		case 39:
			hitPadRight.shadow = new createjs.Shadow("#f44295", 0, 5, 10);
			break;
		case 40:
			hitPadDown.shadow = new createjs.Shadow("#f44295", 0, 5, 10);
	}
};
<|endoftext|>


<commit_before>'use strict'

const path = require('path')

module.exports = function cmdname() {
  const splits = process.execPath.split(path.sep)
  return splits[splits.length - 1]
}
<commit_msg>index: use path.basename<commit_after>'use strict'

const path = require('path')

module.exports = function cmdname() {
  return path.basename(process.execPath)
}
<|endoftext|>


<commit_before>/*
   ___      ___    _____   ___ _  _
  / __|__ _| _ \__|_   _| |_ _| \| |__ _
 | (__/ _` |  _(_-< | || '_| || .` / _` |
  \___\__,_|_| /__/ |_||_||___|_|\_\__, |
                                   |___/
*/

//*******************************************************************

'use strict';

//*******************************************************************

var cap = function(str,c) {

    var nstr = '';

	if (c === 'same') {
		return str;
	}
    else if (c === 'none') {
		return '';
	}
    else if (c === 'proper') {
		return str;
	}
    else if (c === 'title') {
		return str.replace(/\w([^-\s]*)/g, function(txt){
            return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
        });
	}
    else if (c === 'sentence') {
		return str.charAt(0).toUpperCase() + str.substr(1).toLowerCase();
	}
	else if (c === 'upper') {
		return str.toUpperCase();
	}
	else if (c === 'lower') {
		return str.toLowerCase();
	}
    else if (c === 'camel') {
		return str.charAt(0).toLowerCase() + cap(str, 'pascal').substr(1);
	}
    else if (c === 'pascal') {
        return cap(str, 'title').replace(/ /g, '');
	}
    else if (c === 'snake') {
		return str.replace(/ /g, '_');
	}
    else if (c === 'python') {
		return str.toUpperCase().replace(/ /g, '_');
	}
    else if (c === 'leet') {
		return str.toLowerCase().replace(/i/g, '1').replace(/e/g, '3').replace(/o/g, '0').replace(/l/g, '£').replace(/f/g, 'ƒ').replace(/s/g, '$').replace(/n/g, 'И');
	}
    else if (c === 'reverse') {
	   return str.split("").reverse().join("");
    }
    else if (c === 'crazy') {
        for (var i = 0; i < str.length; i++){
            if (i % 2 === 0) {
                nstr += str.charAt(i).toLowerCase();
            }
            else {
                nstr += str.charAt(i).toUpperCase();
            }
        }
        return nstr;
	}
    else if (c === 'random') {
        for (var j = 0; j < str.length; j++){
            var rnd = Math.random();

            if (rnd > 0.5) {
                nstr += str.charAt(j).toLowerCase();
            }
            else {
                nstr += str.charAt(j).toUpperCase();
            }
        }
        return nstr;
	}
	else{
		return str;
	}
};

//*******************************************************************

var string = function(s, opt) {

	if (!s) {
		console.error('s isNaN : ' + s);
		return false;
	}
	else if (typeof s !== 'string') {
		console.error('s typeof : ' + s);
		return false;
	}
	else {

		if (opt) {
            s = cap(s, opt);
		}
        else {
            s = cap(s, 'same');
        }

		return s;
	}
};

//*******************************************************************

module.exports = string;
<commit_msg>cleanup, remove console error<commit_after>/*
   ___      ___    _____   ___ _  _
  / __|__ _| _ \__|_   _| |_ _| \| |__ _
 | (__/ _` |  _(_-< | || '_| || .` / _` |
  \___\__,_|_| /__/ |_||_||___|_|\_\__, |
                                   |___/
*/

//*******************************************************************

'use strict';

//*******************************************************************

var cap = function(str,c) {

    var nstr = '';

	if (c === 'same') {
		return str;
	}
    else if (c === 'none') {
		return '';
	}
    else if (c === 'proper') {
		return str;
	}
    else if (c === 'title') {
		return str.replace(/\w([^-\s]*)/g, function(txt){
            return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
        });
	}
    else if (c === 'sentence') {
		return str.charAt(0).toUpperCase() + str.substr(1).toLowerCase();
	}
	else if (c === 'upper') {
		return str.toUpperCase();
	}
	else if (c === 'lower') {
		return str.toLowerCase();
	}
    else if (c === 'camel') {
		return str.charAt(0).toLowerCase() + cap(str, 'pascal').substr(1);
	}
    else if (c === 'pascal') {
        return cap(str, 'title').replace(/ /g, '');
	}
    else if (c === 'snake') {
		return str.replace(/ /g, '_');
	}
    else if (c === 'python') {
		return str.toUpperCase().replace(/ /g, '_');
	}
    else if (c === 'leet') {
		return str.toLowerCase().replace(/i/g, '1').replace(/e/g, '3').replace(/o/g, '0').replace(/l/g, '£').replace(/f/g, 'ƒ').replace(/s/g, '$').replace(/n/g, 'И');
	}
    else if (c === 'reverse') {
        return str.split('').reverse().join('');
    }
    else if (c === 'crazy') {
        for (var i = 0; i < str.length; i++){
            if (i % 2 === 0) {
                nstr += str.charAt(i).toLowerCase();
            }
            else {
                nstr += str.charAt(i).toUpperCase();
            }
        }
        return nstr;
	}
    else if (c === 'random') {
        for (var j = 0; j < str.length; j++){
            var rnd = Math.random();

            if (rnd > 0.5) {
                nstr += str.charAt(j).toLowerCase();
            }
            else {
                nstr += str.charAt(j).toUpperCase();
            }
        }
        return nstr;
	}
	else{
		return str;
	}
};

//*******************************************************************

var string = function(s, opt) {

	if (!s) {
		console.log('s false : ' + s);
		return false;
	}
	else if (typeof s !== 'string') {
		console.log('s typeof : ' + s);
		return false;
	}
	else {

		if (opt) {
            s = cap(s, opt);
		}
        else {
            s = cap(s, 'same');
        }

		return s;
	}
};

//*******************************************************************

module.exports = string;
<|endoftext|>


<commit_before>const Discord = require("discord.js");
const fs = require("fs");
const date = require("date");
const bot = new Discord.Client();
const prefix = "!";
const botToken = require("./bottoken");

bot.on("ready", () => {
    console.log("Klar");
    bot.user.setGame("Skriv !help för hjälp.");
});

var borde = [
    "Ja",
    "Nej"
];

var ryss = [
    "Du klarade dig",
    "Du klarade dig",
    "Du klarade dig",
    "Du klarade dig",
    "Du klarade dig",
    "Du dog"
];

var dabRespond = [
    "Du kan inte tvinga mig",
    "Du kan inte tvinga mig",
    "Du kan inte tvinga mig",
    "Du kan inte tvinga mig",
    "Du kan inte tvinga mig",
    "Du kan inte tvinga mig",
    "Vad är det du inte förstår?",
    "Jävla människor ska alltid komma och tjata",
    "Okej då, ***DAB***"
];

Date.prototype.getWeek = function() {
    var onejan = new Date(this.getFullYear(), 0, 1);
    return Math.ceil((((this - onejan) / 86400000) + onejan.getDay() + 1) / 7);
}

var weekNumber = (new Date()).getWeek();
var widthSchema = "600"
var heightSchema = "600"
var schemaLink = "http://www.novasoftware.se/ImgGen/schedulegenerator.aspx?format=png&schoolid=80220/sv-se&type=1&id={EA17E85E-CBFC-4836-935C-04780337F6D5}&period=&week="+weekNumber+"&mode=0&printer=0&colors=32&head=0&clock=0&foot=0&day=0&width="+widthSchema+"&height="+heightSchema+"&maxwidth=1883&maxheight=847"

bot.on("message", (message) => {
    if (!message.content.startsWith(prefix)) return;
    if (message.author.bot) return;

    //console.log(test);

    var split = message.content.substring(prefix.length).split(' ');

    switch (split[0].toLowerCase()) {
        case "h":
        case "help":
            message.channel.send({
                embed: new Discord.RichEmbed()
                    .setAuthor("Kommandon:", bot.user.avatarURL)
                    .addField("Allmäna kommandon:", "!help - visar denna meny\n!dab - sprid cancer\n!poll <fråga> - Starta en ja eller nej fråga\n!pinpoll - samma som !poll fast den pinnar också\n!borde - låt boten svara på livets svåra frågor")
                    .addField("Skolrelaterade kommandon:", "!schema - visar veckans schema\n!schemavecka <vecka> - visar schemat från en viss vecka\n!vecka - visar veckan")
                    .addField("Discord kommandon:", "!hex - ger dig en slumpmässig färg\n!hexdisplay <hex> - visar fägen som det inskrivna hex nummret ger\n!github - skickar länken till botens github repo\n!ping - visar botens internal ping (för felsökning)\n!getid - Visar ditt user id")
                    .setColor("0x111111")
            });
            break;
        case "vecka":
            message.channel.send(weekNumber);
            break;
        case "s":
        case "schema":
            message.channel.send({
                embed: new Discord.RichEmbed()
                    .setAuthor("Schema v."+weekNumber+":")
                    .setImage(schemaLink)
                    .setColor("0x"+("000000"+Math.random().toString(16).slice(2, 8).toUpperCase()).slice(-6))
            });
            break;
        //case "sv":
        case "schemavecka":
            /*if (message.content = "!schemavecka") {
                var valfriVecka = message.content.substring(13);
            }
            else {
                var valfriVecka = message.content.substring(4);
                console.log(valfriVecka);
            }*/
            var valfriVecka = message.content.substring(13)
            message.channel.send({
                embed: new Discord.RichEmbed()
                    .setAuthor("Schema v."+valfriVecka+":")
                    .setImage("http://www.novasoftware.se/ImgGen/schedulegenerator.aspx?format=png&schoolid=80220/sv-se&type=1&id={EA17E85E-CBFC-4836-935C-04780337F6D5}&period=&week="+valfriVecka+"&mode=0&printer=0&colors=32&head=0&clock=0&foot=0&day=0&width="+widthSchema+"&height="+heightSchema+"&maxwidth=1883&maxheight=847")
                    .setColor("0x"+("000000"+Math.random().toString(16).slice(2, 8).toUpperCase()).slice(-6))
            });
            break;
        case "github":
            message.author.send("https://github.com/ChilladeChillin/ITGDiscordBot");
            break;
        case "dab":
            message.channel.send(dabRespond[Math.floor(Math.random() * dabRespond.length)]);
            break;
        case "säg":
        case "say":
            var textFromSender = message.content;
            message.delete(0);
            if (message.author.id==="164283691802165250") {
                message.channel.send(message.content.substring(5));
                break;
            }
            else {
                message.author.send("Du har inte tillåtelse att använda detta kommando");
                break;
            }
        case "ping":
            message.channel.send(bot.ping+" ms");
            break;
        case "hex":
            var randomhex = ("000000"+Math.random().toString(16).slice(2, 8).toUpperCase()).slice(-6);
            message.channel.send({
                embed: new Discord.RichEmbed()
                    .setAuthor("Hex:")
                    .setDescription("#"+randomhex)
                    .setColor("0x"+randomhex)
            });
            break;
        case "poll":
            var question = message.content.substring(6)
            message.delete(0);
            message.channel.send(question+"\n\n`👍=JA 👎=NEJ`")
                .then(function (message) {
                    message.react("👍")
                    message.react("👎")
                }).catch(function() {
                    console.log("Reaktionen gick inte hela vägen fram")
                   });
            break;
        case "pinpoll":
            var question = message.content.substring(9)
            message.delete(0);
            if (message.author.id==="164283691802165250" || "349987894171271178") {
                message.channel.send(question+"\n\n`👍=JA 👎=NEJ`")
                .then(function (message) {
                    message.react("👍")
                    message.pin()
                    //delay(10)
                    message.react("👎")
                }).catch(function() {
                    console.log("Reaktionen gick inte hela vägen fram (pinpoll)")
                    });
            }
            else {
                message.author.send("Du har inte tillåtelse att använda detta kommando");
            }
            break;
        case "hd":
        case "hexdisplay":
            var hexMessage = message.content.substring(12)
            if (hexMessage.substr(0, 1) === "#") {
                var hexMessageFix = hexMessage.substing(1)
            }
            else {
                var hexMessageFix = hexMessage
            }
            message.channel.send({
                embed: new Discord.RichEmbed()
                    .setAuthor("Hex:")
                    .setDescription("#"+hexMessageFix)
                    .setColor("0x"+hexMessageFix)
            });
            break;
        case "getid":
            message.channel.send(message.author.id);
            break;
        case "kommer":
        case "är":
        case "borde":
            message.channel.send(borde[Math.floor(Math.random()*borde.length)]+" "+message.author.toString());
            break;
        case "ryss":
            message.channel.send(ryss[Math.floor(Math.random()*ryss.length)]+" "+message.author.toString());
            break;
        case "wikipedia":
            var wikiSearch = message.content.substring(11)
            message.channel.send("https://en.wikipedia.org/wiki/"+wikiSearch);
            break;
        default:
            message.channel.send("```Detta kommando existerar inte (än)\nSkriv !help för att se de kommandon som faktiskt existerar```");
    }
});

bot.login(botToken);<commit_msg>Fixade till !help<commit_after>const Discord = require("discord.js");
const fs = require("fs");
const date = require("date");
const bot = new Discord.Client();
const prefix = "!";
const botToken = require("./bottoken");

bot.on("ready", () => {
    console.log("Klar");
    bot.user.setGame("Skriv !help för hjälp.");
});

var borde = [
    "Ja",
    "Nej"
];

var ryss = [
    "Du klarade dig",
    "Du klarade dig",
    "Du klarade dig",
    "Du klarade dig",
    "Du klarade dig",
    "Du dog"
];

var dabRespond = [
    "Du kan inte tvinga mig",
    "Du kan inte tvinga mig",
    "Du kan inte tvinga mig",
    "Du kan inte tvinga mig",
    "Du kan inte tvinga mig",
    "Du kan inte tvinga mig",
    "Vad är det du inte förstår?",
    "Jävla människor ska alltid komma och tjata",
    "Okej då, ***DAB***"
];

Date.prototype.getWeek = function() {
    var onejan = new Date(this.getFullYear(), 0, 1);
    return Math.ceil((((this - onejan) / 86400000) + onejan.getDay() + 1) / 7);
}

var weekNumber = (new Date()).getWeek();
var widthSchema = "600"
var heightSchema = "600"
var schemaLink = "http://www.novasoftware.se/ImgGen/schedulegenerator.aspx?format=png&schoolid=80220/sv-se&type=1&id={EA17E85E-CBFC-4836-935C-04780337F6D5}&period=&week="+weekNumber+"&mode=0&printer=0&colors=32&head=0&clock=0&foot=0&day=0&width="+widthSchema+"&height="+heightSchema+"&maxwidth=1883&maxheight=847"

bot.on("message", (message) => {
    if (!message.content.startsWith(prefix)) return;
    if (message.author.bot) return;

    //console.log(test);

    var split = message.content.substring(prefix.length).split(' ');

    switch (split[0].toLowerCase()) {
        case "h":
        case "help":
            message.channel.send({
                embed: new Discord.RichEmbed()
                    .setAuthor("Kommandon:", bot.user.avatarURL)
                    .addField("Allmäna kommandon:", "!help - visar denna meny\n!dab - sprid cancer\n!poll <fråga> - Starta en ja eller nej fråga\n!pinpoll - samma som !poll fast den pinnar också\n!borde - låt boten svara på livets svåra frågor\n!ryss - 1/6 risk att du dör")
                    .addField("Skolrelaterade kommandon:", "!schema - visar veckans schema\n!schemavecka <vecka> - visar schemat från en viss vecka\n!vecka - visar veckan\n!wikipedia <sida> - låter dig gå till en viss wikipedia hemsida")
                    .addField("Discord kommandon:", "!hex - ger dig en slumpmässig färg\n!hexdisplay <hex> - visar fägen som det inskrivna hex nummret ger\n!github - skickar länken till botens github repo\n!ping - visar botens internal ping (för felsökning)\n!getid - Visar ditt user id")
                    .setColor("0x111111")
            });
            break;
        case "vecka":
            message.channel.send(weekNumber);
            break;
        case "s":
        case "schema":
            message.channel.send({
                embed: new Discord.RichEmbed()
                    .setAuthor("Schema v."+weekNumber+":")
                    .setImage(schemaLink)
                    .setColor("0x"+("000000"+Math.random().toString(16).slice(2, 8).toUpperCase()).slice(-6))
            });
            break;
        //case "sv":
        case "schemavecka":
            /*if (message.content = "!schemavecka") {
                var valfriVecka = message.content.substring(13);
            }
            else {
                var valfriVecka = message.content.substring(4);
                console.log(valfriVecka);
            }*/
            var valfriVecka = message.content.substring(13)
            message.channel.send({
                embed: new Discord.RichEmbed()
                    .setAuthor("Schema v."+valfriVecka+":")
                    .setImage("http://www.novasoftware.se/ImgGen/schedulegenerator.aspx?format=png&schoolid=80220/sv-se&type=1&id={EA17E85E-CBFC-4836-935C-04780337F6D5}&period=&week="+valfriVecka+"&mode=0&printer=0&colors=32&head=0&clock=0&foot=0&day=0&width="+widthSchema+"&height="+heightSchema+"&maxwidth=1883&maxheight=847")
                    .setColor("0x"+("000000"+Math.random().toString(16).slice(2, 8).toUpperCase()).slice(-6))
            });
            break;
        case "github":
            message.author.send("https://github.com/ChilladeChillin/ITGDiscordBot");
            break;
        case "dab":
            message.channel.send(dabRespond[Math.floor(Math.random() * dabRespond.length)]);
            break;
        case "säg":
        case "say":
            var textFromSender = message.content;
            message.delete(0);
            if (message.author.id==="164283691802165250") {
                message.channel.send(message.content.substring(5));
                break;
            }
            else {
                message.author.send("Du har inte tillåtelse att använda detta kommando");
                break;
            }
        case "ping":
            message.channel.send(bot.ping+" ms");
            break;
        case "hex":
            var randomhex = ("000000"+Math.random().toString(16).slice(2, 8).toUpperCase()).slice(-6);
            message.channel.send({
                embed: new Discord.RichEmbed()
                    .setAuthor("Hex:")
                    .setDescription("#"+randomhex)
                    .setColor("0x"+randomhex)
            });
            break;
        case "poll":
            var question = message.content.substring(6)
            message.delete(0);
            message.channel.send(question+"\n\n`👍=JA 👎=NEJ`")
                .then(function (message) {
                    message.react("👍")
                    message.react("👎")
                }).catch(function() {
                    console.log("Reaktionen gick inte hela vägen fram")
                   });
            break;
        case "pinpoll":
            var question = message.content.substring(9)
            message.delete(0);
            if (message.author.id==="164283691802165250" || "349987894171271178") {
                message.channel.send(question+"\n\n`👍=JA 👎=NEJ`")
                .then(function (message) {
                    message.react("👍")
                    message.pin()
                    //delay(10)
                    message.react("👎")
                }).catch(function() {
                    console.log("Reaktionen gick inte hela vägen fram (pinpoll)")
                    });
            }
            else {
                message.author.send("Du har inte tillåtelse att använda detta kommando");
            }
            break;
        case "hd":
        case "hexdisplay":
            var hexMessage = message.content.substring(12)
            if (hexMessage.substr(0, 1) === "#") {
                var hexMessageFix = hexMessage.substing(1)
            }
            else {
                var hexMessageFix = hexMessage
            }
            message.channel.send({
                embed: new Discord.RichEmbed()
                    .setAuthor("Hex:")
                    .setDescription("#"+hexMessageFix)
                    .setColor("0x"+hexMessageFix)
            });
            break;
        case "getid":
            message.channel.send(message.author.id);
            break;
        case "kommer":
        case "är":
        case "borde":
            message.channel.send(borde[Math.floor(Math.random()*borde.length)]+" "+message.author.toString());
            break;
        case "ryss":
            message.channel.send(ryss[Math.floor(Math.random()*ryss.length)]+" "+message.author.toString());
            break;
        case "wikipedia":
            var wikiSearch = message.content.substring(11)
            message.channel.send("https://en.wikipedia.org/wiki/"+wikiSearch);
            break;
        default:
            message.channel.send("```Detta kommando existerar inte (än)\nSkriv !help för att se de kommandon som faktiskt existerar```");
    }
});

bot.login(botToken);<|endoftext|>


<commit_before>// Inspired by https://www.promisejs.org/generators/
function runGenerator (makeGenerator) {
  return function (thisArg, args) {
    var generator = makeGenerator.apply(thisArg, args)

    function handle (result, gen) {
      var value = result.value

      if (value != null) {
        if (value.constructor.name === 'GeneratorFunctionPrototype') {
          value = handle(value.next(), value)
        } else if (value.constructor.name === 'GeneratorFunction') {
          value = runGenerator(value)(thisArg, args)
        }
      }

      if (result.done) {
        return Promise.resolve(value)
      }

      return Promise.resolve(value).then(function (res) {
        return handle(gen.next(res), gen)
      }, function (err){
        return handle(gen.throw(err), gen)
      })
    }

    try {
      return handle(generator.next(), generator)
    } catch (ex) {
      return Promise.reject(ex)
    }
  }
}

function calling (func, thisArg, args) {
  if (typeof func !== 'function') {
    return func
  }

  var ctx = thisArg == null ? this : thisArg

  return func.constructor.name === 'GeneratorFunction' ?
          runGenerator(func)(ctx, args) : new Promise(function (res, rej) {
            try {
              res(func.apply(ctx, args))
            } catch (ex) {
              rej(ex)
            }
          })
}

Object.defineProperty(calling, 'wrap', {
  enumerable: true,
  value: function (func) {
    return function () {
      return calling(func, this, arguments)
    }
  }
})

module.exports = calling
<commit_msg>should return promise for non-function and non-generator function value<commit_after>// Inspired by https://www.promisejs.org/generators/
function runGenerator (makeGenerator) {
  return function (thisArg, args) {
    var generator = makeGenerator.apply(thisArg, args)

    function handle (result, gen) {
      var value = result.value

      if (value != null) {
        if (value.constructor.name === 'GeneratorFunctionPrototype') {
          value = handle(value.next(), value)
        } else if (value.constructor.name === 'GeneratorFunction') {
          value = runGenerator(value)(thisArg, args)
        }
      }

      if (result.done) {
        return Promise.resolve(value)
      }

      return Promise.resolve(value).then(function (res) {
        return handle(gen.next(res), gen)
      }, function (err){
        return handle(gen.throw(err), gen)
      })
    }

    try {
      return handle(generator.next(), generator)
    } catch (ex) {
      return Promise.reject(ex)
    }
  }
}

function calling (func, thisArg, args) {
  if (typeof func !== 'function') {
    return Promise.resolve(func)
  }

  var ctx = thisArg == null ? this : thisArg

  return func.constructor.name === 'GeneratorFunction' ?
          runGenerator(func)(ctx, args) : new Promise(function (res, rej) {
            try {
              res(func.apply(ctx, args))
            } catch (ex) {
              rej(ex)
            }
          })
}

Object.defineProperty(calling, 'wrap', {
  enumerable: true,
  value: function (func) {
    return function () {
      return calling(func, this, arguments)
    }
  }
})

module.exports = calling
<|endoftext|>


<commit_before>exports['africa_110m.json'] = require('./dist/africa_110m.json');
exports['africa_50m.json'] = require('./dist/africa_50m.json');
exports['asia_110m.json'] = require('./dist/asia_110m.json');
exports['asia_50m.json'] = require('./dist/asia_50m.json');
exports['europe_110m.json'] = require('./dist/europe_110m.json');
exports['europe_50m.json'] = require('./dist/europe_50m.json');
exports['north-america_110m.json'] = require('./dist/north-america_110m.json');
exports['north-america_50m.json'] = require('./dist/north-america_50m.json');
exports['south-america_110m.json'] = require('./dist/south-america_110m.json');
exports['south-america_50m.json'] = require('./dist/south-america_50m.json');
exports['usa_110m.json'] = require('./dist/usa_110m.json');
exports['usa_50m.json'] = require('./dist/usa_50m.json');
exports['world_110m.json'] = require('./dist/world_110m.json');
exports['world_50m.json'] = require('./dist/world_50m.json');
<commit_msg>rm '.json' from index export obj<commit_after>exports['world_110m'] = require('./dist/world_110m.json');
exports['world_50m'] = require('./dist/world_50m.json');

exports['africa_110m'] = require('./dist/africa_110m.json');
exports['africa_50m'] = require('./dist/africa_50m.json');

exports['asia_110m'] = require('./dist/asia_110m.json');
exports['asia_50m'] = require('./dist/asia_50m.json');

exports['europe_110m'] = require('./dist/europe_110m.json');
exports['europe_50m'] = require('./dist/europe_50m.json');

exports['north-america_110m'] = require('./dist/north-america_110m.json');
exports['north-america_50m'] = require('./dist/north-america_50m.json');

exports['south-america_110m'] = require('./dist/south-america_110m.json');
exports['south-america_50m'] = require('./dist/south-america_50m.json');

exports['usa_110m'] = require('./dist/usa_110m.json');
exports['usa_50m'] = require('./dist/usa_50m.json');
<|endoftext|>


<commit_before>var sourceMap = require('source-map'),
    SourceMapConsumer = sourceMap.SourceMapConsumer,
    SourceMapGenerator = sourceMap.SourceMapGenerator

module.exports = merge

/**
 * Merge old source map and new source map and return merged.
 * If old or new source map value is falsy, return another one as it is.
 *
 * @param {object|undefined} oldMap old source map object
 * @param {object|undefined} newmap new source map object
 * @return {object|undefined} merged source map object, or undefined when both old and new source map are undefined
 */
function merge(oldMap, newMap) {

  if (!oldMap)
    return newMap
  if (!newMap)
    return oldMap

  var oldMapConsumer = new SourceMapConsumer(oldMap),
      newMapConsumer = new SourceMapConsumer(newMap),
      mergedMapGenerator = new SourceMapGenerator()

  // iterate on new map and overwrite original position of new map with one of old map
  newMapConsumer.eachMapping(function(m) {

    // pass when `originalLine` is null.
    // It occurs in case that the node does not have origin in original code.
    if (m.originalLine == null)
      return

    var origPosInOldMap = oldMapConsumer.originalPositionFor({line: m.originalLine, column: m.originalColumn})
    if (origPosInOldMap.source == null)
      return

    mergedMapGenerator.addMapping({
      original: {
        line: origPosInOldMap.line,
        column: origPosInOldMap.column
      },
      generated: {
        line: m.generatedLine,
        column: m.generatedColumn
      },
      source: m.source,
      name: m.name
    })
  })

  var mergedMap = JSON.parse(mergedMapGenerator.toString())
  mergedMap.sources = oldMap.sources
  mergedMap.sourcesContent = oldMap.sourcesContent
  mergedMap.sourceRoot = oldMap.sourceRoot

  return mergedMap
}
<commit_msg>map to the old source map files<commit_after>var sourceMap = require('source-map'),
    SourceMapConsumer = sourceMap.SourceMapConsumer,
    SourceMapGenerator = sourceMap.SourceMapGenerator

module.exports = merge

/**
 * Merge old source map and new source map and return merged.
 * If old or new source map value is falsy, return another one as it is.
 *
 * @param {object|undefined} oldMap old source map object
 * @param {object|undefined} newmap new source map object
 * @return {object|undefined} merged source map object, or undefined when both old and new source map are undefined
 */
function merge(oldMap, newMap) {

  if (!oldMap)
    return newMap
  if (!newMap)
    return oldMap

  var oldMapConsumer = new SourceMapConsumer(oldMap),
      newMapConsumer = new SourceMapConsumer(newMap),
      mergedMapGenerator = new SourceMapGenerator()

  // iterate on new map and overwrite original position of new map with one of old map
  newMapConsumer.eachMapping(function(m) {

    // pass when `originalLine` is null.
    // It occurs in case that the node does not have origin in original code.
    if (m.originalLine == null)
      return

    var origPosInOldMap = oldMapConsumer.originalPositionFor({line: m.originalLine, column: m.originalColumn})
    if (origPosInOldMap.source == null)
      return

    mergedMapGenerator.addMapping({
      original: {
        line: origPosInOldMap.line,
        column: origPosInOldMap.column
      },
      generated: {
        line: m.generatedLine,
        column: m.generatedColumn
      },
      source: origPosInOldMap.source,
      name: origPosInOldMap.name
    })
  })

  var mergedMap = JSON.parse(mergedMapGenerator.toString())
  mergedMap.sources = oldMap.sources
  mergedMap.sourcesContent = oldMap.sourcesContent
  mergedMap.sourceRoot = oldMap.sourceRoot

  return mergedMap
}
<|endoftext|>