<commit_before>var _ = require('lodash')
  , crypto = require('crypto')
  , qs = require('qs')
  , request = require('request')
  , sprintf = require('sprintf-js');

exports.hash = function (email) {
  email = email.replace(' ', '').toLowerCase();
  return crypto.createHash('md5').update(email).digest('hex');
};

exports.image = {
  url: function (hash, options) {
    var domain = options.secure ? 'https://secure.gravatar.com' : 'http://www.gravatar.com';
    var params = qs.stringify(_.reject(options, 'secure');
    return sprintf('%s/avatar/%s?%s', domain, hash, params);
  }
};

exports.profile = {
  data: function (hash, options, callback) {
    if (!callback) callback = options;

    var opts = {
      headers: {'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13'},
      json: true,
      url: this.url(hash, options)
    };

    request.get(opts, function (err, res, body) {
      if (res.statusCode !== 200) return callback(res.statusCode);
      callback(err, body);
    });
  },
  url: function (hash, options) {
    var domain = options.secure ? 'https://secure.gravatar.com' : 'http://www.gravatar.com';
    return sprintf('%s/%s.json', domain, hash);
  }
};<commit_msg>allow email or hash, bug fixes<commit_after>var _ = require('lodash')
  , crypto = require('crypto')
  , qs = require('qs')
  , request = require('request')
  , sprintf = require('sprintf-js').sprintf;

exports.hash = function (email) {
  if (!~email.indexOf('@')) return email;
  email = email.replace(' ', '').toLowerCase();
  return crypto.createHash('md5').update(email).digest('hex');
};

exports.image = {
  url: function (email, options) {
    var domain = options.secure ? 'https://secure.gravatar.com' : 'http://www.gravatar.com';
    var params = qs.stringify(_.reject(options, 'secure'));
    return sprintf('%s/avatar/%s?%s', domain, exports.hash(email), params);
  }
};

exports.profile = {
  data: function (email, options, callback) {
    if (!callback) callback = options;

    var opts = {
      headers: {'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13'},
      json: true,
      url: this.url(email, options)
    };

    request.get(opts, function (err, res, body) {
      if (res.statusCode !== 200) return callback(res.statusCode);
      callback(err, body);
    });
  },
  url: function (email, options) {
    var domain = options.secure ? 'https://secure.gravatar.com' : 'http://www.gravatar.com';
    return sprintf('%s/%s.json', domain, exports.hash(email));
  }
};<|endoftext|>


<commit_before>#! /usr/bin/env node
/**
 * Created by Daniel on 8/13/2015.
 */

var http = require('https');
var fs =require('fs');
var AdmZip = require('adm-zip');
var ncp = require('ncp').ncp;
var path = require ("path");
ncp.limit = 32;

var rmdir = function(dir) {
    var list = fs.readdirSync(dir);
    for(var i = 0; i < list.length; i++) {
        var filename = path.join(dir, list[i]);
        var stat = fs.statSync(filename);

        if(filename == "." || filename == "..") {
            // pass these files
        } else if(stat.isDirectory()) {
            // rmdir recursively
            rmdir(filename);
        } else {
            // rm fiilename
            fs.unlinkSync(filename);
        }
    }
    //console.log('delete folder',dir);
    try{
        fs.rmdirSync(dir)
    }
    catch(e){

    }
};

var download = function(url,localZipPath) {

    var file = fs.createWriteStream(localZipPath);
    var request = http.get(url, function(response) {
        if([301,302].indexOf(response.statusCode) > -1){
            console.warn('file has been redirected');
            download(response.headers.location,localZipPath);
            return;
        }

        console.log('begin downloading zip file...');
        response.pipe(file);
        file.on('finish',function(){
            console.log('downloaded zip.');
            file.close(function(a){
                console.log(a);
                console.log('unzipping...');
                var zip = new AdmZip(localZipPath);
                console.log('upzipping...');
                zip.extractAllTo("./" );
                console.log('delete zip file.');
                fs.unlink(localZipPath);
                console.log('move files to root...');
                ncp('./sdk-master', './', function (err) {
                    if (err) console.error(err);
                    console.log('clean up...');
                    rmdir('./sdk-master');
                    rmdir('./sdk-master');
                });
            });

        })
    }).on('error', function(err) { // Handle errors
        console.error(err);
    });
};

/* args
node.exe
path
[command]
 */
if(process.argv.length < 3 || ['-help','help','?','/?'].indexOf(process.argv[2].toLowerCase()) >= 0 ){
    console.log('==================================================');
    console.log('arguments:');
    console.log('* create: this will download latest BuildFire SDK in the current folder');
}
else if(process.argv[2].toLowerCase() == "create")
    download("https://github.com/BuildFire/sdk/archive/master.zip","./_tempsdk.zip");
else
    console.error('unknown command');

<commit_msg>add update command<commit_after>#! /usr/bin/env node
/**
 * Created by Daniel on 8/13/2015.
 */

var http = require('https');
var fs =require('fs');
var AdmZip = require('adm-zip');
var ncp = require('ncp').ncp;
var path = require ("path");
ncp.limit = 32;

var rmdir = function(dir) {
    var list = fs.readdirSync(dir);
    for(var i = 0; i < list.length; i++) {
        var filename = path.join(dir, list[i]);
        var stat = fs.statSync(filename);

        if(filename == "." || filename == "..") {
            // pass these files
        } else if(stat.isDirectory()) {
            // rmdir recursively
            rmdir(filename);
        } else {
            // rm fiilename
            fs.unlinkSync(filename);
        }
    }
    //console.log('delete folder',dir);
    try{
        fs.rmdirSync(dir)
    }
    catch(e){

    }
};

var download = function(url,localZipPath) {

    var file = fs.createWriteStream(localZipPath);
    var request = http.get(url, function(response) {
        if([301,302].indexOf(response.statusCode) > -1){
            console.warn('file has been redirected');
            download(response.headers.location,localZipPath);
            return;
        }

        console.log('begin downloading zip file...');
        response.pipe(file);
        file.on('finish',function(){
            console.log('downloaded zip.');
            file.close(function(a){
                console.log(a);
                console.log('unzipping...');
                var zip = new AdmZip(localZipPath);
                console.log('upzipping...');
                zip.extractAllTo("./" );
                console.log('delete zip file.');
                fs.unlink(localZipPath);
                console.log('move files to root...');
                ncp('./sdk-master', './', function (err) {
                    if (err) console.error(err);
                    console.log('clean up...');
                    rmdir('./sdk-master');
                });
            });

        })
    }).on('error', function(err) { // Handle errors
        console.error(err);
    });
};

/* args
node.exe
path
[command]
 */
if(process.argv.length < 3 || ['-help','help','?','/?'].indexOf(process.argv[2].toLowerCase()) >= 0 ){
    console.log('==================================================');
    console.log('arguments:');
    console.log('* create: this will download latest BuildFire SDK in the current folder');
    console.log('* update: this will download latest BuildFire SDK and update the current folder');
}
else if(["create","update"].indexOf( process.argv[2].toLowerCase() ) >=0 )
    download("https://github.com/BuildFire/sdk/archive/master.zip","./_tempsdk.zip");
else
    console.error('unknown command');

<|endoftext|>


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

const request = require('request')
const chalk = require('chalk')
const Spinner = require('cli-spinner').Spinner
const isChinese = require('is-chinese')
const urlencode = require('urlencode')
const noCase = require('no-case')
const config = require('./lib/config')
const Parser = require('./lib/parser')

let word = process.argv.slice(2).join(' ')
if (!word) {
	console.log('Usage: yd <WORD_TO_QUERY>')
	process.exit()
}

const spinner = new Spinner('努力查询中... %s')

if (config.spinner) {
	spinner.setSpinnerString('|/-\\')
	spinner.start()
}

const isCN = isChinese(word)

word = isCN ? word : noCase(word)

const options = {
	'url': config.getURL(word) + urlencode(word),
	'proxy': config.proxy || null
}

const ColorOutput = chalk.keyword(config.color)
request(options, (error, response, body) => {
	if (error) {
		console.error(error)
	}

	if (config.spinner) {
		spinner.stop(true)
	}
	console.log(ColorOutput(Parser.parse(isCN, body)))
})
<commit_msg>commit<commit_after>#!/usr/bin/env node

const request = require('request')
const chalk = require('chalk')
const Spinner = require('cli-spinner').Spinner
const isChinese = require('is-chinese')
const urlencode = require('urlencode')
const noCase = require('no-case')
const config = require('./lib/config')
const Parser = require('./lib/parser')

let word = process.argv.slice(2).join(' ')
if (!word) {
	console.log('Usage: yd <WORD_TO_QUERY>')
	process.exit()
}

const spinner = new Spinner('努力查询中... %s')

if (config.spinner) {
	spinner.setSpinnerString('|/-\\')
	spinner.start()
}

const isCN = isChinese(word)

word = isCN ? word : noCase(word)

const options = {
	'url': config.getURL(word) + urlencode(word),
	'proxy': config.proxy || null
}

const ColorOutput = chalk.keyword(config.color)
request(options, (error, response, body) => {
	if (error) {
		console.error(error)
	}

	if (config.spinner) {
		spinner.stop(true)
	}
	console.log(ColorOutput(Parser.parse(isCN, body)))
})
<|endoftext|>


<commit_before>'use strict'

const printChat = require('../printChat.js')

const addEdge = (cy, srcNode, trgNode, srcNodeCpt, trgNodeCp, label) => {
  cy.add({
    group: 'edges',
    data: {
      id: `e${srcNode}${trgNode}`,
      source: `${srcNode}`,
      target: `${trgNode}`,
      label: `${label}`
    }
  })
}

module.exports = function addComponent (cy, srcNode, trgNode, srcNodeCpt, trgNodeCpt) {
  if (srcNodeCpt === 'sensor' && trgNodeCpt === 'model') {
    addEdge(cy, srcNode, trgNode, srcNodeCpt, trgNodeCpt, 'belongs')
  } else if (srcNodeCpt === 'model' && trgNodeCpt === 'model') {
    addEdge(cy, srcNode, trgNode, srcNodeCpt, trgNodeCpt, 'configuration')
  } else if (srcNodeCpt === 'event' && trgNodeCpt === 'model') {
    addEdge(cy, srcNode, trgNode, srcNodeCpt, trgNodeCpt, 'affects')
  } else if (srcNodeCpt === 'sensor' && trgNodeCpt === 'event') {
    addEdge(cy, srcNode, trgNode, srcNodeCpt, trgNodeCpt, 'detects')
  } else {
    printChat('mistake 😔')
  }
}
<commit_msg>:hammer: to switch statements<commit_after>'use strict'

const printChat = require('../printChat.js')

const addEdge = (cy, srcNode, trgNode, srcNodeCpt, trgNodeCp, label) => {
  cy.add({
    group: 'edges',
    data: {
      id: `e${srcNode}${trgNode}`,
      source: `${srcNode}`,
      target: `${trgNode}`,
      label: `${label}`
    }
  })
}

module.exports = function addComponent (cy, srcNode, trgNode, srcNodeCpt, trgNodeCpt) {
  switch (true) {
    case (srcNodeCpt === 'sensor' && trgNodeCpt === 'model'):
      addEdge(cy, srcNode, trgNode, srcNodeCpt, trgNodeCpt, 'belongs')
      break
    case (srcNodeCpt === 'model' && trgNodeCpt === 'model'):
      addEdge(cy, srcNode, trgNode, srcNodeCpt, trgNodeCpt, 'configuration')
      break
    case (srcNodeCpt === 'event' && trgNodeCpt === 'model'):
      addEdge(cy, srcNode, trgNode, srcNodeCpt, trgNodeCpt, 'affects')
      break
    case (srcNodeCpt === 'sensor' && trgNodeCpt === 'event'):
      addEdge(cy, srcNode, trgNode, srcNodeCpt, trgNodeCpt, 'detects')
      break
    default:
      printChat('mistake 😔')
  }
}
<|endoftext|>


<commit_before>// This node library follows some rules that I think are very reasonable.  Basically it doesn't work on a url that is stupidly complex.
// There is no need for a url to contain nested loops or enumerations.  The restrictions also mean that loops are the only place where ambiguity, and thus, an NDFA could occur.
// This library takes this into account and will resolve it for you.
// I also need to rewrite this so that it follows better design with JavaScript.
// This is the first reasonable complex JavaScript program I have written.  The only real issue is how I handle errors.

State = function(isTerm, transitions) {
    this.isTerm = isTerm;
    this.transitions = transitions;
    if (typeof transitions === 'undefined') {
        this.transitions = [];
    }
    if (typeof isTerm === 'undefined') {
        this.isTerm = false;
    }
}

State.prototype.transition = function(transVal) {
    for (var index = 0; index < this.transCount(); index++) {
        if (transVal === this.transitions[index].transVal) {
            return this.transitions[index].state;
        }
    }
    return null;
}

State.prototype.addTransition = function(transVal, state) {
    var hasTrans = this.getTransition(transVal);
    if (hasTrans === null) {
        this.transitions.push({
            state: state,
            transVal: transVal
        });
    } else if (this === hasTrans.state) {
        this.updateTransition(transVal, transVal, state);
        var selfTransitions = this.getSelfTransitions();
        selfTransitions.forEach(function(value) {
            state.addTransition(value.transVal, value.state);
        });
        state.addTransition(transVal, state);
    }
}

State.prototype.getSelfTransitions = function() {
    var base = this;
    return this.transitions.filter(function(value) {
        return value.state === base;
    });
}

State.prototype.updateTransition = function(transVal, newTransVal, newState) {
    for (var index = 0; index < this.transitions.length; index++) {
        if (this.transitions[index].transVal === transVal) {
            this.transitions[index] = {
                state: newState,
                transVal: newTransVal
            };
        }
    }
}

State.prototype.addTransitions = function(transVals, state) {
    var base = this;
    transVals.forEach(function(elem, index, array) {
        base.addTransition(elem, state);
    });
}

State.prototype.getTransition = function(transVal) {
    for (var index = 0; index < this.transitions.length; index++) {
        if (this.transitions[index].transVal === transVal) {
            return this.transitions[index];
        }
    }

    return null;
}

State.prototype.transCount = function() {
    return this.transitions.length;
}

Ndfa = function(regex) {
    this.startState = null;
    this.regex = regex;
    if (typeof regex === 'undefined') {
        this.regex = "";
    }
}

Ndfa.prototype.generateStates = function() {
    this.startState = new State();
    var curState = this.startState;

    for (var index = 0; index < this.regex.length; index++) {
        if (this.validate.isValid(this.regex[index])) {
            var newState = new State();
            curState.addTransition(this.regex[index], newState);
            curState = newState;
        } else if (this.regex[index] === '(') {
            var enumLen = this.getEnumLength(this.regex.substring(index));
            var enumeration = this.extract(this.regex, index, enumLen);
            var newState = this.getEnumState(enumeration, curState);
            if (newState !== null) {
                curState = newState;
                index += enumLen;
            }
        } else if (this.regex[index] === '[') {
            var loopLen = this.getLoopLength(this.regex.substring(index));
            var loop = this.extract(this.regex, index, loopLen);
            var newState = this.processLoop(loop, curState);
            if (newState !== null) {
                curState = newState;
                index += loopLen;
            }
        }
    }
    curState.isTerm = true;
}

Ndfa.prototype.extract = function(str, index, extractionLen) {
    return this.regex.substr(index + 1, extractionLen - 1);
}

Ndfa.prototype.getLoopLength = function(str) {
    if (str[0] !== '[') {
        return null;
    }

    var index = 0;
    while (str[index] !== ']') {
        if (str.length === index) {
            return null;
        }
        index += 1;
    }
    return index;
}

Ndfa.prototype.processLoop = function(loop, initialState) {
    var trans = loop.split('|');

    for (var index = 0; index < trans.length; index++) {
        var notValid = (trans[index].length !== 1 || trans[index].length !== 2) && !this.validate.isValid(trans[index])
        if (notValid) {
            return null;
        }
    }

    var state = new State();
    var base = this;

    trans.forEach(function(elem, index, array) {
        if (elem.length === 1) {
            initialState.addTransition(elem, state);
            state.addTransition(elem, state);
        } else {
            var range = base.validate.getRange(elem.charAt(0), elem.charAt(1));
            initialState.addTransitions(range, state)
            state.addTransitions(range, state);
        }
    });

    return state
}

Ndfa.prototype.getEnumLength = function(str) {
    if (str[0] !== '(') {
        return null;
    }

    var index = 0;
    while (str[index] !== ')') {
        if (str.length === index) {
            return null;
        }
        index += 1;
    }

    return index;
}

Ndfa.prototype.getEnumState = function(str, initialState) {
    var trans = str.split('|');
    for (var index = 0; index < trans.length; index++) {
        var notValid = trans[index].length !== 1 || !this.validate.isValid(trans[index])
        if (notValid) {
            return null;
        }
    }

    var state = new State();
    trans.forEach(function(element, index, array) {
        initialState.addTransition(element, state);
    });

    return state;
}

Ndfa.prototype.testString = function(str) {
    var curState = this.startState;
    for (var index = 0; index < str.length; index++) {
        curState = curState.transition(str[index]);
        if (curState === null) {
            break;
        }
    }
    return curState !== null && curState.isTerm;
}

Ndfa.prototype.validate = (function() {
    this.validateRangeableDigit = function(char) {
        var charCast = char.charCodeAt(0);
        var diff = '9'.charCodeAt(0) - charCast;
        return 9 >= diff && diff >= 0;
    };

    this.validateRangeableLowerCase = function(char) {
        var charCast = char.charCodeAt(0);
        var diff = 'z'.charCodeAt(0) - charCast;
        return 25 >= diff && diff >= 0;
    };

    this.validateRangeableUpperCase = function(char) {
        var charCast = char.charCodeAt(0);
        var diff = 'Z'.charCodeAt(0) - charCast;
        return 25 >= diff && diff >= 0;
    };

    this.validateUnRangeable = function(char) {
        return char === '-' || char === '_' ||
            char === '.' || char === '~' ||
            char === '%';
    };

    this.validateOperators = function(char) {
        return char === '[' || char === ']' ||
            char === '(' || char === ')' ||
            char === '|';
    };

    this.validateEnumsLoops = function(regex) {
        var valid = true;
        var regexArray = regex.split('|');
        var inEnum = false;
        var inLoop = false;

        for(var index = 0; index < regexArray.length && valid; index++) {
            var charCount = 0;
            for(var charIndex = 0; charIndex < regexArray[index].length && valid; charIndex++) {
                var curChar = regexArray[index][charIndex];
                if (curChar === '[') {
                    if (!inEnum && !inLoop) {
                        inLoop = true;
                    } else {
                        valid = false;
                    }
                } else if (curChar === '(') {
                    if (!inEnum && !inLoop) {
                        inEnum = true;
                    } else {
                        valid = false;
                    }
                } else if (curChar === ']') {
                    if (inLoop && (charCount === 1 || charCount === 2)) {
                        inLoop = false;
                    } else {
                        valid = false;
                    }
                } else if (curChar === ')') {
                    if (inEnum && charCount === 1) {
                        inEnum = false;
                    } else {
                        valid = false;
                    }
                } else if (inEnum || inLoop) {
                    if (curChar === '') {
                        valid = false;
                    } else {
                        charCount++;
                        if (inEnum && charCount > 1) {
                            valid = false;
                        } else if (inLoop && charCount > 2) {
                            valid = false;
                        }
                    }
                }
            }
            if (inLoop && (charCount < 1 || charCount > 2)) {
                valid = false;
            }
            if (inEnum && charCount !== 1) {
                valid = false;
            }
        }
        return valid;
    };

    this.isValid = function(str) {
        var valid = false;
        for(var index = 0; index < str.length; index++) {
            valid = valid || validateRangeableDigit(str[index]);
            valid = valid || validateRangeableUpperCase(str[index]);
            valid = valid || validateRangeableLowerCase(str[index]);
            valid = valid || validateUnRangeable(str[index]);
        }
        return valid;
    };

    return {
        getRange: function(bound1, bound2) {
            var begin = bound1.charCodeAt(0);
            var end = bound2.charCodeAt(0);
            var charRange = [];
            if (begin > end) {
                begin = bound2Int;
                end = bound1Int;
            }

            for (var char = begin; char <= end; char++) {
                charRange.push(String.fromCharCode(char));
            }

            return charRange;
        },
        canRange: function(bound1, bound2) {
            var valid = false;
            for (var index = 0; index < validateRangeable.length; index++) {
                valid = valid || (validateRangeable[index](bound1) && validateRangeable[index](bound2));
            }
            return valid;
        },
        isValidRegex: function(regex) {
            var valid = true;

            for(var index = 0; index < regex.length; index++) {
                var isValidChar = isValid(regex[index]);
                var isOperator = validateOperators(regex[index]);
                valid = isValidChar || isOperator;
                if(!valid) {
                    break;
                }
            }

            if(valid) {
                valid = validateEnumsLoops(regex);
            }

            return valid;
        }
    };
})();

exports.Ndfa = Ndfa;
var n = new Ndfa('abc');
console.log(n.validate.isValidRegex('abc'));
console.log(n.validate.isValidRegex('abcab[=]e'));
console.log(n.validate.isValidRegex('abc[|z]aed'));
console.log(n.validate.isValidRegex('abc(|z)aed'));
console.log(n.validate.isValidRegex('abc[a|e|f|s|d]eeeaaa'));
<commit_msg>mo bedda. I need to refactor this code.  It is still very manageble but it could be prettier.<commit_after>// This node library follows some rules that I think are very reasonable.  Basically it doesn't work on a url that is stupidly complex.
// There is no need for a url to contain nested loops or enumerations.  The restrictions also mean that loops are the only place where ambiguity, and thus, an NDFA could occur.
// This library takes this into account and will resolve it for you.
// I also need to rewrite this so that it follows better design with JavaScript.
// This is the first reasonable complex JavaScript program I have written.  The only real issue is how I handle errors.

State = function(isTerm, transitions) {
    this.isTerm = isTerm;
    this.transitions = transitions;
    if (typeof transitions === 'undefined') {
        this.transitions = [];
    }
    if (typeof isTerm === 'undefined') {
        this.isTerm = false;
    }
}

State.prototype.transition = function(transVal) {
    for (var index = 0; index < this.transCount(); index++) {
        if (transVal === this.transitions[index].transVal) {
            return this.transitions[index].state;
        }
    }
    return null;
}

State.prototype.addTransition = function(transVal, state) {
    var hasTrans = this.getTransition(transVal);
    if (hasTrans === null) {
        this.transitions.push({
            state: state,
            transVal: transVal
        });
    } else if (this === hasTrans.state) {
        this.updateTransition(transVal, transVal, state);
        var selfTransitions = this.getSelfTransitions();
        selfTransitions.forEach(function(value) {
            state.addTransition(value.transVal, value.state);
        });
        state.addTransition(transVal, state);
    }
}

State.prototype.getSelfTransitions = function() {
    var base = this;
    return this.transitions.filter(function(value) {
        return value.state === base;
    });
}

State.prototype.updateTransition = function(transVal, newTransVal, newState) {
    for (var index = 0; index < this.transitions.length; index++) {
        if (this.transitions[index].transVal === transVal) {
            this.transitions[index] = {
                state: newState,
                transVal: newTransVal
            };
        }
    }
}

State.prototype.addTransitions = function(transVals, state) {
    var base = this;
    transVals.forEach(function(elem, index, array) {
        base.addTransition(elem, state);
    });
}

State.prototype.getTransition = function(transVal) {
    for (var index = 0; index < this.transitions.length; index++) {
        if (this.transitions[index].transVal === transVal) {
            return this.transitions[index];
        }
    }

    return null;
}

State.prototype.transCount = function() {
    return this.transitions.length;
}

Ndfa = function(regex) {
    this.startState = null;
    this.regex = regex;
    if (typeof regex === 'undefined') {
        this.regex = "";
    }
}

Ndfa.prototype.generateStates = function() {
    this.startState = new State();
    var curState = this.startState;

    for (var index = 0; index < this.regex.length; index++) {
        if (this.validate.isValid(this.regex[index])) {
            var newState = new State();
            curState.addTransition(this.regex[index], newState);
            curState = newState;
        } else if (this.regex[index] === '(') {
            var enumLen = this.getEnumLength(this.regex.substring(index));
            var enumeration = this.extract(this.regex, index, enumLen);
            var newState = this.getEnumState(enumeration, curState);
            if (newState !== null) {
                curState = newState;
                index += enumLen;
            }
        } else if (this.regex[index] === '[') {
            var loopLen = this.getLoopLength(this.regex.substring(index));
            var loop = this.extract(this.regex, index, loopLen);
            var newState = this.processLoop(loop, curState);
            if (newState !== null) {
                curState = newState;
                index += loopLen;
            }
        }
    }
    curState.isTerm = true;
}

Ndfa.prototype.extract = function(str, index, extractionLen) {
    return this.regex.substr(index + 1, extractionLen - 1);
}

Ndfa.prototype.getLoopLength = function(str) {
    if (str[0] !== '[') {
        return null;
    }

    var index = 0;
    while (str[index] !== ']') {
        if (str.length === index) {
            return null;
        }
        index += 1;
    }
    return index;
}

Ndfa.prototype.processLoop = function(loop, initialState) {
    var trans = loop.split('|');

    for (var index = 0; index < trans.length; index++) {
        var notValid = (trans[index].length !== 1 || trans[index].length !== 2) && !this.validate.isValid(trans[index])
        if (notValid) {
            return null;
        }
    }

    var state = new State();
    var base = this;

    trans.forEach(function(elem, index, array) {
        if (elem.length === 1) {
            initialState.addTransition(elem, state);
            state.addTransition(elem, state);
        } else {
            var range = base.validate.getRange(elem.charAt(0), elem.charAt(1));
            initialState.addTransitions(range, state)
            state.addTransitions(range, state);
        }
    });

    return state
}

Ndfa.prototype.getEnumLength = function(str) {
    if (str[0] !== '(') {
        return null;
    }

    var index = 0;
    while (str[index] !== ')') {
        if (str.length === index) {
            return null;
        }
        index += 1;
    }

    return index;
}

Ndfa.prototype.getEnumState = function(str, initialState) {
    var trans = str.split('|');
    for (var index = 0; index < trans.length; index++) {
        var notValid = trans[index].length !== 1 || !this.validate.isValid(trans[index])
        if (notValid) {
            return null;
        }
    }

    var state = new State();
    trans.forEach(function(element, index, array) {
        initialState.addTransition(element, state);
    });

    return state;
}

Ndfa.prototype.testString = function(str) {
    var curState = this.startState;
    for (var index = 0; index < str.length; index++) {
        curState = curState.transition(str[index]);
        if (curState === null) {
            break;
        }
    }
    return curState !== null && curState.isTerm;
}

Ndfa.prototype.validate = (function() {
    this.validateRangeableDigit = function(char) {
        var charCast = char.charCodeAt(0);
        var diff = '9'.charCodeAt(0) - charCast;
        return 9 >= diff && diff >= 0;
    };

    this.validateRangeableLowerCase = function(char) {
        var charCast = char.charCodeAt(0);
        var diff = 'z'.charCodeAt(0) - charCast;
        return 25 >= diff && diff >= 0;
    };

    this.validateRangeableUpperCase = function(char) {
        var charCast = char.charCodeAt(0);
        var diff = 'Z'.charCodeAt(0) - charCast;
        return 25 >= diff && diff >= 0;
    };

    this.validateUnRangeable = function(char) {
        return char === '-' || char === '_' ||
            char === '.' || char === '~' ||
            char === '%';
    };

    this.validateOperators = function(char) {
        return char === '[' || char === ']' ||
            char === '(' || char === ')' ||
            char === '|';
    };

    this.validateEnumsLoops = function(regex) {
        var valid = true;
        var regexArray = regex.split('|');
        var inEnum = false;
        var inLoop = false;

        for(var index = 0; index < regexArray.length && valid; index++) {
            var charCount = 0;
            for(var charIndex = 0; charIndex < regexArray[index].length && valid; charIndex++) {
                var curChar = regexArray[index][charIndex];
                if (curChar === '[') {
                    if (!inEnum && !inLoop) {
                        inLoop = true;
                    } else {
                        valid = false;
                    }
                } else if (curChar === '(') {
                    if (!inEnum && !inLoop) {
                        inEnum = true;
                    } else {
                        valid = false;
                    }
                } else if (curChar === ']') {
                    if (inLoop && (charCount === 1 || charCount === 2)) {
                        inLoop = false;
                    } else {
                        valid = false;
                    }
                } else if (curChar === ')') {
                    if (inEnum && charCount === 1) {
                        inEnum = false;
                    } else {
                        valid = false;
                    }
                } else if (inEnum || inLoop) {
                    if (curChar === '') {
                        valid = false;
                    } else {
                        charCount++;
                        if (charCount === 2) {

                            valid = canRange(regexArray[index][charIndex], regexArray[index][charIndex - 1])
                        }
                        if (inEnum && charCount > 1) {
                            valid = false;
                        } else if (inLoop && charCount > 2) {
                            valid = false;
                        }
                    }
                }
            }
            if (inLoop && (charCount < 1 || charCount > 2)) {
                valid = false;
            }
            if (inEnum && charCount !== 1) {
                valid = false;
            }
        }
        return valid;
    };

    this.isValid = function(str) {
        var valid = false;
        for(var index = 0; index < str.length; index++) {
            valid = valid || validateRangeableDigit(str[index]);
            valid = valid || validateRangeableUpperCase(str[index]);
            valid = valid || validateRangeableLowerCase(str[index]);
            valid = valid || validateUnRangeable(str[index]);
        }
        return valid;
    };

    this.canRange = function(bound1, bound2) {
        var valid = false;

        valid = valid || validateRangeableDigit(bound1) && validateRangeableDigit(bound2);
        valid = valid || validateRangeableUpperCase(bound1) && validateRangeableUpperCase(bound2);
        valid = valid || validateRangeableLowerCase(bound1) && validateRangeableLowerCase(bound2);

        return valid;
    };

    return {
        getRange: function(bound1, bound2) {
            var begin = bound1.charCodeAt(0);
            var end = bound2.charCodeAt(0);
            var charRange = [];
            if (begin > end) {
                begin = bound2Int;
                end = bound1Int;
            }

            for (var char = begin; char <= end; char++) {
                charRange.push(String.fromCharCode(char));
            }

            return charRange;
        },
        isValidRegex: function(regex) {
            var valid = true;

            for(var index = 0; index < regex.length; index++) {
                var isValidChar = isValid(regex[index]);
                var isOperator = validateOperators(regex[index]);
                valid = isValidChar || isOperator;
                if(!valid) {
                    break;
                }
            }

            if(valid) {
                valid = validateEnumsLoops(regex);
            }

            return valid;
        }
    };
})();

exports.Ndfa = Ndfa;
var n = new Ndfa('abc');
console.log(n.validate.isValidRegex('abc'));
console.log(n.validate.isValidRegex('abcab[=]e'));
console.log(n.validate.isValidRegex('abc[|z]aed'));
console.log(n.validate.isValidRegex('abc(|z)aed'));
console.log(n.validate.isValidRegex('abc[a|Aa|f|s|d]eeeaaa'));
<|endoftext|>


<commit_before>// index.js
var config = require('./config');
var getsoda = require('./getsoda');
var insertrow = require('./insertrow');
var Promise = require("bluebird");

getsoda()
.each(function(record){
    insertrow(record);
    return 0;
})
.catch(function(e) {
    console.log('Error: ' + e)
})
.finally(function() {
    console.log('Fin.');
});<commit_msg>Remove finish function.<commit_after>// index.js
var config = require('./config');
var getsoda = require('./getsoda');
var insertrow = require('./insertrow');
var Promise = require("bluebird");

getsoda()
.each(function(record){
    insertrow(record);
    return 0;
})
.catch(function(e) {
    console.log('Error: ' + e)
});
<|endoftext|>


<commit_before>function boo() {
  //Reset search.value
  var search = document.getElementById("search");
  search.value = "(";

  //extract function - splits tested input into arrays and removes array elements that are empty
    function extract(op, arrX) {
      if (/\w|\d/.test(arrX.value)) {
        var arrY = arrX.value.toLowerCase().split("\n");
        for (var i = 0; i < arrY.length; i++) {
          arrY[i] = arrY[i].trim();
          if (!(/\w|\d/.test(arrY[i]))) {
            arrY.splice(i, 1);
            i--;
          }
        }
        if (op.value === "and") {
          conObj = new obj(" AND ", arrY);
        } else {
          conObj = new obj(" NOT ", arrY);
        }
        concepts.push(conObj);
      }
    }

    //extract concepts and add to concepts array
    var concept = document.querySelectorAll(".concept");
    var operator = document.querySelectorAll('input:checked');
    var conObj;
    var concepts = [];
    //object constructor
    function obj(op, arr) {
      this.operator = op;
      this.array = arr;
      this.combine;
    }
    //ierate over all concept boxes
    for (var i = 0; i < concept.length; i++) {
      extract(operator[i], concept[i]);
    }

    //look for phrases
    for (var i = 0; i < concepts.length; i++) {
      for (var j = 0; j < concepts[i].array.length; j++) {
        if (/\s/.test(concepts[i].array[j])) {
          concepts[i].array[j] = "\"" + concepts[i].array[j] + "\"";
        }
      }
    }

    //combine synonyms "OR"
    for (var i = 0; i < concepts.length; i++) {
      var str = "(";
      for (var j = 0; j < concepts[i].array.length; j++) {
        if (j < concepts[i].array.length - 1) {
          str += concepts[i].array[j] + " OR ";
        } else {
          str += concepts[i].array[j] + ")";
        }
      }
      concepts[i].combine = str;
    }

    //combine concepts using user selected operators
    for (var i = 0; i < concepts.length; i++) {
      if (i < concepts.length - 1) {
        search.value += concepts[i].combine + concepts[i + 1].operator;
      } else {
        search.value += concepts[i].combine + ")";
      }
    }

    //check for empty search string
    if (search.value === "(") {
  	   search.value = "";
       alert("Please enter some concepts");
    }
  }

function addConcept() {

  var cnt = document.getElementsByClassName("booContainer").length;
  if (cnt < 6) {
    //find container div
    var container = document.getElementById("container");

    //create div
    var div = document.createElement("div");
    div.setAttribute("class", "booContainer");

    //create h4 and add text
    var h4 = document.createElement("h4");
    var count = document.querySelectorAll(".concept");
    var h4Text = "Concept " + (count.length + 1);
    h4.appendChild(document.createTextNode(h4Text));

    //create textarea
    var textarea = document.createElement("textarea");
    textarea.setAttribute("class", "concept");

    //create radio inputs
    function radObj(name, op, checked) {
      this.type = "radio";
      this.name = name;
      this.id = name + "-" + op;
      this.value = op;
      this.label = op.toUpperCase();
    }

    var name = "concept" + (count.length + 1).toString();
    var radioAND = new radObj(name, "and");
    var radioNOT = new radObj(name, "not");

    var radio = [document.createElement("input"), document.createElement("input")];
    var radioArr = [radioAND, radioNOT];
    var radioLabel = [document.createElement("label"), document.createElement("label")];
    for (var i = 0; i < radio.length; i++) {
      radio[i].setAttribute("type", radioArr[i].type);
      radio[i].setAttribute("name", radioArr[i].name);
      radio[i].setAttribute("id", radioArr[i].id);
      radio[i].setAttribute("value", radioArr[i].value);
      if (i === 0) {
        radio[i].setAttribute("checked", "");
      }
      radioLabel[i].setAttribute("for", radioArr[i].id);
      radioLabel[i].appendChild(document.createTextNode(radioArr[i].label));
    }

    //create linebreak
    var br = document.createElement("br");

    //append new elements
    container.appendChild(div);
    div.appendChild(h4);
    div.appendChild(textarea);
    div.appendChild(br);
    for (var i = 0; i < 2; i++) {
      div.appendChild(radio[i]);
      div.appendChild(radioLabel[i]);
    }
  } else {
    alert("Maximum number of concepts created");
  }
}

function resetAll() {
  var x = document.getElementsByClassName("concept");
  for (var i = 0; i < x.length; i++) {
    x[i].value = "";
  }
  var radios = document.querySelectorAll('input[value="and"]');
  for (var i = 0; i < radios.length; i++) {
  	radios[i].checked = true;
  }
}
<commit_msg>Update boo.js<commit_after>function boo() {
  //Reset search.value
  var search = document.getElementById("search");
  search.value = "(";

  //extract function - splits tested input into arrays and removes array elements that are empty
    function extract(op, arrX) {
      if (/\w|\d/.test(arrX.value)) {
        var arrY = arrX.value.toLowerCase().split("\n");
        for (var i = 0; i < arrY.length; i++) {
          arrY[i] = arrY[i].trim();
          if (!(/\w|\d/.test(arrY[i]))) {
            arrY.splice(i, 1);
            i--;
          }
        }
        if (op.value === "and") {
          conObj = new obj(" AND ", arrY);
        } else {
          conObj = new obj(" NOT ", arrY);
        }
        concepts.push(conObj);
      }
    }

    //extract concepts and add to concepts array
    var concept = document.querySelectorAll(".concept");
    var operator = document.querySelectorAll('input:checked');
    var conObj;
    var concepts = [];
    //object constructor
    function obj(op, arr) {
      this.operator = op;
      this.array = arr;
      this.combine;
    }
    //ierate over all concept boxes
    for (var i = 0; i < concept.length; i++) {
      extract(operator[i], concept[i]);
    }

    //look for phrases
    for (var i = 0; i < concepts.length; i++) {
      for (var j = 0; j < concepts[i].array.length; j++) {
        if (/\s/.test(concepts[i].array[j])) {
          concepts[i].array[j] = "\"" + concepts[i].array[j] + "\"";
        }
      }
    }

    //combine synonyms "OR"
    for (var i = 0; i < concepts.length; i++) {
      var str = "(";
      for (var j = 0; j < concepts[i].array.length; j++) {
        if (j < concepts[i].array.length - 1) {
          str += concepts[i].array[j] + " OR ";
        } else {
          str += concepts[i].array[j] + ")";
        }
      }
      concepts[i].combine = str;
    }

    //combine concepts using user selected operators
    for (var i = 0; i < concepts.length; i++) {
      if (i < concepts.length - 1) {
        search.value += concepts[i].combine + concepts[i + 1].operator;
      } else {
        search.value += concepts[i].combine + ")";
      }
    }

    //check for empty search string
    if (search.value === "(") {
  	   search.value = "";
       alert("Please enter some concepts");
    }
  }

function addConcept() {

  var cnt = document.getElementsByClassName("booContainer").length;
  if (cnt < 6) {
    //find container div
    var container = document.getElementById("container");

    //create div
    var div = document.createElement("div");
    div.setAttribute("class", "booContainer");

    //create h4 and add text
    var h4 = document.createElement("h4");
    var count = document.querySelectorAll(".concept");
    var h4Text = "Concept " + (count.length + 1);
    h4.appendChild(document.createTextNode(h4Text));

    //create textarea
    var textarea = document.createElement("textarea");
    textarea.setAttribute("class", "concept");

    //create radio inputs
    function radObj(name, op) {
      this.type = "radio";
      this.name = name;
      this.id = name + "-" + op;
      this.value = op;
      this.label = op.toUpperCase();
    }

    var name = "concept" + (count.length + 1).toString();
    var radioAND = new radObj(name, "and");
    var radioNOT = new radObj(name, "not");

    var radio = [document.createElement("input"), document.createElement("input")];
    var radioArr = [radioAND, radioNOT];
    var radioLabel = [document.createElement("label"), document.createElement("label")];
    for (var i = 0; i < radio.length; i++) {
      radio[i].setAttribute("type", radioArr[i].type);
      radio[i].setAttribute("name", radioArr[i].name);
      radio[i].setAttribute("id", radioArr[i].id);
      radio[i].setAttribute("value", radioArr[i].value);
      if (i === 0) {
        radio[i].setAttribute("checked", "");
      }
      radioLabel[i].setAttribute("for", radioArr[i].id);
      radioLabel[i].appendChild(document.createTextNode(radioArr[i].label));
    }

    //create linebreak
    var br = document.createElement("br");

    //append new elements
    container.appendChild(div);
    div.appendChild(h4);
    div.appendChild(textarea);
    div.appendChild(br);
    for (var i = 0; i < 2; i++) {
      div.appendChild(radio[i]);
      div.appendChild(radioLabel[i]);
    }
  } else {
    alert("Maximum number of concepts created");
  }
}

function resetAll() {
  var x = document.getElementsByClassName("concept");
  for (var i = 0; i < x.length; i++) {
    x[i].value = "";
  }
  var radios = document.querySelectorAll('input[value="and"]');
  for (var i = 0; i < radios.length; i++) {
  	radios[i].checked = true;
  }
}
<|endoftext|>


<commit_before>'use strict';

module.exports = {
    parserOptions: {
        // sourceType: 'module',
        ecmaFeatures: {
            jsx: true,
            experimentalObjectRestSpread: true
        }
    },
    env: {
        node: true,
        es6: true
    },
    globals: {
        logger: false
    },
    extends: 'eslint:recommended',
    rules: {
        // Possible Errors
        'no-console': [1, { allow: ['warn', 'error'] }], // overrides eslint:recommended config (2)

        // Best Practices
        eqeqeq: 2,
        'guard-for-in': 2,
        'no-caller': 2,
        'no-eval': 2,
        'no-extend-native': 2,
        'no-extra-bind': 2,
        'no-floating-decimal': 2,
        'no-implied-eval': 2,
        'no-loop-func': 2,
        'no-new-wrappers': 2,
        'no-return-assign': 2,
        'no-script-url': 2,
        'no-self-compare': 2,
        'no-sequences': 2,
        'no-throw-literal': 2,
        'no-unused-expressions': [2, { allowShortCircuit: true, allowTernary: true }],
        'no-useless-call': 2,
        'no-useless-concat': 2,
        'no-useless-escape': 2,
        'no-void': 2,
        yoda: 2,

        // Strict Mode
        strict: 2,

        // Variables
        'no-label-var': 2,
        'no-unused-vars': [2, { args: 'none' }],
        'no-shadow-restricted-names': 2,
        'no-undef-init': 2,
        'no-use-before-define': 2,

        // Node.js and CommonJS
        // TODO: Set rules for Node.js and CommonJS http://eslint.org/docs/rules/#nodejs-and-commonjs

        // Stylistic Issues
        'array-bracket-spacing': [2, 'never'],
        'brace-style': 2,
        camelcase: [2, { properties: 'never' }],
        'comma-dangle': 2,
        'comma-spacing': 2,
        'comma-style': 2,
        'consistent-this': 2,
        curly: 2,
        'dot-notation': 2,
        indent: [2, 4, { SwitchCase: 1 }],
        'eol-last': 2,
        'key-spacing': 2,
        'keyword-spacing': 2,
        'max-nested-callbacks': [2, { max: 3 }],
        'max-statements-per-line': [2, { max: 1 }],
        'new-cap': 2,
        'new-parens': 2,
        'no-array-constructor': 2,
        'no-extra-parens': [2, 'functions'],
        'no-bitwise': 2,
        'no-lonely-if': 2,
        'no-mixed-operators': 2,
        'no-multi-spaces': 2,
        'no-multi-str': 2,
        'no-multiple-empty-lines': [2, { max: 1 }],
        'no-nested-ternary': 2,
        'no-negated-condition': 2,
        'no-new-object': 2,
        'no-spaced-func': 2,
        'no-tabs': 2,
        'no-trailing-spaces': 2,
        'no-underscore-dangle': 2,
        'no-whitespace-before-property': 2,
        'object-curly-spacing': [2, 'always'],
        'one-var': [2, 'never'],
        'one-var-declaration-per-line': 2,
        'padded-blocks': [2, 'never'],
        'quote-props': [2, 'as-needed'],
        quotes: [2, 'single'],
        semi: 2,
        'semi-spacing': 2,
        'space-before-blocks': 2,
        'space-before-function-paren': 2,
        'space-in-parens': [2, 'never'],
        'space-infix-ops': 2,
        'space-unary-ops': [2, { words: true, nonwords: false }],
        'spaced-comment': 2,
        'wrap-iife': 2
        // TODO: Add `requirePaddingNewLinesAfterBlocks` rule once it gets implemented
        // since we had it in JSCS: https://github.com/eslint/eslint/issues/3092

        // ECMAScript 6
        // TODO: set rules for ECMAScript 6 http://eslint.org/docs/rules/#ecmascript-6
    }
};
<commit_msg>Add "root": true<commit_after>'use strict';

module.exports = {
    root: true,
    parserOptions: {
        // sourceType: 'module',
        ecmaFeatures: {
            jsx: true,
            experimentalObjectRestSpread: true
        }
    },
    env: {
        node: true,
        es6: true
    },
    globals: {
        logger: false
    },
    extends: 'eslint:recommended',
    rules: {
        // Possible Errors
        'no-console': [1, { allow: ['warn', 'error'] }], // overrides eslint:recommended config (2)

        // Best Practices
        eqeqeq: 2,
        'guard-for-in': 2,
        'no-caller': 2,
        'no-eval': 2,
        'no-extend-native': 2,
        'no-extra-bind': 2,
        'no-floating-decimal': 2,
        'no-implied-eval': 2,
        'no-loop-func': 2,
        'no-new-wrappers': 2,
        'no-return-assign': 2,
        'no-script-url': 2,
        'no-self-compare': 2,
        'no-sequences': 2,
        'no-throw-literal': 2,
        'no-unused-expressions': [2, { allowShortCircuit: true, allowTernary: true }],
        'no-useless-call': 2,
        'no-useless-concat': 2,
        'no-useless-escape': 2,
        'no-void': 2,
        yoda: 2,

        // Strict Mode
        strict: 2,

        // Variables
        'no-label-var': 2,
        'no-unused-vars': [2, { args: 'none' }],
        'no-shadow-restricted-names': 2,
        'no-undef-init': 2,
        'no-use-before-define': 2,

        // Node.js and CommonJS
        // TODO: Set rules for Node.js and CommonJS http://eslint.org/docs/rules/#nodejs-and-commonjs

        // Stylistic Issues
        'array-bracket-spacing': [2, 'never'],
        'brace-style': 2,
        camelcase: [2, { properties: 'never' }],
        'comma-dangle': 2,
        'comma-spacing': 2,
        'comma-style': 2,
        'consistent-this': 2,
        curly: 2,
        'dot-notation': 2,
        indent: [2, 4, { SwitchCase: 1 }],
        'eol-last': 2,
        'key-spacing': 2,
        'keyword-spacing': 2,
        'max-nested-callbacks': [2, { max: 3 }],
        'max-statements-per-line': [2, { max: 1 }],
        'new-cap': 2,
        'new-parens': 2,
        'no-array-constructor': 2,
        'no-extra-parens': [2, 'functions'],
        'no-bitwise': 2,
        'no-lonely-if': 2,
        'no-mixed-operators': 2,
        'no-multi-spaces': 2,
        'no-multi-str': 2,
        'no-multiple-empty-lines': [2, { max: 1 }],
        'no-nested-ternary': 2,
        'no-negated-condition': 2,
        'no-new-object': 2,
        'no-spaced-func': 2,
        'no-tabs': 2,
        'no-trailing-spaces': 2,
        'no-underscore-dangle': 2,
        'no-whitespace-before-property': 2,
        'object-curly-spacing': [2, 'always'],
        'one-var': [2, 'never'],
        'one-var-declaration-per-line': 2,
        'padded-blocks': [2, 'never'],
        'quote-props': [2, 'as-needed'],
        quotes: [2, 'single'],
        semi: 2,
        'semi-spacing': 2,
        'space-before-blocks': 2,
        'space-before-function-paren': 2,
        'space-in-parens': [2, 'never'],
        'space-infix-ops': 2,
        'space-unary-ops': [2, { words: true, nonwords: false }],
        'spaced-comment': 2,
        'wrap-iife': 2
        // TODO: Add `requirePaddingNewLinesAfterBlocks` rule once it gets implemented
        // since we had it in JSCS: https://github.com/eslint/eslint/issues/3092

        // ECMAScript 6
        // TODO: set rules for ECMAScript 6 http://eslint.org/docs/rules/#ecmascript-6
    }
};
<|endoftext|>


<commit_before>require('dotenv').config();
const express = require('express');
const graphqlHTTP = require('express-graphql');
const graphql = require('graphql');
const session = require('express-session');
const BasecampAuth = require('./lib/basecamp-auth.js');
const BasecampClient = require('./lib/basecamp-client.js');
const Schema = require('./graphql/schema.js');
const Resolver = require('./graphql/resolver.js');

const client_id = process.env.CLIENT_ID;
const client_secret = process.env.CLIENT_SECRET;
const basecampAuth = new BasecampAuth(client_id, client_secret);

// Construct a schema, using GraphQL schema language

const app = express();
app.set('port', (process.env.PORT || 5000));
app.use(session({ secret: 'basecamp', cookie: { maxAge: 60000 }}));

app.get('/', function (req, res) {
  res.send('Authenticate with Basecamp 3');
});

app.get('/auth', function (request, response) {
  const authCode = request.query.code;
  const session = request.session;
  basecampAuth.createToken(authCode).then(token => {
    request.session.oAuth = token;
    response.redirect('/graphql');
  });
});

app.use('/graphql', graphqlHTTP((request) => ({
  schema: Schema,
  rootValue: {},
  context: {
    resolver: new Resolver(new BasecampClient(basecampAuth, request.session.oAuth, 'Basecamp 3 GraphQL wrapper (oriol@codegram.com)'))
  },
  graphiql: true,
})));

app.listen(app.get('port'), function() {
  console.log('Running a GraphQL API server on port', app.get('port'));
});
<commit_msg>Fix session configuration<commit_after>require('dotenv').config();
const express = require('express');
const graphqlHTTP = require('express-graphql');
const graphql = require('graphql');
const session = require('express-session');
const BasecampAuth = require('./lib/basecamp-auth.js');
const BasecampClient = require('./lib/basecamp-client.js');
const Schema = require('./graphql/schema.js');
const Resolver = require('./graphql/resolver.js');

const client_id = process.env.CLIENT_ID;
const client_secret = process.env.CLIENT_SECRET;
const basecampAuth = new BasecampAuth(client_id, client_secret);

// Construct a schema, using GraphQL schema language

const app = express();
app.set('port', (process.env.PORT || 5000));
app.use(session({
  secret: 'basecamp',
  resave: true,
  rolling: true,
  saveUninitialized: false,
  cookie: {
    maxAge: 3600000
  }
}));

app.get('/', function (req, res) {
  res.send('Authenticate with Basecamp 3');
});

app.get('/auth', function (request, response) {
  const authCode = request.query.code;
  const session = request.session;
  basecampAuth.createToken(authCode).then(token => {
    request.session.oAuth = token;
    response.redirect('/graphql');
  });
});

app.use('/graphql', graphqlHTTP((request) => ({
  schema: Schema,
  rootValue: {},
  context: {
    resolver: new Resolver(new BasecampClient(basecampAuth, request.session.oAuth, 'Basecamp 3 GraphQL wrapper (oriol@codegram.com)'))
  },
  graphiql: true,
})));

app.listen(app.get('port'), function() {
  console.log('Running a GraphQL API server on port', app.get('port'));
});
<|endoftext|>


<commit_before>"use strict";

var END_DATE = new Date("Jul 5 2016");
var NEXT_YEAR = new Date("Jun 25 2017");
var DEFAULT_COORDS = { // Haifa
  "coords": {
    "latitude": 32.8167,
    "longitude": 34.9833,
  }
};

var DAY = "days";
var HR = "hours";
var MIN = "minutes";
var SEC = "seconds";

var UNIT_CONVERTER = {};

// times in ms
var UNIT_TIMES = {};
UNIT_TIMES[SEC] = 3000; // one second is too annoying
UNIT_TIMES[MIN] = 1000 * 60;
UNIT_TIMES[HR] = UNIT_TIMES[MIN] * 5; // one hour is too long
UNIT_TIMES[DAY] = UNIT_TIMES[HR] * 24;

// http://stackoverflow.com/questions/5915096/get-random-item-from-javascript-array
(function($) {
  $.rand = function(arg) {
    if ($.isArray(arg)) {
      return arg[$.rand(arg.length)];
    } else if (typeof arg === "number") {
      return Math.floor(Math.random() * arg);
    } else {
      return 4; // chosen by fair dice roll
    }
  };
})(jQuery);

function getCoords(callback) {
  geolocator.locate(callback, function(error) {
    callback(DEFAULT_COORDS);
  }, true, { // fallback to IP is true
    "timeout": 5000
  });
}

function displayDaySplit(split, klass) {
  $(klass).hide();
  $(klass + "-split1").html(split.time1 + " " + split.unit1);
  $(klass + "-split2").html(split.time2 + " " + split.unit2);
  $(klass).fadeIn("slow");
}

function displayTimeSplit(split, klass) {
  $(klass + "-split1").hide().html(split.time1 + " " + split.unit1).slideDown();
  $(klass + "-split2").hide().html(split.time2 + " " + split.unit2).slideDown();
}

function humanizeFloat(x) {
  return Math.round(x);
}

function humanizeUnit(val, unit) {
  if (val == 1) {
    unit = unit.slice(0, -1);
  }
  return unit;
}

function getTimeoutVal(unit) {
  var timeoutVal = UNIT_TIMES[unit];
  if (timeoutVal === undefined) {
    timeoutVal = 1000 * 60;
  }
  return timeoutVal;
}

/*
 * Returns an object containing
 * two times splitting the time left
 * into two parts.
 */
function getTimeUntil(endTime, unit) {
  var time1 = 0;
  var time2 = 0;
  var count = 0;
  var units = [HR, MIN, SEC];
  while ((time1 === 0 || time2 === 0) && count < 10) {
    unit = unit || $.rand(units);
    var remaining = timeLeft(endTime, unit);
    time1 = humanizeFloat($.rand(remaining));
    time2 = humanizeFloat(remaining - time1);
    count++;
    if (time1 === 0 && time2 === 0) {
      var index = units.indexOf(unit);
      if (index > -1) {
        units.splice(index, 1);
        count = 0;
      }
    }
  }
  return {
    "time1": time1,
    "time2": time2,
    "unit": unit,
    // for internationalization
    "unit1": humanizeUnit(time1, unit),
    "unit2": humanizeUnit(time2, unit),
  };
}

/*
 * Return the amount of time left between
 * now and `endTime` in the given units
 */
function timeLeft(endTime, unit) {
  var diff = endTime.getTime() - Date.now();
  return UNIT_CONVERTER[unit](diff);
}

/*
 * Returns either time until sunrise or
 * time until sunset depending on the current time
 * returns the correct class to apply to the `body`
 */
function getEndTimeData(position) {
  var sunTimes = SunCalc.getTimes(new Date(), position.coords.latitude, position.coords.longitude);
  var timeToSunset = timeLeft(sunTimes.sunsetStart, SEC);
  var timeToDawn = timeLeft(sunTimes.dawn, SEC);
  var endTimeData;
  if (timeToSunset >= 0 && timeToDawn <= 0) {
    endTimeData = {
      "endTimeKlass": "sunset",
      "endTime": sunTimes.sunsetStart,
      "endTimeText": "until sunset.",
    };
  } else {
    endTimeData = {
      "endTimeKlass": "dawn",
      "endTime": sunTimes.dawn,
      "endTimeText": "until dawn.",
    };
  }
  if (timeToSunset < 0 && timeToDawn < 0) { // dawn the next day
    var sunTimes = SunCalc.getTimes(new Date(new Date().getTime() + 24 * 60 * 60 * 1000), position.coords.latitude, position.coords.longitude);
    endTimeData.endTime = sunTimes.dawn;
  }
  return endTimeData;
}

function inSeconds(diff) {
  return diff / 1000;
}

function inMinutes(diff) {
  return inSeconds(diff) / 60;
}

function inHours(diff) {
  return inMinutes(diff) / 60;
}

function inDays(diff) {
  return inHours(diff) / 24;
}

function displayTimes(position) {
  $(".waiting").hide();
  $(".container").show();

  var daySplit = getTimeUntil(END_DATE, DAY);
  displayDaySplit(daySplit, ".daySplit");

  var endTimeData = getEndTimeData(position);
  var timeSplit = getTimeUntil(endTimeData.endTime);
  displayTimeSplit(timeSplit, ".timeSplit");

  $("body").removeClass().addClass(endTimeData.endTimeKlass);
  $(".timeSplit-val").html(endTimeData.endTimeText);

  // update display after unit units
  setTimeout(function() {
    displayTimes(position);
  }, getTimeoutVal(timeSplit.unit));
}

function displayNextYear() {
  $(".waiting").hide();
  var daySplit = getTimeUntil(NEXT_YEAR, DAY);
  $(".daySplit").hide();
  displayTimeSplit(daySplit, ".timeSplit");
  $(".timeSplit-val").text("until Ramadan begins.");
}

$(document).ready(function() {
  UNIT_CONVERTER[DAY] = inDays;
  UNIT_CONVERTER[HR] = inHours;
  UNIT_CONVERTER[MIN] = inMinutes;
  UNIT_CONVERTER[SEC] = inSeconds;
  if (Date.now() > END_DATE) {
    displayNextYear();
  } else {
    $(".container").hide();
    getCoords(displayTimes);
  }
  loadSharing();
  setTimeout(function() {
    $(".subshare").fadeIn();
  }, 2500);
});
<commit_msg>date update<commit_after>"use strict";

var END_DATE = new Date("Jun 24 2017");
var NEXT_YEAR = new Date("May 15 2017");
var DEFAULT_COORDS = { // Haifa
  "coords": {
    "latitude": 32.8167,
    "longitude": 34.9833,
  }
};

var DAY = "days";
var HR = "hours";
var MIN = "minutes";
var SEC = "seconds";

var UNIT_CONVERTER = {};

// times in ms
var UNIT_TIMES = {};
UNIT_TIMES[SEC] = 3000; // one second is too annoying
UNIT_TIMES[MIN] = 1000 * 60;
UNIT_TIMES[HR] = UNIT_TIMES[MIN] * 5; // one hour is too long
UNIT_TIMES[DAY] = UNIT_TIMES[HR] * 24;

// http://stackoverflow.com/questions/5915096/get-random-item-from-javascript-array
(function($) {
  $.rand = function(arg) {
    if ($.isArray(arg)) {
      return arg[$.rand(arg.length)];
    } else if (typeof arg === "number") {
      return Math.floor(Math.random() * arg);
    } else {
      return 4; // chosen by fair dice roll
    }
  };
})(jQuery);

function getCoords(callback) {
  geolocator.locate(callback, function(error) {
    callback(DEFAULT_COORDS);
  }, true, { // fallback to IP is true
    "timeout": 5000
  });
}

function displayDaySplit(split, klass) {
  $(klass).hide();
  $(klass + "-split1").html(split.time1 + " " + split.unit1);
  $(klass + "-split2").html(split.time2 + " " + split.unit2);
  $(klass).fadeIn("slow");
}

function displayTimeSplit(split, klass) {
  $(klass + "-split1").hide().html(split.time1 + " " + split.unit1).slideDown();
  $(klass + "-split2").hide().html(split.time2 + " " + split.unit2).slideDown();
}

function humanizeFloat(x) {
  return Math.round(x);
}

function humanizeUnit(val, unit) {
  if (val == 1) {
    unit = unit.slice(0, -1);
  }
  return unit;
}

function getTimeoutVal(unit) {
  var timeoutVal = UNIT_TIMES[unit];
  if (timeoutVal === undefined) {
    timeoutVal = 1000 * 60;
  }
  return timeoutVal;
}

/*
 * Returns an object containing
 * two times splitting the time left
 * into two parts.
 */
function getTimeUntil(endTime, unit) {
  var time1 = 0;
  var time2 = 0;
  var count = 0;
  var units = [HR, MIN, SEC];
  while ((time1 === 0 || time2 === 0) && count < 10) {
    unit = unit || $.rand(units);
    var remaining = timeLeft(endTime, unit);
    time1 = humanizeFloat($.rand(remaining));
    time2 = humanizeFloat(remaining - time1);
    count++;
    if (time1 === 0 && time2 === 0) {
      var index = units.indexOf(unit);
      if (index > -1) {
        units.splice(index, 1);
        count = 0;
      }
    }
  }
  return {
    "time1": time1,
    "time2": time2,
    "unit": unit,
    // for internationalization
    "unit1": humanizeUnit(time1, unit),
    "unit2": humanizeUnit(time2, unit),
  };
}

/*
 * Return the amount of time left between
 * now and `endTime` in the given units
 */
function timeLeft(endTime, unit) {
  var diff = endTime.getTime() - Date.now();
  return UNIT_CONVERTER[unit](diff);
}

/*
 * Returns either time until sunrise or
 * time until sunset depending on the current time
 * returns the correct class to apply to the `body`
 */
function getEndTimeData(position) {
  var sunTimes = SunCalc.getTimes(new Date(), position.coords.latitude, position.coords.longitude);
  var timeToSunset = timeLeft(sunTimes.sunsetStart, SEC);
  var timeToDawn = timeLeft(sunTimes.dawn, SEC);
  var endTimeData;
  if (timeToSunset >= 0 && timeToDawn <= 0) {
    endTimeData = {
      "endTimeKlass": "sunset",
      "endTime": sunTimes.sunsetStart,
      "endTimeText": "until sunset.",
    };
  } else {
    endTimeData = {
      "endTimeKlass": "dawn",
      "endTime": sunTimes.dawn,
      "endTimeText": "until dawn.",
    };
  }
  if (timeToSunset < 0 && timeToDawn < 0) { // dawn the next day
    var sunTimes = SunCalc.getTimes(new Date(new Date().getTime() + 24 * 60 * 60 * 1000), position.coords.latitude, position.coords.longitude);
    endTimeData.endTime = sunTimes.dawn;
  }
  return endTimeData;
}

function inSeconds(diff) {
  return diff / 1000;
}

function inMinutes(diff) {
  return inSeconds(diff) / 60;
}

function inHours(diff) {
  return inMinutes(diff) / 60;
}

function inDays(diff) {
  return inHours(diff) / 24;
}

function displayTimes(position) {
  $(".waiting").hide();
  $(".container").show();

  var daySplit = getTimeUntil(END_DATE, DAY);
  displayDaySplit(daySplit, ".daySplit");

  var endTimeData = getEndTimeData(position);
  var timeSplit = getTimeUntil(endTimeData.endTime);
  displayTimeSplit(timeSplit, ".timeSplit");

  $("body").removeClass().addClass(endTimeData.endTimeKlass);
  $(".timeSplit-val").html(endTimeData.endTimeText);

  // update display after unit units
  setTimeout(function() {
    displayTimes(position);
  }, getTimeoutVal(timeSplit.unit));
}

function displayNextYear() {
  $(".waiting").hide();
  var daySplit = getTimeUntil(NEXT_YEAR, DAY);
  $(".daySplit").hide();
  displayTimeSplit(daySplit, ".timeSplit");
  $(".timeSplit-val").text("until Ramadan begins.");
}

$(document).ready(function() {
  UNIT_CONVERTER[DAY] = inDays;
  UNIT_CONVERTER[HR] = inHours;
  UNIT_CONVERTER[MIN] = inMinutes;
  UNIT_CONVERTER[SEC] = inSeconds;
  if (Date.now() > END_DATE) {
    displayNextYear();
  } else {
    $(".container").hide();
    getCoords(displayTimes);
  }
  loadSharing();
  setTimeout(function() {
    $(".subshare").fadeIn();
  }, 2500);
});
<|endoftext|>


<commit_before>const Discord = require("discord.js");
const client = new Discord.Client();
const YTDL = require("ytdl-core");

// Get authentication data
try {
	var AuthDetails = require("./auth.json");
} catch (e){
	console.log("Please create an auth.json like auth.json.example with a bot token or an email and password.\n"+e.stack);
	process.exit();
}

if(AuthDetails.bot_token){
	client.login(AuthDetails.bot_token);
    var bot_token = AuthDetails.bot_token;
}

if(AuthDetails.owner_id){
	var owner_id = AuthDetails.owner_id
} else {
	console.log("No owner id set in auth.json!");
}

if(AuthDetails.prefix){
	var prefix = AuthDetails.prefix
} else {
	console.log("No prefix set in auth.json!");
}
function play(connection, message) {
	var server = servers[message.guild.id];

	server.dispatcher = connection.playStream(YTDL(server.queue[0], {filter: "audioonly"}));

	server.queue.shift();

	server.dipatcher.on("end", function() {
	  if(server.queue[0]) play(connection, message);
	  else connection.disconnect();
})}

var version = "v0.3"

var servers = {};

client.on("ready", () => {
    client.fetchUser(owner_id)
    var owner = client.users.get(owner_id);
	console.log("\n===============================\n")
	console.log(`PIXABOT`)
    console.log(`Logged in as ${client.user.username}`);
    console.log("The bot is ready! Currently on:");
    console.log(client.guilds.size + " servers");
    console.log(client.channels.size + " channels");
    console.log("Current prefix: " + prefix);
    console.log("Owner: " + owner.tag);
	console.log("\n===============================\n")
});

client.on("guildCreate", guild => {
	console.log(`New guild joined ${guild.name}`);
});

client.on("guildDelete", guild => {
	  console.log(`I have been removed from ${guild.name}`);
});

client.on("disconnected", function () {
	  console.log("The bot is now shut down.");
	  process.exit(1);
});

client.on("message", function(message) {

    if (message.author.equals(client.user)) return;

    if (!message.content.startsWith(prefix)) return;

    var args = message.content.substring(prefix.length).split(" ");
    var haveMatched=true;

    switch (args[0]) {

        //ping command
        case "ping":
            var m = message.channel.send(":hourglass: *Testing connectivity…*").then(m => {
            var embed = new Discord.RichEmbed()
           	.setColor("#940000")
           	.setAuthor("Pong!", "https://cdn.discordapp.com/attachments/347288279357456387/348647441815306241/ping.png")
	     	.setDescription(`Response time: ${m.createdTimestamp - message.createdTimestamp}ms`)
           	.setFooter("Requested by " + message.author.tag, message.author.displayAvatarURL)
           	.setTimestamp()
            m.delete()
            message.channel.send({embed})
            });
            break;

        // about command
        case "about":
            var embed = new Discord.RichEmbed()
	        .setColor("#940000")
            .setAuthor("About PixaBot", "https://cdn.discordapp.com/attachments/347288279357456387/348643671002054657/about.png")
			.setDescription("PixaBot is a Discord bot that features games, image manipulation, moderation and music commands written in JavaScript.")
			.setThumbnail("https://media.discordapp.net/attachments/347288279357456387/348940216242929664/Untitled.jpg")
           	.setFooter("Requested by " + message.author.tag, message.author.displayAvatarURL)
           	.setTimestamp()
            message.channel.send({embed});
            break;

        // version command
        case "version":
            var embed = new Discord.RichEmbed()
	        .setColor("#940000")
            .setAuthor("Version", "https://cdn.discordapp.com/attachments/347288279357456387/348642213582077953/ver.png")
            .setDescription("The current version is " + version + ".")
           	.setFooter("Requested by " + message.author.tag, message.author.displayAvatarURL)
           	.setTimestamp()
            message.channel.send({embed});
            break;

        // kick command
        case "kick":
		    message.channel.send("Coming Soon!")
		break;

        // ban command
        case "ban":
            message.channel.send("Coming Soon!")
            break;

        // shutdown command
        case "shutdown":
            if (message.author.id != owner_id) {
                return;
            } else {
                var embed = new Discord.RichEmbed()
                .setColor("#940000")
                .setAuthor("Shutting down…", "https://cdn.discordapp.com/attachments/347288279357456387/348594144790183937/power.png")
                .setDescription("Please wait while the bot system is currently shutting down.")
                .setFooter("Requested by " + message.author.tag, message.author.displayAvatarURL)
                .setTimestamp()
                message.channel.send({embed});
                client.destroy((err) => {
                console.log(err);
                    });
                console.log("The bot is now shut down.");
                setTimeout(function(){
                    process.exit(0);
                }, 2000)
            }
            break;
                //exit node.js without an error

        // help command
        case "help":
            var embed = new Discord.RichEmbed()
            .setColor("#940000")
            .setAuthor("PixaBot Help Guide", "https://cdn.discordapp.com/attachments/347288279357456387/348643679373754369/help.png")
            .setDescription("Here are my available commands. To execute one of my commands, my prefix is `px;`.\n\n**Parameters:**\n< > - Required\n[ ] - Optional".replace('px;', prefix))
            .addField("General Commands", "`about` - Information about PixaBot.\n`help` - Displays the PixaBot's Help Guide, which is *this* one.\n`ping` - Test a connection to PixaBot.\n`version` - Displays the PixaBot's current version.", true)
            .addField("Fun Commands", "`8ball <question>` - Ask a question to a bot, and what does the bot say…?\n`piko` - Shows the picture of Piko Kugihara, an anime original character serves as a mascot of PixaBot.\n`say <message>` - Say something as a bot!", true)
			.addField("Music Commands", "`play <URL>` - Plays a music.\n`skip` - Skips the current song.\n`stop` - Stops the music and disconnects from the voice channel.", true)
            .addField("Moderation Commands", "`ban <mention> <reason>` - Bans the user out of this server.\n`kick <mention> <reason>` - Kicks a member.", true)
            .setFooter("Requested by " + message.author.tag, message.author.displayAvatarURL)
            .setTimestamp()
            if (message.author.id == owner_id) {
                embed.addField("Commands for the Bot Owner", "`shutdown` - De-initialize the bot.", true)
            }
            message.channel.send({embed});
            break;

		// say command
	    case "say":
			try {
                    if(message.content.length < prefix.length + 4) {
                        message.channel.send("Come on, say something!")
                        break
                    } else {
							message.channel.send(message.content.replace(prefix + "say ", ''));
					message.delete();
							}
					} catch(err) {
						message.channel.send(error)
					}
            break;

        // 8ball command
        case "8ball":
			if(message.content.length < prefix.length + 6) {
                message.channel.send("Go ahead, ask it anything.")
                break
            } else {
                var choices = ["Yes.", "No.", "Maybe.", "It could be true.", "I guess so.", "Tell your doctor to find out.", "No, I'm not!", "I don't like you!"]
                var rand = choices[Math.floor(Math.random() * choices.length)];
                message.reply(rand)
                break
            }

        // piko command
		case "piko":
            var embed = new Discord.RichEmbed()
				.setColor("#940000")
				.setAuthor("Piko-chan!", "https://cdn.discordapp.com/attachments/347288279357456387/349276625575346179/dm.png")
				.setDescription("Sent you a DM for the mascot!")
				.setFooter("Requested by " + message.author.tag, message.author.displayAvatarURL)
				.setTimestamp()
		    message.channel.send({embed});
            message.author.send("Here's the mascot, Piko Kugihara (釘原 飛鼓), an anime OC made by YottabyteINSIDE™, also known as Jigs.", { files: [ 'https://cdn.discordapp.com/attachments/347282801021943811/348985242385907714/pixa_by_exjageroo-dbka7oa.png' ] });
            break
		case "play":
			if (!args[1]) {
            var embed = new Discord.RichEmbed()
				.setColor("#940000")
				.setAuthor("Music Player", "https://cdn.discordapp.com/attachments/347288279357456387/349279668639367168/music.png")
				.setTitle("No video URL specified.")
				.setDescription("Please provide a link.")
				.setFooter("Requested by " + message.author.tag, message.author.displayAvatarURL)
				.setTimestamp()
				message.channel.sendMessage({embed});
				return
			 }

			 if (!message.member.voiceChannel) {
            var embed = new Discord.RichEmbed()
				.setColor("#940000")
				.setAuthor("Music Player", "https://cdn.discordapp.com/attachments/347288279357456387/349279668639367168/music.png")
				.setTitle("You are not in the voice channel.")
				.setDescription("Please join the voice channel to play music.")
				.setFooter("Requested by " + message.author.tag, message.author.displayAvatarURL)
				.setTimestamp()
				message.channel.sendMessage({embed});
				return
			 }

			if (!servers[message.guild.id]) servers[message.guild.id] = {
				queue: []
			}

		 var server = servers[message.guild.id];

		  server.queue.push(args[1]);

			 if (!message.guild.voiceConnection) message.member.voiceChannel.join().then(function(connection) {
			 play(connection, message);
			})
		break;
		case "skip":
			var server = servers[message.guild.id];

		 if (server.dispatcher) server.dispatcher.end();
		 break;
		 case "stop":
		   var server = servers[message.guild.id];

		   if (message.guild.voiceConnection) message.guild.voiceConnection.disconnect();
			var embed = new Discord.RichEmbed()
				.setColor("#940000")
				.setAuthor("Music Player", "https://cdn.discordapp.com/attachments/347288279357456387/349279668639367168/music.png")
				.setTitle("Music stopped.")
				.setDescription("I stopped the music and I left the voice channel.")
				.setFooter("Requested by " + message.author.tag, message.author.displayAvatarURL)
				.setTimestamp()
				message.channel.sendMessage({embed});
		   break;

        case "eval":
		let msg = message
		let bot = client
	let args = msg.content.split(' ')
        let variable = args.shift()
	if (message.author.id != owner_id && message.author.id != AuthDetails.rain && message.author.id != AuthDetails.yottabyte && message.author.id != AuthDetails.terax) return;
	const clean = text => {
  if (typeof(text) === "string")
    return text.replace(/`/g, "`" + String.fromCharCode(8203)).replace(/@/g, "@" + String.fromCharCode(8203));
  else
      return text;
}
var guild = msg.guild
    try {
      const code = args.join(" ");
      let evaled = eval(code);

      if (typeof evaled !== "string")
        evaled = require("util").inspect(evaled);
	  message.delete()
	  if (!code) return msg.author.send(":warning: *Eval failed. Please use the specified arguments!*");
	  const embed = new Discord.RichEmbed()
	  .setAuthor("Eval Results", "https://cdn.discordapp.com/attachments/347288279357456387/349554608068362243/eval.png")
	  .setFooter("Requested by " + message.author.tag, message.author.displayAvatarURL)
	  .setTimestamp()
	  .setColor("#940000")
	  .addField("📥 Input", args.join(' '))
	  .addField("📤 Output", "```x1\n" + clean(evaled) + "```")
      message.channel.send({embed});
	  console.log("========================================================================================\nEVAL RESULTS\nINPUT:\n" + args.join(' ') + "\nOUTPUT:\n" + clean(evaled) + "\n========================================================================================\n");
    } catch (err) {
	message.delete()
	  const embed = new Discord.RichEmbed()
	  .setAuthor("Eval Results", "https://cdn.discordapp.com/attachments/347288279357456387/349554608068362243/eval.png")
	  .setTimestamp()
	  .setFooter("Requested by " + message.author.tag, message.author.displayAvatarURL)
	  .setColor("#940000")
	  .setDescription("ERROR")
	  .addField("📥 Input", args.join(' '))
	  .addField("📤 Output", "```x1\n" + clean(err) + "```")
      msg.author.send({embed});
      console.log("========================================================================================\nEVAL RESULTS\nERROR\n\nINPUT:\n" + args.join(' ') + "\nOUTPUT:\n" + clean(err) + "\n========================================================================================\n");
    }
    break

		default:
            haveMatched = false
    }
/*
        // command that is invalid.
            var embed = new Discord.RichEmbed()
				.setColor("#940000")
				.setAuthor("Unknown Command", "https://cdn.discordapp.com/attachments/347288279357456387/349278178499493888/unknowncmd.png")
				.setTitle("The specified command that you are trying to execute is invalid.")
				.setDescription("Use `px;help` to view my available commands.".replace('px;', prefix))
				.setFooter("Requested by " + message.author.tag, message.author.displayAvatarURL)
				.setTimestamp()
            message.channel.send({embed})
			break;
}
*/
	//eval command
if (haveMatched){
    console.log(`[Command] ${message.author.id}/${message.author.username} (${message.content})`)
}
})
<commit_msg>Untagging the unknown command<commit_after>const Discord = require("discord.js");
const client = new Discord.Client();
const YTDL = require("ytdl-core");

// Get authentication data
try {
	var AuthDetails = require("./auth.json");
} catch (e){
	console.log("Please create an auth.json like auth.json.example with a bot token or an email and password.\n"+e.stack);
	process.exit();
}

if(AuthDetails.bot_token){
	client.login(AuthDetails.bot_token);
    var bot_token = AuthDetails.bot_token;
}

if(AuthDetails.owner_id){
	var owner_id = AuthDetails.owner_id
} else {
	console.log("No owner id set in auth.json!");
}

if(AuthDetails.prefix){
	var prefix = AuthDetails.prefix
} else {
	console.log("No prefix set in auth.json!");
}
function play(connection, message) {
	var server = servers[message.guild.id];

	server.dispatcher = connection.playStream(YTDL(server.queue[0], {filter: "audioonly"}));

	server.queue.shift();

	server.dipatcher.on("end", function() {
	  if(server.queue[0]) play(connection, message);
	  else connection.disconnect();
})}

var version = "v0.3"

var servers = {};

client.on("ready", () => {
    client.fetchUser(owner_id)
    var owner = client.users.get(owner_id);
	console.log("\n===============================\n")
	console.log(`PIXABOT`)
    console.log(`Logged in as ${client.user.username}`);
    console.log("The bot is ready! Currently on:");
    console.log(client.guilds.size + " servers");
    console.log(client.channels.size + " channels");
    console.log("Current prefix: " + prefix);
    console.log("Owner: " + owner.tag);
	console.log("\n===============================\n")
});

client.on("guildCreate", guild => {
	console.log(`New guild joined ${guild.name}`);
});

client.on("guildDelete", guild => {
	  console.log(`I have been removed from ${guild.name}`);
});

client.on("disconnected", function () {
	  console.log("The bot is now shut down.");
	  process.exit(1);
});

client.on("message", function(message) {

    if (message.author.equals(client.user)) return;

    if (!message.content.startsWith(prefix)) return;

    var args = message.content.substring(prefix.length).split(" ");
    var haveMatched=true;

    switch (args[0]) {

        //ping command
        case "ping":
            var m = message.channel.send(":hourglass: *Testing connectivity…*").then(m => {
            var embed = new Discord.RichEmbed()
           	.setColor("#940000")
           	.setAuthor("Pong!", "https://cdn.discordapp.com/attachments/347288279357456387/348647441815306241/ping.png")
	     	.setDescription(`Response time: ${m.createdTimestamp - message.createdTimestamp}ms`)
           	.setFooter("Requested by " + message.author.tag, message.author.displayAvatarURL)
           	.setTimestamp()
            m.delete()
            message.channel.send({embed})
            });
            break;

        // about command
        case "about":
            var embed = new Discord.RichEmbed()
	        .setColor("#940000")
            .setAuthor("About PixaBot", "https://cdn.discordapp.com/attachments/347288279357456387/348643671002054657/about.png")
			.setDescription("PixaBot is a Discord bot that features games, image manipulation, moderation and music commands written in JavaScript.")
			.setThumbnail("https://media.discordapp.net/attachments/347288279357456387/348940216242929664/Untitled.jpg")
           	.setFooter("Requested by " + message.author.tag, message.author.displayAvatarURL)
           	.setTimestamp()
            message.channel.send({embed});
            break;

        // version command
        case "version":
            var embed = new Discord.RichEmbed()
	        .setColor("#940000")
            .setAuthor("Version", "https://cdn.discordapp.com/attachments/347288279357456387/348642213582077953/ver.png")
            .setDescription("The current version is " + version + ".")
           	.setFooter("Requested by " + message.author.tag, message.author.displayAvatarURL)
           	.setTimestamp()
            message.channel.send({embed});
            break;

        // kick command
        case "kick":
		    message.channel.send("Coming Soon!")
		break;

        // ban command
        case "ban":
            message.channel.send("Coming Soon!")
            break;

        // shutdown command
        case "shutdown":
            if (message.author.id != owner_id) {
                return;
            } else {
                var embed = new Discord.RichEmbed()
                .setColor("#940000")
                .setAuthor("Shutting down…", "https://cdn.discordapp.com/attachments/347288279357456387/348594144790183937/power.png")
                .setDescription("Please wait while the bot system is currently shutting down.")
                .setFooter("Requested by " + message.author.tag, message.author.displayAvatarURL)
                .setTimestamp()
                message.channel.send({embed});
                client.destroy((err) => {
                console.log(err);
                    });
                console.log("The bot is now shut down.");
                setTimeout(function(){
                    process.exit(0);
                }, 2000)
            }
            break;
                //exit node.js without an error

        // help command
        case "help":
            var embed = new Discord.RichEmbed()
            .setColor("#940000")
            .setAuthor("PixaBot Help Guide", "https://cdn.discordapp.com/attachments/347288279357456387/348643679373754369/help.png")
            .setDescription("Here are my available commands. To execute one of my commands, my prefix is `px;`.\n\n**Parameters:**\n< > - Required\n[ ] - Optional".replace('px;', prefix))
            .addField("General Commands", "`about` - Information about PixaBot.\n`help` - Displays the PixaBot's Help Guide, which is *this* one.\n`ping` - Test a connection to PixaBot.\n`version` - Displays the PixaBot's current version.", true)
            .addField("Fun Commands", "`8ball <question>` - Ask a question to a bot, and what does the bot say…?\n`piko` - Shows the picture of Piko Kugihara, an anime original character serves as a mascot of PixaBot.\n`say <message>` - Say something as a bot!", true)
			.addField("Music Commands", "`play <URL>` - Plays a music.\n`skip` - Skips the current song.\n`stop` - Stops the music and disconnects from the voice channel.", true)
            .addField("Moderation Commands", "`ban <mention> <reason>` - Bans the user out of this server.\n`kick <mention> <reason>` - Kicks a member.", true)
            .setFooter("Requested by " + message.author.tag, message.author.displayAvatarURL)
            .setTimestamp()
            if (message.author.id == owner_id) {
                embed.addField("Commands for the Bot Owner", "`shutdown` - De-initialize the bot.", true)
            }
            message.channel.send({embed});
            break;

		// say command
	    case "say":
			try {
                    if(message.content.length < prefix.length + 4) {
                        message.channel.send("Come on, say something!")
                        break
                    } else {
							message.channel.send(message.content.replace(prefix + "say ", ''));
					message.delete();
							}
					} catch(err) {
						message.channel.send(error)
					}
            break;

        // 8ball command
        case "8ball":
			if(message.content.length < prefix.length + 6) {
                message.channel.send("Go ahead, ask it anything.")
                break
            } else {
                var choices = ["Yes.", "No.", "Maybe.", "It could be true.", "I guess so.", "Tell your doctor to find out.", "No, I'm not!", "I don't like you!"]
                var rand = choices[Math.floor(Math.random() * choices.length)];
                message.reply(rand)
                break
            }

        // piko command
		case "piko":
            var embed = new Discord.RichEmbed()
				.setColor("#940000")
				.setAuthor("Piko-chan!", "https://cdn.discordapp.com/attachments/347288279357456387/349276625575346179/dm.png")
				.setDescription("Sent you a DM for the mascot!")
				.setFooter("Requested by " + message.author.tag, message.author.displayAvatarURL)
				.setTimestamp()
		    message.channel.send({embed});
            message.author.send("Here's the mascot, Piko Kugihara (釘原 飛鼓), an anime OC made by YottabyteINSIDE™, also known as Jigs.", { files: [ 'https://cdn.discordapp.com/attachments/347282801021943811/348985242385907714/pixa_by_exjageroo-dbka7oa.png' ] });
            break
		case "play":
			if (!args[1]) {
            var embed = new Discord.RichEmbed()
				.setColor("#940000")
				.setAuthor("Music Player", "https://cdn.discordapp.com/attachments/347288279357456387/349279668639367168/music.png")
				.setTitle("No video URL specified.")
				.setDescription("Please provide a link.")
				.setFooter("Requested by " + message.author.tag, message.author.displayAvatarURL)
				.setTimestamp()
				message.channel.sendMessage({embed});
				return
			 }

			 if (!message.member.voiceChannel) {
            var embed = new Discord.RichEmbed()
				.setColor("#940000")
				.setAuthor("Music Player", "https://cdn.discordapp.com/attachments/347288279357456387/349279668639367168/music.png")
				.setTitle("You are not in the voice channel.")
				.setDescription("Please join the voice channel to play music.")
				.setFooter("Requested by " + message.author.tag, message.author.displayAvatarURL)
				.setTimestamp()
				message.channel.sendMessage({embed});
				return
			 }

			if (!servers[message.guild.id]) servers[message.guild.id] = {
				queue: []
			}

		 var server = servers[message.guild.id];

		  server.queue.push(args[1]);

			 if (!message.guild.voiceConnection) message.member.voiceChannel.join().then(function(connection) {
			 play(connection, message);
			})
		break;
		case "skip":
			var server = servers[message.guild.id];

		 if (server.dispatcher) server.dispatcher.end();
		 break;
		 case "stop":
		   var server = servers[message.guild.id];

		   if (message.guild.voiceConnection) message.guild.voiceConnection.disconnect();
			var embed = new Discord.RichEmbed()
				.setColor("#940000")
				.setAuthor("Music Player", "https://cdn.discordapp.com/attachments/347288279357456387/349279668639367168/music.png")
				.setTitle("Music stopped.")
				.setDescription("I stopped the music and I left the voice channel.")
				.setFooter("Requested by " + message.author.tag, message.author.displayAvatarURL)
				.setTimestamp()
				message.channel.sendMessage({embed});
		   break;

        case "eval":
		let msg = message
		let bot = client
	let args = msg.content.split(' ')
        let variable = args.shift()
	if (message.author.id != owner_id && message.author.id != AuthDetails.rain && message.author.id != AuthDetails.yottabyte && message.author.id != AuthDetails.terax) return;
	const clean = text => {
  if (typeof(text) === "string")
    return text.replace(/`/g, "`" + String.fromCharCode(8203)).replace(/@/g, "@" + String.fromCharCode(8203));
  else
      return text;
}
var guild = msg.guild
    try {
      const code = args.join(" ");
      let evaled = eval(code);

      if (typeof evaled !== "string")
        evaled = require("util").inspect(evaled);
	  message.delete()
	  if (!code) return msg.author.send(":warning: *Eval failed. Please use the specified arguments!*");
	  const embed = new Discord.RichEmbed()
	  .setAuthor("Eval Results", "https://cdn.discordapp.com/attachments/347288279357456387/349554608068362243/eval.png")
	  .setFooter("Requested by " + message.author.tag, message.author.displayAvatarURL)
	  .setTimestamp()
	  .setColor("#940000")
	  .addField("📥 Input", args.join(' '))
	  .addField("📤 Output", "```x1\n" + clean(evaled) + "```")
      message.channel.send({embed});
	  console.log("========================================================================================\nEVAL RESULTS\nINPUT:\n" + args.join(' ') + "\nOUTPUT:\n" + clean(evaled) + "\n========================================================================================\n");
    } catch (err) {
	message.delete()
	  const embed = new Discord.RichEmbed()
	  .setAuthor("Eval Results", "https://cdn.discordapp.com/attachments/347288279357456387/349554608068362243/eval.png")
	  .setTimestamp()
	  .setFooter("Requested by " + message.author.tag, message.author.displayAvatarURL)
	  .setColor("#940000")
	  .setDescription("ERROR")
	  .addField("📥 Input", args.join(' '))
	  .addField("📤 Output", "```x1\n" + clean(err) + "```")
      msg.author.send({embed});
      console.log("========================================================================================\nEVAL RESULTS\nERROR\n\nINPUT:\n" + args.join(' ') + "\nOUTPUT:\n" + clean(err) + "\n========================================================================================\n");
    }
    break
	    // command that is invalid.
		default:
            haveMatched = false

            var embed = new Discord.RichEmbed()
				.setColor("#940000")
				.setAuthor("Unknown Command", "https://cdn.discordapp.com/attachments/347288279357456387/349278178499493888/unknowncmd.png")
				.setTitle("The specified command that you are trying to execute is invalid.")
				.setDescription("Use `px;help` to view my available commands.".replace('px;', prefix))
				.setFooter("Requested by " + message.author.tag, message.author.displayAvatarURL)
				.setTimestamp()
            message.channel.send({embed})
			break;
}
	//eval command
if (haveMatched){
    console.log(`[Command] ${message.author.id}/${message.author.username} (${message.content})`)
}
})
<|endoftext|>