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

'use strict';

var fs = require('fs');
var glob = require('glob');
var nconf = require('nconf');
var path = require('path');
var program = require('commander');
var prompt = require('prompt');
var qs = require('querystring');
var request = require('request');
var unzip = require('unzip');
var url = require('url');

var config = 'chatbot.json';

var sep = function (str) {
    return str ? '/' + str : '';
}

var composeUri = function (mode, botname, kind, filename) {
    var uri = {
	protocol: nconf.get('protocol'),
	hostname: nconf.get('hostname')
    }
    var path = mode;
    path += sep(conf_app_id());
    path += sep(botname);
    path += sep(kind);
    path += sep(filename);
    uri.pathname = path;
    return uri;
}

var composeParams = function (params) {
    params.user_key = conf_user_key();
    return params;
}

var listUri = function () {
    var uri = composeUri('bot', '', '', '');
    uri.query = composeParams({});
    return url.format(uri);
}

var botUri = function (botname) {
    var uri = composeUri('bot', botname, '', '');
    uri.query = composeParams({});
    return url.format(uri);
}

var fileUri = function (filename) {
    var ext = path.extname(filename);
    var base = path.basename(filename, ext);
    var kind = ext.slice(1);
    var botname = conf_botname();
    var uri;
    if (kind === 'pdefaults' || kind === 'properties')
	uri = composeUri('bot', botname, kind, '');
    else if (kind === 'map' || kind === 'set' || kind === 'substitution')
	uri = composeUri('bot', botname, kind, base);
    else if (kind === 'aiml')
	uri = composeUri('bot', botname, 'file', base + ext);
    else {
	console.log('illegal file name: ' + filename);
	return;
    }
    uri.query = composeParams({});
    return url.format(uri);
}

var zipUri = function () {
    var uri = composeUri('bot', conf_botname(), '', '');
    uri.query = composeParams({return: 'zip'});
    return url.format(uri);
}

var verifyUri = function () {
    var uri = composeUri('bot', conf_botname(), 'verify', '');
    uri.query = composeParams({});
    return url.format(uri);
}

var talkUri = function () {
    var uri = composeUri('talk', conf_botname(), '', '');
    return url.format(uri);
}

var okResp = function (error, response, body) {
    var jObj = JSON.parse(body);
    if (jObj.status === 'ok')
	console.log(jObj.status)
    else {
	console.log(jObj.message)
	if (jObj.results !== undefined)
	    console.log(JSON.stringify(jObj.results[0], null, 2))
    }
}

var deleteResp = function (error, response, body) {
    var jObj = JSON.parse(body);
    if (jObj.status === 'ok')
	console.log(jObj.status)
    else {
	console.log(jObj.message);
	var prop  = {
	    message: 'Re-enter the name of the bot to delete:',
	    name: 'botname',
	    required: true
	};
	prompt.get(prop, function (error, result) {
	    if (error) {
		console.log("aborted.");
		process.exit(2);
	    }
	    else {
		nconf.set('botname', result.botname);
		request.del(botUri(conf_botname()), deleteResp);
	    }
	});
    }
}

var retryOnFile = function (file, cb) {
    fs.exists(file, function (doesExist) {
	if (doesExist)
	    cb(file);
	else {
	    console.log('file not found');
	    if (!nconf.get('yes')) {
		var prop  = {
		    message: 'Re-enter the name of file to upload:',
		    name: 'input',
		    required: true
		};
		prompt.get(prop, function (error, result) {
		    if (error) {
			console.log("aborted.");
			process.exit(2);
		    }
		    else
			retryOnFile(result.input, cb);
		});
	    }
	}
    });
}

var removeResp = function (error, response, body) {
    var jObj = JSON.parse(body);
    if (jObj.status === 'ok')
	console.log(jObj.status)
    else {
	console.log("file not found");
	if (!nconf.get('yes')) {
	    var prop  = {
		message: 'Re-enter the name of file to remove:',
		name: 'filename',
		required: true
	    };
	    prompt.get(prop, function (error, result) {
		if (error) {
		    console.log("aborted.");
		    process.exit(2);
		}
		else {
		    request.del(fileUri(result.filename), removeResp);
		}
	    });
	}
    }
}

var listBotResp = function (error, response, body) {
    var jObj = JSON.parse(body);
    if (response.statusCode === 200) {
	jObj.forEach (function (entry) {
	    console.log(entry.botname);
	});
    }
    else
	console.log(jObj.message)
}

var fileList = function (jObj) {
    var files = [];
    if (jObj.properties.length) files.push(jObj.botname + ".properties");
    if (jObj.pdefaults.length) files.push(jObj.botname + ".pdefaults");
    jObj.files.forEach (function (entry) { files.push(entry.name); });
    jObj.sets.forEach (function (entry) { files.push(entry.name + ".set"); });
    jObj.maps.forEach (function (entry) { files.push(entry.name + ".map"); });
    jObj.substitutions.forEach (function (entry) { files.push(entry.name + ".substitution"); });
    return files;
}

var listFileResp = function (error, response, body) {
    var jObj = JSON.parse(body);
    if (response.statusCode === 200)
	fileList(jObj).forEach (function (file) { console.log(file); });
    else
	console.log(jObj.message)
}

var pullResp = function (error, response, body) {
    var jObj = JSON.parse(body);
    if (response.statusCode === 200) {
	fileList(jObj).forEach (function (file) {
	    request.get(fileUri(file)).pipe(fs.createWriteStream(file));
	});
    }
    else
	console.log(jObj.message)
}

var talkResp = function (error, response, body) {
    var jObj = JSON.parse(body);
    if (jObj.status === 'ok') {
	nconf.set('sessionid', jObj.sessionid);
	if (nconf.get('extra') || nconf.get('trace'))
	    console.log(jObj);
	else {
	    jObj.responses.forEach (function (entry) {
		console.log(entry);
	    });
	}
    }
    else
	console.log(jObj.message)
}

var conf_app_id = function () {
    var app_id = nconf.get('app_id');
    if (app_id === undefined) {
	console.log('app_id required. use --app_id <app_id> or do init');
	process.exit(1);
    }
    return app_id;
}

var conf_user_key = function () {
    var user_key = nconf.get('user_key');
    if (user_key === undefined) {
	console.log('user_key required. use --user_key <user_key> or do init');
	process.exit(1);
    }
    return user_key;
}

var conf_botname = function () {
    var botname = nconf.get('botname');
    if (botname === undefined) {
	console.log('botname required. use --botname <botname> or do init');
	process.exit(1);
    }
    return botname;
}

var options = {
    protocol: 'https',
    hostname: 'aiaas.pandorabots.com',
    app_id: undefined,
    user_key: undefined,
    botname: undefined,
    client_name: undefined,
    sessionid: undefined,
    extra: undefined,
    reset: undefined,
    trace: undefined,
    reload: undefined,
    recent: undefined,
    all: undefined,
    yes: undefined
}

prompt.message = "";
prompt.delimiter = "";

nconf.env();
nconf.file({file: config});
nconf.defaults(options);

program
    .version('0.0.1')
    .usage('command [options] <file ...>')
    .option('-p, --protocol <protocol>', 'protocol')
    .option('-h, --hostname <hostname>', 'hostname')
    .option('-i, --app_id <app_id>', 'app_id')
    .option('-k, --user_key <user_key>', 'user_key')
    .option('-b, --botname <botname>', 'name of bot')
    .option('-c, --client_name <client_name>', 'name of client')
    .option('-s, --sessionid <sessionid>', 'session id of conversation')
    .option('-e, --extra', 'provides additional information with bot response')
    .option('-M, --reset', 'reset the bot memory')
    .option('-t, --trace', 'adds trace data into response')
    .option('-r, --reload', 'force system to reload bot')
    .option('-R, --recent', 'use most recently compiled version of bot')
    .option('-a, --all', 'downloads all files')
    .option('-y, --yes', 'do not prompt anything; assume yes to all yes/no queries')
    .parse(process.argv);

for (var key in options) {
    if (program[key])
	nconf.set(key, program[key]);
}

// Initialize
if (program.args[0] === 'init') {
    var props = [
	{message: 'app_id? (required)', name: 'app_id',
	    required: true, validator: /^[0-9a-z]+$/,
	    warning: 'app_id must consist of alphanumeric, lowercase characters'},
	{message: 'user_key? (required)', name: 'user_key',
	    required: true, validator: /^[0-9a-z]+$/,
	    warning: 'user_key must consist of alphanumeric, lowercase characters'},
	{message: 'botname? (recommended)', name: 'botname'},
	{message: 'hostname? (optional)', name: 'hostname'}
    ];
    prompt.get(props, function (error, result) {
	if (error) {
	    console.log("aborted.");
	    process.exit(2);
	}
	else {
	    var prop = {};
	    for (var key in result) {
		if (result[key]) {
		    prop[key] = result[key];
		}
	    }
	    fs.writeFileSync(config, JSON.stringify(prop, null, 4));
	}
    });
}

// List names of bots
else if (program.args[0] === 'list') {
    request.get(listUri(), listBotResp);
}

// Create a bot
else if (program.args[0] === 'create') {
    request.put(botUri(conf_botname()), okResp);
}

// Delete a bot
else if (program.args[0] === 'delete') {
    request.del(botUri(conf_botname()), deleteResp);
}

// Upload a file
else if (program.args[0] === 'upload') {
    if (program.args[1]) {
	retryOnFile(program.args[1], function (entry) {
	    fs.createReadStream(entry).pipe(request.put(fileUri(entry), okResp));
	});
    }
    else {
	console.log('usage: upload <filename>');
    }
}

// Upload all files at once
else if (program.args[0] === 'push') {
    var files = glob.sync('*.{pdefaults,properties,map,set,substitution,aiml}', {});
    if (files.length) {
	files.forEach (function (entry) {
	    console.log('uploading: ' + entry);
	    fs.createReadStream(entry).pipe(request.put(fileUri(entry), okResp))
	});
    }
    else {
	console.log('no bot files found');
    }
}

// Remove a file
else if (program.args[0] === 'remove') {
    if (program.args[1]) {
	request.del(fileUri(program.args[1]), removeResp);
    }
    else {
	console.log('usage: remove <filename>');
    }
}

// Download a file
else if (program.args[0] === 'download') {
    if (program.args[1]) {
	request.get(fileUri(program.args[1])).pipe(fs.createWriteStream(program.args[1]));;
    }
    else {
	console.log('usage: download <filename>');
    }
}

// List files of bot
else if (program.args[0] === 'get' && !program.all) {
    request.get(botUri(conf_botname()), listFileResp);
}

// Retrieve all files as ZIP
else if (program.args[0] === 'get' && program.all) {
    request.get(zipUri()).pipe(fs.createWriteStream(conf_botname() + '.zip'));
}

// Retrieve all files at once
else if (program.args[0] === 'pull') {
    //request.get(zipUri()).pipe(unzip.Extract({path: conf_botname()}));
    //it should work however gets freeze after zip have been downloaded; ugly workaround below
    request.get(botUri(conf_botname()), pullResp);
}

// Compile a bot
else if (program.args[0] === 'compile') {
    request.get(verifyUri(), okResp);
}

// Talk to a bot
else if (program.args[0] === 'talk') {
    if (program.args[1]) {
	var param = {input: program.args.slice(1).join(' ')};
	if (nconf.get('client_name')) param.client_name = nconf.get('client_name');
	if (nconf.get('sessionid')) param.sessionid = nconf.get('sessionid');
	if (nconf.get('extra')) param.extra = true;
	if (nconf.get('reset')) param.reset = true;
	if (nconf.get('trace')) param.trace = true;
	if (nconf.get('reload')) param.reload = true;
	if (nconf.get('recent')) param.recent = true;
	request.post(talkUri(), talkResp).form(composeParams(param));
    }
    else {
	console.log('usage: talk <text...>');
    }
}

else if (program.args[0] === undefined)
    console.log('usage: <command> [--options...]');
else {
    console.log('invalid command: ' + program.args[0]);
    process.exit(1);
}

<commit_msg>adds validation for bot deletion in pb-cli<commit_after>#!/usr/bin/env node

'use strict';

var fs = require('fs');
var glob = require('glob');
var nconf = require('nconf');
var path = require('path');
var program = require('commander');
var prompt = require('prompt');
var qs = require('querystring');
var request = require('request');
var unzip = require('unzip');
var url = require('url');

var config = 'chatbot.json';

var sep = function (str) {
    return str ? '/' + str : '';
}

var composeUri = function (mode, botname, kind, filename) {
    var uri = {
	protocol: nconf.get('protocol'),
	hostname: nconf.get('hostname')
    }
    var path = mode;
    path += sep(conf_app_id());
    path += sep(botname);
    path += sep(kind);
    path += sep(filename);
    uri.pathname = path;
    return uri;
}

var composeParams = function (params) {
    params.user_key = conf_user_key();
    return params;
}

var listUri = function () {
    var uri = composeUri('bot', '', '', '');
    uri.query = composeParams({});
    return url.format(uri);
}

var botUri = function (botname) {
    var uri = composeUri('bot', botname, '', '');
    uri.query = composeParams({});
    return url.format(uri);
}

var fileUri = function (filename) {
    var ext = path.extname(filename);
    var base = path.basename(filename, ext);
    var kind = ext.slice(1);
    var botname = conf_botname();
    var uri;
    if (kind === 'pdefaults' || kind === 'properties')
	uri = composeUri('bot', botname, kind, '');
    else if (kind === 'map' || kind === 'set' || kind === 'substitution')
	uri = composeUri('bot', botname, kind, base);
    else if (kind === 'aiml')
	uri = composeUri('bot', botname, 'file', base + ext);
    else {
	console.log('illegal file name: ' + filename);
	return;
    }
    uri.query = composeParams({});
    return url.format(uri);
}

var zipUri = function () {
    var uri = composeUri('bot', conf_botname(), '', '');
    uri.query = composeParams({return: 'zip'});
    return url.format(uri);
}

var verifyUri = function () {
    var uri = composeUri('bot', conf_botname(), 'verify', '');
    uri.query = composeParams({});
    return url.format(uri);
}

var talkUri = function () {
    var uri = composeUri('talk', conf_botname(), '', '');
    return url.format(uri);
}

var okResp = function (error, response, body) {
    var jObj = JSON.parse(body);
    if (jObj.status === 'ok')
	console.log(jObj.status)
    else {
	console.log(jObj.message)
	if (jObj.results !== undefined)
	    console.log(JSON.stringify(jObj.results[0], null, 2))
    }
}

var deletePerf = function (botname) {
    if (nconf.get('yes')) {
	console.log('deleting bot "' + botname + '"');
	request.del(botUri(botname), deleteResp);
    }
    else {
	var prop  = {
	    message: 'Are you sure you want to delete bot "' + botname + '" (yes/no)?',
	    name: 'resp', required: true, validator: /^(y|yes|n|no)$/i,
	    warning: 'please answer yes or no.'
	};
	prompt.get(prop, function (error, result) {
	    var yesRe = /^(y|yes)$/i;
	    if (error) {
		console.log("aborted.");
		process.exit(2);
	    }
	    else if (yesRe.test(result.resp))
		request.del(botUri(botname), deleteResp);
	    else
		console.log('skipped.');
	});
    }
}

var deleteResp = function (error, response, body) {
    var jObj = JSON.parse(body);
    if (jObj.status === 'ok')
	console.log(jObj.status)
    else {
	console.log(jObj.message);
	if (!nconf.get('yes')) {
	    var prop  = {
		message: 'Re-enter the name of the bot to delete:',
		name: 'botname',
		required: true
	    };
	    prompt.get(prop, function (error, result) {
		if (error) {
		    console.log("aborted.");
		    process.exit(2);
		}
		else
		    deletePerf(result.botname);
	    });
	}
    }
}

var retryOnFile = function (file, cb) {
    fs.exists(file, function (doesExist) {
	if (doesExist)
	    cb(file);
	else {
	    console.log('file not found');
	    if (!nconf.get('yes')) {
		var prop  = {
		    message: 'Re-enter the name of file to upload:',
		    name: 'input',
		    required: true
		};
		prompt.get(prop, function (error, result) {
		    if (error) {
			console.log("aborted.");
			process.exit(2);
		    }
		    else
			retryOnFile(result.input, cb);
		});
	    }
	}
    });
}

var removeResp = function (error, response, body) {
    var jObj = JSON.parse(body);
    if (jObj.status === 'ok')
	console.log(jObj.status)
    else {
	console.log("file not found");
	if (!nconf.get('yes')) {
	    var prop  = {
		message: 'Re-enter the name of file to remove:',
		name: 'filename',
		required: true
	    };
	    prompt.get(prop, function (error, result) {
		if (error) {
		    console.log("aborted.");
		    process.exit(2);
		}
		else {
		    request.del(fileUri(result.filename), removeResp);
		}
	    });
	}
    }
}

var listBotResp = function (error, response, body) {
    var jObj = JSON.parse(body);
    if (response.statusCode === 200) {
	jObj.forEach (function (entry) {
	    console.log(entry.botname);
	});
    }
    else
	console.log(jObj.message)
}

var fileList = function (jObj) {
    var files = [];
    if (jObj.properties.length) files.push(jObj.botname + ".properties");
    if (jObj.pdefaults.length) files.push(jObj.botname + ".pdefaults");
    jObj.files.forEach (function (entry) { files.push(entry.name); });
    jObj.sets.forEach (function (entry) { files.push(entry.name + ".set"); });
    jObj.maps.forEach (function (entry) { files.push(entry.name + ".map"); });
    jObj.substitutions.forEach (function (entry) { files.push(entry.name + ".substitution"); });
    return files;
}

var listFileResp = function (error, response, body) {
    var jObj = JSON.parse(body);
    if (response.statusCode === 200)
	fileList(jObj).forEach (function (file) { console.log(file); });
    else
	console.log(jObj.message)
}

var pullResp = function (error, response, body) {
    var jObj = JSON.parse(body);
    if (response.statusCode === 200) {
	fileList(jObj).forEach (function (file) {
	    request.get(fileUri(file)).pipe(fs.createWriteStream(file));
	});
    }
    else
	console.log(jObj.message)
}

var talkResp = function (error, response, body) {
    var jObj = JSON.parse(body);
    if (jObj.status === 'ok') {
	nconf.set('sessionid', jObj.sessionid);
	if (nconf.get('extra') || nconf.get('trace'))
	    console.log(jObj);
	else {
	    jObj.responses.forEach (function (entry) {
		console.log(entry);
	    });
	}
    }
    else
	console.log(jObj.message)
}

var conf_app_id = function () {
    var app_id = nconf.get('app_id');
    if (app_id === undefined) {
	console.log('app_id required. use --app_id <app_id> or do init');
	process.exit(1);
    }
    return app_id;
}

var conf_user_key = function () {
    var user_key = nconf.get('user_key');
    if (user_key === undefined) {
	console.log('user_key required. use --user_key <user_key> or do init');
	process.exit(1);
    }
    return user_key;
}

var conf_botname = function () {
    var botname = nconf.get('botname');
    if (botname === undefined) {
	console.log('botname required. use --botname <botname> or do init');
	process.exit(1);
    }
    return botname;
}

var options = {
    protocol: 'https',
    hostname: 'aiaas.pandorabots.com',
    app_id: undefined,
    user_key: undefined,
    botname: undefined,
    client_name: undefined,
    sessionid: undefined,
    extra: undefined,
    reset: undefined,
    trace: undefined,
    reload: undefined,
    recent: undefined,
    all: undefined,
    yes: undefined
}

prompt.message = "";
prompt.delimiter = "";

nconf.env();
nconf.file({file: config});
nconf.defaults(options);

program
    .version('0.0.1')
    .usage('command [options] <file ...>')
    .option('-p, --protocol <protocol>', 'protocol')
    .option('-h, --hostname <hostname>', 'hostname')
    .option('-i, --app_id <app_id>', 'app_id')
    .option('-k, --user_key <user_key>', 'user_key')
    .option('-b, --botname <botname>', 'name of bot')
    .option('-c, --client_name <client_name>', 'name of client')
    .option('-s, --sessionid <sessionid>', 'session id of conversation')
    .option('-e, --extra', 'provides additional information with bot response')
    .option('-M, --reset', 'reset the bot memory')
    .option('-t, --trace', 'adds trace data into response')
    .option('-r, --reload', 'force system to reload bot')
    .option('-R, --recent', 'use most recently compiled version of bot')
    .option('-a, --all', 'downloads all files')
    .option('-y, --yes', 'do not prompt anything; assume yes to all yes/no queries')
    .parse(process.argv);

for (var key in options) {
    if (program[key])
	nconf.set(key, program[key]);
}

// Initialize
if (program.args[0] === 'init') {
    var props = [
	{message: 'app_id? (required)', name: 'app_id',
	    required: true, validator: /^[0-9a-z]+$/,
	    warning: 'app_id must consist of alphanumeric, lowercase characters'},
	{message: 'user_key? (required)', name: 'user_key',
	    required: true, validator: /^[0-9a-z]+$/,
	    warning: 'user_key must consist of alphanumeric, lowercase characters'},
	{message: 'botname? (recommended)', name: 'botname'},
	{message: 'hostname? (optional)', name: 'hostname'}
    ];
    prompt.get(props, function (error, result) {
	if (error) {
	    console.log("aborted.");
	    process.exit(2);
	}
	else {
	    var prop = {};
	    for (var key in result) {
		if (result[key]) {
		    prop[key] = result[key];
		}
	    }
	    fs.writeFileSync(config, JSON.stringify(prop, null, 4));
	}
    });
}

// List names of bots
else if (program.args[0] === 'list') {
    request.get(listUri(), listBotResp);
}

// Create a bot
else if (program.args[0] === 'create') {
    request.put(botUri(conf_botname()), okResp);
}

// Delete a bot
else if (program.args[0] === 'delete') {
    deletePerf(conf_botname());
}

// Upload a file
else if (program.args[0] === 'upload') {
    if (program.args[1]) {
	retryOnFile(program.args[1], function (entry) {
	    fs.createReadStream(entry).pipe(request.put(fileUri(entry), okResp));
	});
    }
    else {
	console.log('usage: upload <filename>');
    }
}

// Upload all files at once
else if (program.args[0] === 'push') {
    var files = glob.sync('*.{pdefaults,properties,map,set,substitution,aiml}', {});
    if (files.length) {
	files.forEach (function (entry) {
	    console.log('uploading: ' + entry);
	    fs.createReadStream(entry).pipe(request.put(fileUri(entry), okResp))
	});
    }
    else {
	console.log('no bot files found');
    }
}

// Remove a file
else if (program.args[0] === 'remove') {
    if (program.args[1]) {
	request.del(fileUri(program.args[1]), removeResp);
    }
    else {
	console.log('usage: remove <filename>');
    }
}

// Download a file
else if (program.args[0] === 'download') {
    if (program.args[1]) {
	request.get(fileUri(program.args[1])).pipe(fs.createWriteStream(program.args[1]));;
    }
    else {
	console.log('usage: download <filename>');
    }
}

// List files of bot
else if (program.args[0] === 'get' && !program.all) {
    request.get(botUri(conf_botname()), listFileResp);
}

// Retrieve all files as ZIP
else if (program.args[0] === 'get' && program.all) {
    request.get(zipUri()).pipe(fs.createWriteStream(conf_botname() + '.zip'));
}

// Retrieve all files at once
else if (program.args[0] === 'pull') {
    //request.get(zipUri()).pipe(unzip.Extract({path: conf_botname()}));
    //it should work however gets freeze after zip have been downloaded; ugly workaround below
    request.get(botUri(conf_botname()), pullResp);
}

// Compile a bot
else if (program.args[0] === 'compile') {
    request.get(verifyUri(), okResp);
}

// Talk to a bot
else if (program.args[0] === 'talk') {
    if (program.args[1]) {
	var param = {input: program.args.slice(1).join(' ')};
	if (nconf.get('client_name')) param.client_name = nconf.get('client_name');
	if (nconf.get('sessionid')) param.sessionid = nconf.get('sessionid');
	if (nconf.get('extra')) param.extra = true;
	if (nconf.get('reset')) param.reset = true;
	if (nconf.get('trace')) param.trace = true;
	if (nconf.get('reload')) param.reload = true;
	if (nconf.get('recent')) param.recent = true;
	request.post(talkUri(), talkResp).form(composeParams(param));
    }
    else {
	console.log('usage: talk <text...>');
    }
}

else if (program.args[0] === undefined)
    console.log('usage: <command> [--options...]');
else {
    console.log('invalid command: ' + program.args[0]);
    process.exit(1);
}

<|endoftext|>


<commit_before>var fbPerson = new Firebase('https://trivia-crossroads.firebaseio.com/Person');

function ExistingProfiles(name, email, neighborhood, day, specialty){
  this.name = name;
  this.email = email;
  this.neighborhood = neighborhood;
  this.day = day;
  this.specialty = specialty;
}

var profileList = [];
var parsedProfileList = [];

fbPerson.once("value", function(snapshot) {
  snapshot.forEach(function(childSnapshot) {
    parsedProfileList.push(JSON.parse(childSnapshot.val()));
  });
  var table = document.getElementById('profileDisplay');
  for(var i = 0; i < parsedProfileList.length; i++){
    var tr = document.createElement('tr');

    for(var j in parsedProfileList[i]){
      var td = document.createElement('td');
      td.textContent = parsedProfileList[i][j];
      tr.appendChild(td);
    }
  table.appendChild(tr);
  }
});
<commit_msg>removed object constructer. Was not using it.<commit_after>var fbPerson = new Firebase('https://trivia-crossroads.firebaseio.com/Person');
var profileList = [];
var parsedProfileList = [];

fbPerson.once("value", function(snapshot) {
  snapshot.forEach(function(childSnapshot) {
    parsedProfileList.push(JSON.parse(childSnapshot.val()));
  });
  var table = document.getElementById('profileDisplay');
  for(var i = 0; i < parsedProfileList.length; i++){
    var tr = document.createElement('tr');

    for(var j in parsedProfileList[i]){
      var td = document.createElement('td');
      td.textContent = parsedProfileList[i][j];
      tr.appendChild(td);
    }
  table.appendChild(tr);
  }
});
<|endoftext|>


<commit_before>define(() => {
  return function Player(context, properties, x=0, y=0, pathfind) {
    let options = properties;
    options.tileWidth = options.tileWidth || 32;
    options.tileHeight = options.tileHeight || 32;
    options.movementFrameCount = options.movementFrameCount || 8;
    options.framesPerDirection = options.framesPerDirection || 4;
    options.speed = options.speed || 1;

    let tile = {x, y};
    let pos = {
      x: tile.x * options.tileWidth + options.files[0].width / 2,
      y: tile.y * options.tileHeight + options.files[0].width / 2
    };

    let direction = options.direction || 0;
    let speed = options.speed;
    let path = [];
    let movementFrame = Math.floor(Math.random() * options.framesPerDirection);
    let movementFrameTimer = Math.floor(Math.random() * options.movementFrameCount);

    let getFrame = () => options.files[options.framesPerDirection * direction + movementFrame];
    let getFrameX = (offset) => pos.x - options.files[0].width / 2 + offset.x;
    let getFrameY = (offset) => pos.y - options.files[0].height / 2 + offset.y;

    this.goTo = function (x, y) {
      pathfind(options.id, [tile.x, tile.y], [x, y], options.pathfindingLayer.getLayout(), false, false)
        .then(function (data) {
          if (data.length > 0 && data[1] !== undefined) {
            path = data;
          }
        });
    };

    this.moveTo = function (x, y) {
      let layout = options.pathfindingLayer.getLayout();
      if (layout[x][y] === 0) {
        path = [{x, y}];
      }
    }

    this.getTile = function () {
      return tile;
    };

    this.draw = function () {
      let offset = options.layer.getOffset();
      context.drawImage(getFrame(), getFrameX(offset), getFrameY(offset));
    };

    this.getDirection = function () {
      return direction;
    };

    this.setDirection = function (where) {
      direction = where % 4;
    };

    this.move = function () {
      if (path.length > 0) {
        movementFrameTimer++;
        if (movementFrameTimer >= options.movementFrameCount - 1) {
          movementFrame = (movementFrame + 1) % 4;
          movementFrameTimer = 0;
        }
        let tileWidth = options.tileWidth;
        let tileHeight = options.tileHeight;
        let frameWidth = options.files[0].width;
        let frameHeight = options.files[0].height;

        let targetX = path[0].x * tileWidth + frameWidth / 2;
        let targetY = path[0].y * tileHeight + frameHeight / 2;

        let inPosX = (targetX === pos.x);
        let inPosY = (targetY === pos.y);

        if (inPosX && inPosY) {
          path.shift();
        } else {
          if (!inPosX) {
            let modifier = (targetX - pos.x) / Math.abs(targetX - pos.x);
            direction = modifier > 0 ? 3 : 2;
            pos.x += modifier * speed;
          }
          if (!inPosY) {
            let modifier = (targetY - pos.y) / Math.abs(targetY - pos.y);
            direction = modifier > 0 ? 0 : 1;
            pos.y += modifier * speed;
          }
        }
      }
      tile = options.layer.getXYCoords(pos.x, pos.y);
    };

    this.id = options.id
  }
});
<commit_msg>Turn player in direction of impossible path when trying to move there<commit_after>define(() => {
  return function Player(context, properties, x=0, y=0, pathfind) {
    let options = properties;
    options.tileWidth = options.tileWidth || 32;
    options.tileHeight = options.tileHeight || 32;
    options.movementFrameCount = options.movementFrameCount || 8;
    options.framesPerDirection = options.framesPerDirection || 4;
    options.speed = options.speed || 1;

    let tile = {x, y};
    let pos = {
      x: tile.x * options.tileWidth + options.files[0].width / 2,
      y: tile.y * options.tileHeight + options.files[0].width / 2
    };

    let direction = options.direction || 0;
    let speed = options.speed;
    let path = [];
    let movementFrame = Math.floor(Math.random() * options.framesPerDirection);
    let movementFrameTimer = Math.floor(Math.random() * options.movementFrameCount);

    let getFrame = () => options.files[options.framesPerDirection * direction + movementFrame];
    let getFrameX = (offset) => pos.x - options.files[0].width / 2 + offset.x;
    let getFrameY = (offset) => pos.y - options.files[0].height / 2 + offset.y;

    this.goTo = function (x, y) {
      pathfind(options.id, [tile.x, tile.y], [x, y], options.pathfindingLayer.getLayout(), false, false)
        .then(function (data) {
          if (data.length > 0 && data[1] !== undefined) {
            path = data;
          }
        });
    };

    this.moveTo = function (x, y) {
      let directionFrom = (x, y) => 2 * (x != tile.x) + (x > tile.x) + (y < tile.y);
      let layout = options.pathfindingLayer.getLayout();
      if (layout[x][y] === 0) {
        path = [{x, y}];
      } else {
        direction = directionFrom(x, y);
      }
    }

    this.getTile = function () {
      return tile;
    };

    this.draw = function () {
      let offset = options.layer.getOffset();
      context.drawImage(getFrame(), getFrameX(offset), getFrameY(offset));
    };

    this.getDirection = function () {
      return direction;
    };

    this.setDirection = function (where) {
      direction = where % 4;
    };

    this.move = function () {
      if (path.length > 0) {
        movementFrameTimer++;
        if (movementFrameTimer >= options.movementFrameCount - 1) {
          movementFrame = (movementFrame + 1) % 4;
          movementFrameTimer = 0;
        }
        let tileWidth = options.tileWidth;
        let tileHeight = options.tileHeight;
        let frameWidth = options.files[0].width;
        let frameHeight = options.files[0].height;

        let targetX = path[0].x * tileWidth + frameWidth / 2;
        let targetY = path[0].y * tileHeight + frameHeight / 2;

        let inPosX = (targetX === pos.x);
        let inPosY = (targetY === pos.y);

        if (inPosX && inPosY) {
          path.shift();
        } else {
          if (!inPosX) {
            let modifier = (targetX - pos.x) / Math.abs(targetX - pos.x);
            direction = modifier > 0 ? 3 : 2;
            pos.x += modifier * speed;
          }
          if (!inPosY) {
            let modifier = (targetY - pos.y) / Math.abs(targetY - pos.y);
            direction = modifier > 0 ? 0 : 1;
            pos.y += modifier * speed;
          }
        }
      }
      tile = options.layer.getXYCoords(pos.x, pos.y);
    };

    this.id = options.id
  }
});
<|endoftext|>


<commit_before>function _player() {
	this.hp = 20;
	this.hpMax = 20;
	this.bloodcount = 0;
	this.goldCount = 0;
}

_player.prototype = {
	isDead : function() {
		if (this.hp <= 0) return true;
		else return false;
	},
	revive : function() {
		if (engine.dayStatus == "night") {
			this.healDamage(1);
		}
	},
	healDamage : function(heal) {
		if ((this.hp+heal) > this.hpMax) this.hp = this.hpMax;
		else this.hp += heal;
		engine.elements.alterHTML("hp",this.hp);
	},
	triggerDeath : function(cause,bloodLoss) {
		engine.elements.eventMsg("You have died from: "+cause);
		engine.elements.eventMsg("Your death has cost you "+bloodLoss+" pints of your precious blood!");
		if (this.bloodcount < 20) this.bloodcount = 0;
		else this.bloodcount -= bloodLoss;
		engine.elements.alterHTML("blood",this.bloodcount);
	},
	dealDamage : function(dmg,type,bloodLossOnDeath) {
		if (!engine.firstHPLoss) {
			engine.firstHPLoss = true;
			engine.elements.showElement("hpDiv");
		}
		if ((this.hp-dmg) <= 0) {
			this.hp = 0;
			this.triggerDeath(type,bloodLossOnDeath);
		} else {
			this.hp -= dmg;
		}
	},
	hunt : function() {
		var bloodCollected = 0;
		engine.elements.alterHTML("bloodButton","Wait to hunt...");
		engine.elements.disableElement("bloodButton");
		if (engine.dayStatus == engine.statusCycle[0]) {
			this.dealDamage(10,"sunlight",20);
			engine.elements.eventMsg("Hunting in the daylight has hurt you! -10 HP!");
		} else {
			bloodCollected = 1*engine.multiplier;
			this.bloodcount += bloodCollected;
			console.log(bloodCollected);
			engine.elements.alterHTML("blood",this.bloodcount);
			engine.elements.eventMsg("Your hunt yielded "+bloodCollected+" pint(s) of blood!");
			this.healDamage(1);
		}
	},
	raid : function() {
		engine.elements.showElement("goldDiv");
		var goldCollected;
		var hpLoss = 0;
		engine.elements.alterHTML("raidButton","Wait to raid...");
		engine.elements.disableElement("raidButton");
		if (engine.dayStatus == engine.statusCycle[0]) {
			this.dealDamage(15,"sunlight");
			engine.elements.eventMsg("Raiding in the daylight has hurt you! -15 HP!");
		} else {
			hpLoss = Math.floor(Math.random()*(5-1+1)+1);
			goldCollected = Math.floor((Math.random()*100));
			this.goldCount += goldCollected;
			engine.elements.alterHTML("gold",this.goldCount);
			engine.elements.eventMsg("Your raid yielded "+goldCollected+" gold coins at the cost of "+hpLoss+"HP from the townspeople!");
			this.dealDamage(hpLoss,"raiding",15);
		}
	}
}<commit_msg>Player Prototype Object<commit_after>function _player() {
	this.hp = 20;
	this.hpMax = 20;
	this.bloodcount = 0;
	this.goldCount = 0;
}

_player.prototype = {
	isDead : function() {
		if (engine.player.hp <= 0) return true;
		else return false;
	},
	revive : function() {
		if (engine.dayStatus == "night") {
			engine.player.healDamage(1);
		}
	},
	healDamage : function(heal) {
		if ((engine.player.hp+heal) > engine.player.hpMax) engine.player.hp = engine.player.hpMax;
		else engine.player.hp += heal;
		engine.elements.alterHTML("hp",engine.player.hp);
	},
	triggerDeath : function(cause,bloodLoss) {
		engine.elements.eventMsg("You have died from: "+cause);
		engine.elements.eventMsg("Your death has cost you "+bloodLoss+" pints of your precious blood!");
		if (engine.player.bloodcount < 20) engine.player.bloodcount = 0;
		else engine.player.bloodcount -= bloodLoss;
		engine.elements.alterHTML("blood",engine.player.bloodcount);
		engine.elements.disableElement("bloodButton","Wait to Hunt...");
		engine.elements.disableElement("raidButton","Wait to Raid...");
	},
	dealDamage : function(dmg,type,bloodLossOnDeath) {
		if (!engine.firstHPLoss) {
			engine.firstHPLoss = true;
			engine.elements.showElement("hpDiv","block");
		}
		if ((engine.player.hp-dmg) <= 0) {
			engine.player.hp = 0;
			engine.player.triggerDeath(type,bloodLossOnDeath);
		} else {
			engine.player.hp -= dmg;
		}
		engine.elements.alterHTML("hp",engine.player.hp);
	},
	hunt : function() {
		var bloodCollected = 0;
		engine.elements.disableElement("bloodButton","Wait to Hunt...");
		if (engine.dayStatus == engine.statusCycle[0]) {
			engine.player.dealDamage(10,"sunlight",20);
			engine.elements.eventMsg("Hunting in the daylight has hurt you! -10 HP!");
		} else {
			bloodCollected = 1*engine.multiplier;
			engine.player.bloodcount += bloodCollected;
			engine.elements.alterHTML("blood",engine.player.bloodcount);
			engine.elements.eventMsg("Your hunt yielded "+bloodCollected+" pint(s) of blood!");
			engine.player.healDamage(1);
		}
	},
	raid : function() {
		engine.elements.showElement("goldDiv","block");
		var goldCollected;
		var hpLoss = 0;
		engine.elements.disableElement("raidButton","Wait to Raid...");
		if (engine.dayStatus == engine.statusCycle[0]) {
			engine.player.dealDamage(15,"sunlight",25);
			engine.elements.eventMsg("Raiding in the daylight has hurt you! -15 HP!");
		} else {
			hpLoss = Math.floor(Math.random()*(5-1+1)+1);
			goldCollected = Math.floor((Math.random()*100));
			engine.player.goldCount += goldCollected;
			engine.elements.alterHTML("gold",engine.player.goldCount);
			engine.elements.eventMsg("Your raid yielded "+goldCollected+" gold coins at the cost of "+hpLoss+"HP from the townspeople!");
			engine.player.dealDamage(hpLoss,"raiding",15);
		}
	}
}<|endoftext|>


<commit_before>
module.exports = {

  VERSION: "Awesome JS player",

  bet_request: function(game_state, bet) {
    bet(1000);
  },

  showdown: function(game_state) {

  }
};
<commit_msg>Updating branch for +1<commit_after>
module.exports = {

  VERSION: "Awesome JS player",

  bet_request: function(game_state, bet) {
    var me = game_state.players[game_state.in_action];
    var betAmount = game_state.current_buy_in - me.bet + 1;
    bet(betAmount);
  },

  showdown: function(game_state) {

  }
};
<|endoftext|>


<commit_before>var io = require('socket.io-client')
    game = io('http://localhost:3000'),
    lobby = io('http://localhost:3030'),
    Chess = require('chess.js').Chess,

    name = 'RndJesus_' + Math.floor(Math.random() * 100);;

lobby.on('connect', function () {
    console.log('Player ' + name + ' is connected to lobby');
    lobby.emit('enter', name);
});

lobby.on('join', function (gameId) {
    console.log('Player is joining game: ' + gameId);
    game.emit('join', gameId);
});

game.on('connect', function () {
    console.log('Player ' + name + ' is connected to game');
});

game.on('move', function (gameState) {
    var chess = new Chess();
    chess.load(gameState.board);

    var moves = chess.moves(),
        move = moves[Math.floor(Math.random() * moves.length)];

    console.log(move);
    gameState.move = move;

    game.emit('move', gameState);
});
<commit_msg>Delay moves with 100 ms<commit_after>var io = require('socket.io-client')
    game = io('http://localhost:3000'),
    lobby = io('http://localhost:3030'),
    Chess = require('chess.js').Chess,

    name = 'RndJesus_' + Math.floor(Math.random() * 100);;

lobby.on('connect', function () {
    console.log('Player ' + name + ' is connected to lobby');
    lobby.emit('enter', name);
});

lobby.on('join', function (gameId) {
    console.log('Player is joining game: ' + gameId);
    game.emit('join', gameId);
});

game.on('connect', function () {
    console.log('Player ' + name + ' is connected to game');
});

game.on('move', function (gameState) {
    var chess = new Chess();
    chess.load(gameState.board);

    var moves = chess.moves(),
        move = moves[Math.floor(Math.random() * moves.length)];

    console.log(move);
    gameState.move = move;

    setTimeout(function () {
        game.emit('move', gameState);
    }, 100);
});
<|endoftext|>


<commit_before>var METER  = TILE;
var GRAVITY = METER * 9.8 * 3;
var MAXDX = METER * 10;
var MAXDY = METER * 15;
var ACCEL = MAXDX * 2;
var JUMP = METER * 1500;
var FRICTION = MAXDX * 6;

var LEFT = 0;
var RIGHT = 1;

var ANIM_IDLE = 0;
var ANIM_JUMP = 1;
var ANIM_WALK_LEFT = 2;
var ANIM_WALK_RIGHT = 3;
var ANIM_MAX = 4;

var Player = function(){

	this.sprite = new Sprite("p1_spritesheet.png");
	this.sprite.buildAnimation(7, 3, 73.5, 95, 0.05,
		[4]);
	this.sprite.buildAnimation(7, 3, 73, 94, 0.05,
		[13, 13]);
	this.sprite.buildAnimation(7, 3, 72.7, 97, 0.05,
		[0, 1, 2, 7, 9, 10, 3, 4, 5]);
	this.sprite.buildAnimation(7, 3, 72.7, 97, 0.05,
		[5, 4, 3, 10, 9, 7, 2, 1, 0]);

	for(var i=0; i<ANIM_MAX; i++)
	{
		this.sprite.setAnimationOffset(i, -55, -87);
	}

	this.x = SCREEN_WIDTH/2;
	this.y = SCREEN_HEIGHT/2;
	this.width = 72.5;
	this.height = 95;

	this.velocityX =  0;
	this.velocityY = 0;
	this.angularVelocity = 0;
	this.rotation = 0;

	this.falling = true;
	this.jumping = false;

	this.offset_x = -55;
	this.offset_y = -87

	this.lives = 3;
	this.shooting = false;
	this.ammo = 7;

	this.score = 0;

	this.hasKey = false;

	this.direction = LEFT;

};

Player.prototype.Update = function(deltaTime) {

	this.sprite.update(deltaTime);

	GRAVITY = METER * 9.8 * 3;

	var tx = pixel2Tile(this.x);
	var ty = pixel2Tile(this.y);

	var nx = this.x % TILE;
	var ny = this.y % TILE;

	var cell = 		 cellAtTileCoord(LAYER_GROUND, tx, 		ty);
	var cellRight =	 cellAtTileCoord(LAYER_GROUND, tx + 1, 	ty);
	var cellDown  =	 cellAtTileCoord(LAYER_GROUND, tx, 		ty + 1);
	var cellDiag  =  cellAtTileCoord(LAYER_GROUND, tx + 1, 	ty + 1);

	var cellPortal = cellAtTileCoord(LAYER_DOORS, tx, 		ty);
	var cellKey = cellAtTileCoord(LAYER_KEYS, tx, ty);
	//var cellDoor = cellAtTileCoord(LAYER)

	var left, right, jump;
	left = right = jump = false;

	//changing anmiation and direction for left
	if(keyboard.isKeyDown(keyboard.KEY_LEFT)){
		left = true;
		this.direction = LEFT;
		if(this.sprite.currentAnimation != ANIM_WALK_LEFT)
			this.sprite.setAnimation(ANIM_WALK_LEFT);
	}

	//changing anmiation and direction for right
	else if (keyboard.isKeyDown(keyboard.KEY_RIGHT)){
		right = true;
		this.direction = RIGHT;
		if(this.sprite.currentAnimation != ANIM_WALK_RIGHT)
			this.sprite.setAnimation(ANIM_WALK_RIGHT);
	}

	if ((keyboard.isKeyDown(keyboard.KEY_SPACE)) || (keyboard.isKeyDown(keyboard.KEY_UP))){
		jump = true;
		this.score += 1;
		if(this.sprite.currentAnimation != ANIM_JUMP)
			this.sprite.setAnimation(ANIM_JUMP);
	}

	if ((keyboard.isKeyDown(keyboard.KEY_CTRL)) && cellDoor){
		CurrentLevel = level1_blue;
		initialize(CurrentLevel);
	}

	else if ((keyboar.isKeyDown(keyboard.KEY_CTRL)) && cellKey){
		this.hasKey = true;
	}

	//jump = keyboard.isKeyDown(keyboard.KEY_SPACE);

	var wasleft = this.velocityX < 0;
	var wasright = this.velocityX > 0;

	var falling = this.falling;
	var ddx = 0;			 //ACCELERATION
	var ddy = GRAVITY;

	if (left){
		ddx -= ACCEL;
	}
	else if (wasleft){
		ddx += FRICTION;
	}

	if (right){
		ddx += ACCEL;
	}
	else if (wasright){
		ddx -= FRICTION
	}

	if (jump && !this.jumping && !falling){
		ddy -= JUMP;
		this.jumping = true;
		this.sprite.setAnimation(ANIM_JUMP)
	}

	//calculate the new postioin and velocity:
	this.x += deltaTime * this.velocityX;
	this.y += deltaTime * this.velocityY;
	this.velocityX = bound(this.velocityX + (deltaTime * ddx), -MAXDX, MAXDX);
	this.velocityY = bound(this.velocityY + (deltaTime * ddy), -MAXDY, MAXDY);

	if (this.y > SCREEN_HEIGHT){
			this.lives --;
			if (this.lives <= 0){
				curGameState = GAMESTATE_ENDGAME;

			}

			else{
				this.respawn();
			}

		}

	if ( (wasleft && (this.velocityX > 0)) || (wasright && (this.velocityX < 0))){
		//clamp at zero to prevbent frition from making us jiggle side to side
		this.velocityX = 0;
	}

	//rotation when walking
	//if ( this.velocityX > 0){
	//	this.rotation = (this.velocityX / MAXDX) * (Math.PI / 8) ;
	//}
	//else if (this.velocityX < 0){
	//	this.rotation = (-this.velocityX / MAXDX) * (-Math.PI /8);
	//}
	//else{
	//	this.rotation = 0;
	//}

	//CEILING
	if(this.velocityY > 0){
		if ((cellDown & !cell) || (cellDiag && !cellRight && nx)){
			this.y = tile2Pixel(ty);
			this.velocityY = 0;
			this.falling = false;
			this.jumping = false;
			ny = 0;
		}

	}
	//FLOOR
	else if (this.velocityY < 0) {
		if ((cell && !cellDown) || (cellRight && !cellDiag && nx)){
			//calmp the y poition to avoid jumping into platform above

			this.y = tile2Pixel(ty + 1);
			this.velocityY = 0; 		//stop upward velocity

			cell = cellDown;
			cellRight = cellDiag;
			ny = 0;
		}
	}

	if (this.velocityX > 0){
		if ((cellRight && !cell) || (cellDiag && !cellDown && ny)){
			//clamp the x position to avoid moving into the platform we just hit
			this.x = tile2Pixel(tx);
			this.velocityX = 0;
		}
	}

	else if (this.velocityX < 0){
		if((cell && !cellRight) || (cellDown && !cellDiag && ny)){
			this.x = tile2Pixel(tx + 1);
			this.velocityX = 0;
		}
	}

Player.prototype.respawn = function(){
	this.x = SCREEN_WIDTH/2;
	this.y = SCREEN_HEIGHT/2;
	this.width = 73.5;
	this.height = 95;

	this.offset_x = -55;
	this.offset_y = -87;

	this.velocityX =  0;
	this.velocityY = 0;
	this.angularVelocity = 0;
	this.rotation = 0;

	this.shooting = false;
	this.ammo = 7;
}

};

Player.prototype.Draw = function(_cam_x, _cam_y){

	this.sprite.draw(context, this.x + (this.width/2), this.y + (this.height/2));
//	context.save();
//
//		context.translate(this.x + _cam_x, this.y + _cam_y);
//		context.rotate(this.rotation);
//		context.drawImage(this.image,
//							-this.width/2,
//							-this.height/2)
//
//	context.restore();
//
	context.save();

	context.beginPath();

	//context.rect(this.x - (this.width/2)  , this.y - (this.height/2), this.width, this.height);
	context.stroke();
	context.restore();

};

<commit_msg>no message<commit_after>var METER  = TILE;
var GRAVITY = METER * 9.8 * 3;
var MAXDX = METER * 10;
var MAXDY = METER * 15;
var ACCEL = MAXDX * 2;
var JUMP = METER * 1500;
var FRICTION = MAXDX * 6;

var LEFT = 0;
var RIGHT = 1;

var ANIM_IDLE = 0;
var ANIM_JUMP = 1;
var ANIM_WALK_LEFT = 2;
var ANIM_WALK_RIGHT = 3;
var ANIM_MAX = 4;

var Player = function(){

	this.sprite = new Sprite("p1_spritesheet.png");
	this.sprite.buildAnimation(7, 3, 73.5, 95, 0.05,
		[4]);
	this.sprite.buildAnimation(7, 3, 73, 94, 0.05,
		[13, 13]);
	this.sprite.buildAnimation(7, 3, 72.7, 97, 0.05,
		[0, 1, 2, 7, 9, 10, 3, 4, 5]);
	this.sprite.buildAnimation(7, 3, 72.7, 97, 0.05,
		[5, 4, 3, 10, 9, 7, 2, 1, 0]);

	for(var i=0; i<ANIM_MAX; i++)
	{
		this.sprite.setAnimationOffset(i, -55, -87);
	}

	this.x = SCREEN_WIDTH/2;
	this.y = SCREEN_HEIGHT/2;
	this.width = 72.5;
	this.height = 95;

	this.velocityX =  0;
	this.velocityY = 0;
	this.angularVelocity = 0;
	this.rotation = 0;

	this.falling = true;
	this.jumping = false;

	this.offset_x = -55;
	this.offset_y = -87

	this.lives = 3;
	this.shooting = false;
	this.ammo = 7;

	this.score = 0;

	this.hasKey = false;

	this.direction = LEFT;

};

Player.prototype.Update = function(deltaTime) {

	this.sprite.update(deltaTime);

	GRAVITY = METER * 9.8 * 3;

	var tx = pixel2Tile(this.x);
	var ty = pixel2Tile(this.y);

	var nx = this.x % TILE;
	var ny = this.y % TILE;

	var cell = 		 cellAtTileCoord(LAYER_GROUND, tx, 		ty);
	var cellRight =	 cellAtTileCoord(LAYER_GROUND, tx + 1, 	ty);
	var cellDown  =	 cellAtTileCoord(LAYER_GROUND, tx, 		ty + 1);
	var cellDiag  =  cellAtTileCoord(LAYER_GROUND, tx + 1, 	ty + 1);

	var cellPortal = cellAtTileCoord(LAYER_DOORS, tx, 		ty);
	var cellKey = cellAtTileCoord(LAYER_KEYS, tx, ty);
	//var cellDoor = cellAtTileCoord(LAYER)

	var left, right, jump;
	left = right = jump = false;

	//changing anmiation and direction for left
	if(keyboard.isKeyDown(keyboard.KEY_LEFT)){
		left = true;
		this.direction = LEFT;
		if(this.sprite.currentAnimation != ANIM_WALK_LEFT)
			this.sprite.setAnimation(ANIM_WALK_LEFT);
	}

	//changing anmiation and direction for right
	else if (keyboard.isKeyDown(keyboard.KEY_RIGHT)){
		right = true;
		this.direction = RIGHT;
		if(this.sprite.currentAnimation != ANIM_WALK_RIGHT)
			this.sprite.setAnimation(ANIM_WALK_RIGHT);
	}

	if ((keyboard.isKeyDown(keyboard.KEY_SPACE)) || (keyboard.isKeyDown(keyboard.KEY_UP))){
		jump = true;
		this.score += 1;
		if(this.sprite.currentAnimation != ANIM_JUMP)
			this.sprite.setAnimation(ANIM_JUMP);
	}

	if ((keyboard.isKeyDown(keyboard.KEY_CTRL)) && cellDoor){
		CurrentLevel = level1_blue;
		initialize(CurrentLevel);
	}

	else if ((keyboarD.isKeyDown(keyboard.KEY_CTRL)) && cellKey){
		this.hasKey = true;
	}

	//jump = keyboard.isKeyDown(keyboard.KEY_SPACE);

	var wasleft = this.velocityX < 0;
	var wasright = this.velocityX > 0;

	var falling = this.falling;
	var ddx = 0;			 //ACCELERATION
	var ddy = GRAVITY;

	if (left){
		ddx -= ACCEL;
	}
	else if (wasleft){
		ddx += FRICTION;
	}

	if (right){
		ddx += ACCEL;
	}
	else if (wasright){
		ddx -= FRICTION
	}

	if (jump && !this.jumping && !falling){
		ddy -= JUMP;
		this.jumping = true;
		this.sprite.setAnimation(ANIM_JUMP)
	}

	//calculate the new postioin and velocity:
	this.x += deltaTime * this.velocityX;
	this.y += deltaTime * this.velocityY;
	this.velocityX = bound(this.velocityX + (deltaTime * ddx), -MAXDX, MAXDX);
	this.velocityY = bound(this.velocityY + (deltaTime * ddy), -MAXDY, MAXDY);

	if (this.y > SCREEN_HEIGHT){
			this.lives --;
			if (this.lives <= 0){
				curGameState = GAMESTATE_ENDGAME;

			}

			else{
				this.respawn();
			}

		}

	if ( (wasleft && (this.velocityX > 0)) || (wasright && (this.velocityX < 0))){
		//clamp at zero to prevbent frition from making us jiggle side to side
		this.velocityX = 0;
	}

	//rotation when walking
	//if ( this.velocityX > 0){
	//	this.rotation = (this.velocityX / MAXDX) * (Math.PI / 8) ;
	//}
	//else if (this.velocityX < 0){
	//	this.rotation = (-this.velocityX / MAXDX) * (-Math.PI /8);
	//}
	//else{
	//	this.rotation = 0;
	//}

	//CEILING
	if(this.velocityY > 0){
		if ((cellDown & !cell) || (cellDiag && !cellRight && nx)){
			this.y = tile2Pixel(ty);
			this.velocityY = 0;
			this.falling = false;
			this.jumping = false;
			ny = 0;
		}

	}
	//FLOOR
	else if (this.velocityY < 0) {
		if ((cell && !cellDown) || (cellRight && !cellDiag && nx)){
			//calmp the y poition to avoid jumping into platform above

			this.y = tile2Pixel(ty + 1);
			this.velocityY = 0; 		//stop upward velocity

			cell = cellDown;
			cellRight = cellDiag;
			ny = 0;
		}
	}

	if (this.velocityX > 0){
		if ((cellRight && !cell) || (cellDiag && !cellDown && ny)){
			//clamp the x position to avoid moving into the platform we just hit
			this.x = tile2Pixel(tx);
			this.velocityX = 0;
		}
	}

	else if (this.velocityX < 0){
		if((cell && !cellRight) || (cellDown && !cellDiag && ny)){
			this.x = tile2Pixel(tx + 1);
			this.velocityX = 0;
		}
	}

Player.prototype.respawn = function(){
	this.x = SCREEN_WIDTH/2;
	this.y = SCREEN_HEIGHT/2;
	this.width = 73.5;
	this.height = 95;

	this.offset_x = -55;
	this.offset_y = -87;

	this.velocityX =  0;
	this.velocityY = 0;
	this.angularVelocity = 0;
	this.rotation = 0;

	this.shooting = false;
	this.ammo = 7;
}

};

Player.prototype.Draw = function(_cam_x, _cam_y){

	this.sprite.draw(context, this.x + (this.width/2), this.y + (this.height/2));
//	context.save();
//
//		context.translate(this.x + _cam_x, this.y + _cam_y);
//		context.rotate(this.rotation);
//		context.drawImage(this.image,
//							-this.width/2,
//							-this.height/2)
//
//	context.restore();
//
	context.save();

	context.beginPath();

	//context.rect(this.x - (this.width/2)  , this.y - (this.height/2), this.width, this.height);
	context.stroke();
	context.restore();

};

<|endoftext|>


<commit_before>'use strict';

var LIVERELOAD_PORT = 35729;
var lrSnippet = require('connect-livereload')({ port: LIVERELOAD_PORT });
var mountFolder = function (connect, dir) {
  return connect.static(require('path').resolve(dir));
};
var cheerio = require('cheerio');
var async = require('async');

module.exports = function (grunt) {
  require('load-grunt-tasks')(grunt);
  require('time-grunt')(grunt);

  // configurable paths
  var pointsConfig = {
    app: 'app',
    static: 'app/static',
    dist: 'dist'
  };

  grunt.initConfig({
    points: pointsConfig,
    watch: {
      coffee: {
        files: ['<%= points.static %>/scripts/{,*/}*.coffee'],
        tasks: ['coffee:dev']
      },
      styles: {
        files: ['<%= points.static %>/styles/**/*.less'],
        tasks: ['less:dev']
      },
      livereload: {
        options: {
          livereload: LIVERELOAD_PORT
        },
        files: [
          '<%= points.app %>/**/*.html',
          '<%= points.static %>/documents/{,*/}*.md',
          '<%= points.static %>/styles/{,*/}*.css',
          '<%= points.static %>/scripts/{,*/}*.js',
          '<%= points.static %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
        ]
      }
    },
    connect: {
      options: {
        port: 9000,
        // Change this to '0.0.0.0' to access the server from outside.
        hostname: '0.0.0.0'
      },
      livereload: {
        options: {
          middleware: function (connect) {
            return [
              lrSnippet,
              mountFolder(connect, pointsConfig.app)
            ];
          }
        }
      }
    },
    open: {
      server: {
        url: 'http://localhost:<%= connect.options.port %>'
      }
    },
    less: {
      dev: {
        options: {
          paths: ['<%= points.static %>/styles']
        },
        files: [{
            expand: true,
            cwd: '<%= points.static %>/styles',
            src: ['app.less'],
            dest: '<%= points.static %>/styles',
            ext: '.css'
        }]
      },
      dist: {
        options: {
          paths: ['<%= points.static %>/styles'],
          yuicompress: true
        },
        files: {
          '<%= points.dist %>/static/styles/app.css': '<%= points.static %>/styles/app.less'
        }
      }
    },
    coffee: {
      dev: {
        options: {
          sourceMap: true,
          sourceRoot: ''
        },
        files: [{
          expand: true,
          cwd: '<%= points.static %>/scripts',
          src: ['{,*/}*.coffee'],
          dest: '<%= points.static %>/scripts',
          ext: '.js'
        }]
      },
      dist: {
        files: [{
          expand: true,
          cwd: '<%= points.static %>/scripts',
          src: ['{,*/}*.coffee'],
          dest: '<%= points.static %>/scripts',
          ext: '.js'
        }]
      }
    },
    imagemin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= points.dist %>/static/images',
          src: '{,*/}*.{png,jpg,jpeg}',
          dest: '<%= points.dist %>/static/images'
        }]
      }
    },
    concurrent: {
      server: [
        'coffee:dev',
        'less:dev'
      ]
    },
    copy: {
      images: {
        files: [{
          expand: true,
          cwd: '<%= points.static %>/',
          src: ['images/**'],
          dest: '<%= points.dist %>/static/'
        }]
      },
      html: {
        files: [{
          expand: true,
          cwd: '<%= points.app %>/',
          src: ['*.html'],
          dest: '<%= points.dist %>/'
        }]
      }
    },
    clean: {
      dist: [
      ]
    },
    requirejs: {
      dist: {
        options: {
          // Use almond.js
          // appDir: '<%= points.static %>/scripts/',
          // dir: '<%= points.dist %>/static/scripts/',

          almond: true,
          baseUrl: '<%= points.static %>/scripts/',
          mainConfigFile: '<%= points.static %>/scripts/main.js',

          replaceRequireScript: [{
            files: ['<%= points.dist %>/*.html'],
            module: 'main',
            modulePath: 'static/scripts/app'
          }],
          pragmasOnSave : {
            excludeMdown : true
          },

          shim: {
            'bootstrap.scrollspy': {
              deps: ['jquery']
            },
            'jquery.fixto': {
              deps: ['jquery']
            },
            'Handlebars': {
              exports: 'Handlebars'
            }
          },

          optimize: 'uglify',
          uglify: {
            no_mangle: true
          },

          fileExclusionRegExp: /^(node_modules|.svn)/,
          findNestedDependencies: true,
          include: ['main'],
          stubModules : ['json', 'text'],

          out: '<%= points.dist %>/static/scripts/app.js'
        }
      }
    },
    markdown: {
      all: {
        files: [{
          cwd: '<%= points.static %>/documents',
          src: ['*.md'],
          expand: true,
          dest: '<%= points.static %>/tmp',
          ext: '.html'
        }],
        options: {
          template: 'utils/templates/markdown.html',
          postCompile: function(src, context) {
            var $ = cheerio.load(src);

            function processHtml(stage) {
              var next, newHtml, current, id;

              return function(i, obj) {
                id = $(obj).text().replace(/[\. ,#():-]+/g, '-').toLowerCase();
                next = $(obj).next();
                newHtml = $(obj);
                current = obj;

                async.whilst(
                  function() {
                    if (stage === 'create-sections') {
                      return !next.is('h2') && next.length > 0
                    } else if (stage === 'create-subsections') {
                      return !next.is('h3') && next.length > 0
                    } else {
                      return !next.is('h3') && !next.is('h2') && next.length > 0
                    }
                  },
                  function(callback) {
                      newHtml += '\n'+next;
                      next = next.next();
                      next.prev().remove();
                      callback();
                  },
                  function() {
                    var update;

                    if (stage === 'create-sections') {
                      update = '
\n'+newHtml+'\n
';
                    } else {
                      update = '
\n'+newHtml+'\n
'
                    }

                    $(current).replaceWith(update)
                  }
                );
              }
            }
            async.series([
              function (callback) {
                $('h2').each(processHtml('create-sections'));
                $('h2').each(processHtml('create-h2-subsections'));
                $('h3').each(processHtml('create-subsections'));

                callback();
              },
              function (callback) {
                $('section').each(function(i, obj) {
                  $(obj).children().last().remove();
                });
                $('section').last().next().remove();
                callback();
              }
            ]);

            return $.html()
          }
        }
      }
    }
  });

  grunt.registerTask('generate-markdown-list', function() {
    var files = []
      , paths =[]
      , data = {}
      , template = grunt.file.read('utils/templates/generate-markdown-files.html')
      , writeTo = 'app/static/scripts/modules/load-markdown-documents.coffee';

    grunt.file.recurse('app/static/documents/', function(abspath, rootdir, subdir, filename) {
      abspath = abspath.replace('app/static', 'mdown!../..')
      filename = filename.replace(/\-/g, '_').replace('.md','').replace('.html', '');

      if (filename !== '.DS_Store') {
        files.push(filename);
        paths.push(abspath);
      }
    });

    data = { files: files, paths: paths };

    grunt.file.write(writeTo, grunt.template.process(template, {data: data}));
  });

  grunt.registerTask('build-html', [
    'markdown:all'
  ]);

  grunt.registerTask('server', function (target) {
    grunt.task.run([
      'concurrent:server',
      'connect:livereload',
      'open',
      'watch'
    ]);
  });

  grunt.registerTask('build', [
    'generate-markdown-list',
    'copy:html',
    'coffee:dist',
    'less:dist',
    'requirejs:dist',
    'copy:images',
    'imagemin'
  ]);

  grunt.registerTask('default', [
    'server'
  ]);
};
<commit_msg>use uglifyjs2<commit_after>'use strict';

var LIVERELOAD_PORT = 35729;
var lrSnippet = require('connect-livereload')({ port: LIVERELOAD_PORT });
var mountFolder = function (connect, dir) {
  return connect.static(require('path').resolve(dir));
};
var cheerio = require('cheerio');
var async = require('async');

module.exports = function (grunt) {
  require('load-grunt-tasks')(grunt);
  require('time-grunt')(grunt);

  // configurable paths
  var pointsConfig = {
    app: 'app',
    static: 'app/static',
    dist: 'dist'
  };

  grunt.initConfig({
    points: pointsConfig,
    watch: {
      coffee: {
        files: ['<%= points.static %>/scripts/{,*/}*.coffee'],
        tasks: ['coffee:dev']
      },
      styles: {
        files: ['<%= points.static %>/styles/**/*.less'],
        tasks: ['less:dev']
      },
      livereload: {
        options: {
          livereload: LIVERELOAD_PORT
        },
        files: [
          '<%= points.app %>/**/*.html',
          '<%= points.static %>/documents/{,*/}*.md',
          '<%= points.static %>/styles/{,*/}*.css',
          '<%= points.static %>/scripts/{,*/}*.js',
          '<%= points.static %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
        ]
      }
    },
    connect: {
      options: {
        port: 9000,
        // Change this to '0.0.0.0' to access the server from outside.
        hostname: '0.0.0.0'
      },
      livereload: {
        options: {
          middleware: function (connect) {
            return [
              lrSnippet,
              mountFolder(connect, pointsConfig.app)
            ];
          }
        }
      }
    },
    open: {
      server: {
        url: 'http://localhost:<%= connect.options.port %>'
      }
    },
    less: {
      dev: {
        options: {
          paths: ['<%= points.static %>/styles']
        },
        files: [{
            expand: true,
            cwd: '<%= points.static %>/styles',
            src: ['app.less'],
            dest: '<%= points.static %>/styles',
            ext: '.css'
        }]
      },
      dist: {
        options: {
          paths: ['<%= points.static %>/styles'],
          yuicompress: true
        },
        files: {
          '<%= points.dist %>/static/styles/app.css': '<%= points.static %>/styles/app.less'
        }
      }
    },
    coffee: {
      dev: {
        options: {
          sourceMap: true,
          sourceRoot: ''
        },
        files: [{
          expand: true,
          cwd: '<%= points.static %>/scripts',
          src: ['{,*/}*.coffee'],
          dest: '<%= points.static %>/scripts',
          ext: '.js'
        }]
      },
      dist: {
        files: [{
          expand: true,
          cwd: '<%= points.static %>/scripts',
          src: ['{,*/}*.coffee'],
          dest: '<%= points.static %>/scripts',
          ext: '.js'
        }]
      }
    },
    imagemin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= points.dist %>/static/images',
          src: '{,*/}*.{png,jpg,jpeg}',
          dest: '<%= points.dist %>/static/images'
        }]
      }
    },
    concurrent: {
      server: [
        'coffee:dev',
        'less:dev'
      ]
    },
    copy: {
      images: {
        files: [{
          expand: true,
          cwd: '<%= points.static %>/',
          src: ['images/**'],
          dest: '<%= points.dist %>/static/'
        }]
      },
      html: {
        files: [{
          expand: true,
          cwd: '<%= points.app %>/',
          src: ['*.html'],
          dest: '<%= points.dist %>/'
        }]
      }
    },
    clean: {
      dist: [
      ]
    },
    requirejs: {
      dist: {
        options: {
          // Use almond.js
          // appDir: '<%= points.static %>/scripts/',
          // dir: '<%= points.dist %>/static/scripts/',

          almond: true,
          baseUrl: '<%= points.static %>/scripts/',
          mainConfigFile: '<%= points.static %>/scripts/main.js',

          replaceRequireScript: [{
            files: ['<%= points.dist %>/*.html'],
            module: 'main',
            modulePath: 'static/scripts/app'
          }],
          pragmasOnSave : {
            excludeMdown : true
          },

          shim: {
            'bootstrap.scrollspy': {
              deps: ['jquery']
            },
            'jquery.fixto': {
              deps: ['jquery']
            },
            'Handlebars': {
              exports: 'Handlebars'
            }
          },

          optimize: 'uglify2',

          fileExclusionRegExp: /^(node_modules|.svn)/,
          findNestedDependencies: true,
          include: ['main'],
          stubModules : ['json', 'text'],

          out: '<%= points.dist %>/static/scripts/app.js'
        }
      }
    },
    markdown: {
      all: {
        files: [{
          cwd: '<%= points.static %>/documents',
          src: ['*.md'],
          expand: true,
          dest: '<%= points.static %>/tmp',
          ext: '.html'
        }],
        options: {
          template: 'utils/templates/markdown.html',
          postCompile: function(src, context) {
            var $ = cheerio.load(src);

            function processHtml(stage) {
              var next, newHtml, current, id;

              return function(i, obj) {
                id = $(obj).text().replace(/[\. ,#():-]+/g, '-').toLowerCase();
                next = $(obj).next();
                newHtml = $(obj);
                current = obj;

                async.whilst(
                  function() {
                    if (stage === 'create-sections') {
                      return !next.is('h2') && next.length > 0
                    } else if (stage === 'create-subsections') {
                      return !next.is('h3') && next.length > 0
                    } else {
                      return !next.is('h3') && !next.is('h2') && next.length > 0
                    }
                  },
                  function(callback) {
                      newHtml += '\n'+next;
                      next = next.next();
                      next.prev().remove();
                      callback();
                  },
                  function() {
                    var update;

                    if (stage === 'create-sections') {
                      update = '
\n'+newHtml+'\n
';
                    } else {
                      update = '
\n'+newHtml+'\n
'
                    }

                    $(current).replaceWith(update)
                  }
                );
              }
            }
            async.series([
              function (callback) {
                $('h2').each(processHtml('create-sections'));
                $('h2').each(processHtml('create-h2-subsections'));
                $('h3').each(processHtml('create-subsections'));

                callback();
              },
              function (callback) {
                $('section').each(function(i, obj) {
                  $(obj).children().last().remove();
                });
                $('section').last().next().remove();
                callback();
              }
            ]);

            return $.html()
          }
        }
      }
    }
  });

  grunt.registerTask('generate-markdown-list', function() {
    var files = []
      , paths =[]
      , data = {}
      , template = grunt.file.read('utils/templates/generate-markdown-files.html')
      , writeTo = 'app/static/scripts/modules/load-markdown-documents.coffee';

    grunt.file.recurse('app/static/documents/', function(abspath, rootdir, subdir, filename) {
      abspath = abspath.replace('app/static', 'mdown!../..')
      filename = filename.replace(/\-/g, '_').replace('.md','').replace('.html', '');

      if (filename !== '.DS_Store') {
        files.push(filename);
        paths.push(abspath);
      }
    });

    data = { files: files, paths: paths };

    grunt.file.write(writeTo, grunt.template.process(template, {data: data}));
  });

  grunt.registerTask('build-html', [
    'markdown:all'
  ]);

  grunt.registerTask('server', function (target) {
    grunt.task.run([
      'concurrent:server',
      'connect:livereload',
      'open',
      'watch'
    ]);
  });

  grunt.registerTask('build', [
    'generate-markdown-list',
    'copy:html',
    'coffee:dist',
    'less:dist',
    'requirejs:dist',
    'copy:images',
    'imagemin'
  ]);

  grunt.registerTask('default', [
    'server'
  ]);
};
<|endoftext|>


<commit_before>var correction = require('./correction');
var format = require('util').format;

// Will not change if 2 instances of tennu launched
const helps = {
    "correction": [
        "s/<target>/<replacement>",
        "Correct a previously said message."
    ]
};

var TennuCorrection = {
    //dblogger forces users to meet the dependency. No logger, no data.
    requiresRoles: ["admin", "dbcore", "dblogger"],
    init: function(client, imports) {

        const adminCooldown = client._plugins.getRole("admin-cooldown");

        const requiresAdminHelp = "Requires admin privileges.";

        var isAdmin = imports.admin.isAdmin;
        if (adminCooldown) {
            var cooldown = client.config("correction")['cooldown'];
            if (!cooldown) {
                client._logger.warn('tennu-correction: Cooldown plugin found but no cooldown defined.')
            }
            else {
                isAdmin = adminCooldown.isAdmin;
            }
        }

        const dbACorrectionPromise = imports.dbcore.then(function(knex) {
            return correction(knex);
        });

       function handleCorrection(IRCMessage){

           // Lets do this quickly
           var isSearchAndReplace = IRCMessage.message.match(/^s\/(.+?)\/(.*?)$/);

           if(!isSearchAndReplace)
           {
               return;
           }

           // Build data for correction
           var target = isSearchAndReplace[1];
           var replacement = isSearchAndReplace[2];

           return dbACorrectionPromise.then(function(correction){
               return correction.findCorrectable(target, IRCMessage.channel).then(function(locatedDBTarget){
                   if(!locatedDBTarget)
                   {
                       return {
                           intent: "notice",
                           query: true,
                           message: format('I searched the last 30 messages to the channel but couldnt find anything with "%s" in it', target)
                       };
                   }
                   var corrected = correction.correct(locatedDBTarget.Message, target, replacement);
                   return format('Correction, <%s> %s', locatedDBTarget.FromNick, corrected);
               });
           });
       }

        return {
            handlers: {
                "privmsg": handleCorrection,
            },
            help: {
                "correction": helps.correction
            }
        };

    }
};

module.exports = TennuCorrection;<commit_msg>Adapt to new cooldown plugin<commit_after>var correction = require('./correction');
var format = require('util').format;

// Will not change if 2 instances of tennu launched
const helps = {
    "correction": [
        "s/<target>/<replacement>",
        "Correct a previously said message."
    ]
};

var TennuCorrection = {
    //dblogger forces users to meet the dependency. No logger, no data.
    requiresRoles: ["admin", "dbcore", "dblogger"],
    init: function(client, imports) {

        const requiresAdminHelp = "Requires admin privileges.";

        var correctionConfig = client.config("correction");

        if (!correctionConfig) {
            throw Error("tennu-correction: is missing some or all of its configuration.");
        }

        var isAdmin = imports.admin.isAdmin;
        const adminCooldown = client._plugins.getRole("cooldown");
        if (adminCooldown) {
            var cooldown = correctionConfig['cooldown'];
            if (!cooldown) {
                client._logger.warn('tennu-correction: Cooldown plugin found but no cooldown defined.')
            }
            else {
                isAdmin = adminCooldown(cooldown);
            }
        }

        const dbACorrectionPromise = imports.dbcore.then(function(knex) {
            return correction(knex);
        });

        function handleCorrection(IRCMessage) {

            // Lets do this quickly
            var isSearchAndReplace = IRCMessage.message.match(/^s\/(.+?)\/(.*?)$/);

            if (!isSearchAndReplace) {
                return;
            }

            return isAdmin(IRCMessage.hostmask).then(function(isadmin) {
                // isAdmin will be "undefined" if cooldown system is enabled
                // isAdmin will be true/false if cooldown system is disabled
                if (typeof(isAdmin) !== "undefined" && isAdmin === false) {
                    throw new Error(requiresAdminHelp);
                }

                // Build data for correction
                var target = isSearchAndReplace[1];
                var replacement = isSearchAndReplace[2];

                return dbACorrectionPromise.then(function(correction) {
                    return correction.findCorrectable(target, IRCMessage.channel).then(function(locatedDBTarget) {
                        if (!locatedDBTarget) {
                            return {
                                intent: "notice",
                                query: true,
                                message: format('I searched the last 30 messages to the channel but couldnt find anything with "%s" in it', target)
                            };
                        }
                        var corrected = correction.correct(locatedDBTarget.Message, target, replacement);
                        return format('Correction, <%s> %s', locatedDBTarget.FromNick, corrected);
                    });
                });

            }).catch(adminFail);

        }

        function adminFail(err) {
            return {
                intent: 'notice',
                query: true,
                message: err
            };
        }

        return {
            handlers: {
                "privmsg": handleCorrection,
            },
            help: {
                "correction": helps.correction
            }
        };

    }
};

module.exports = TennuCorrection;<|endoftext|>


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

    var REG_CHECK_EMPTY_STRING = /^(\u200B|\ufeff)*$/;
    var REG_REPLACE_EMPTY_CHAR = /\u200B|\ufeff/g;
    var REG_CHECK_LINK = /(?:https?:\/\/|ssh:\/\/|ftp:\/\/|file:\/|www\.|mailto:)/i;
    var REG_CHECK_LINK_START = /^(?:https?:\/\/|ssh:\/\/|ftp:\/\/|file:\/|www\.|mailto:)/i;
    var REG_PROTO_HTTP = /^(?:https?:\/\/|ssh:\/\/|ftp:\/\/|file:\/|mailto:)/i;
    var REG_MAILTO = /^mailto:([^\?]+)/i;
    var REG_EMAIL = /^[a-zа-яёÇçĞğIıİiÖöŞşÜüẞß0-9!#$%&'*+\/=?.^_`{|}~-]+?@(?:[a-zа-яёÇçĞğIıİiÖöŞşÜüẞß0-9](?:[a-zа-яёÇçĞğIıİiÖöŞşÜüẞß0-9-_]*?[a-zа-яёÇçĞğIıİiÖöŞşÜüẞß0-9])?\.)+?(?:xn--[-a-z0-9]+|[a-zа-яё]{2,}|\d{1,3})$/i;
    var REG_CHECK_EMAIL = /(?:^|\s+)[a-zа-яёÇçĞğIıİiÖöŞşÜüẞß0-9!#$%&'*+\/=?.^_`{|}~-]+?@(?:[a-zа-яёÇçĞğIıİiÖöŞşÜüẞß0-9](?:[a-zа-яёÇçĞğIıİiÖöŞşÜüẞß0-9-_]*?[a-zа-яёÇçĞğIıİiÖöŞşÜüẞß0-9])?\.)+?(?:xn--[-a-z0-9]+|[a-zа-яё]{2,}|\d{1,3})(?:$|\s+)/i;
    var REG_CHECK_EMAIL_START = /^[a-zа-яёÇçĞğIıİiÖöŞşÜüẞß0-9!#$%&'*+\/=?.^_`{|}~-]+?@(?:[a-zа-яёÇçĞğIıİiÖöŞşÜüẞß0-9](?:[a-zа-яёÇçĞğIıİiÖöŞşÜüẞß0-9-_]*?[a-zа-яёÇçĞğIıİiÖöŞşÜüẞß0-9])?\.)+?(?:xn--[-a-z0-9]+|[a-zа-яё]{2,}|\d{1,3})/i;
    var REG_BREAK_STRING = /(?:^|\s)\S+$/;

    CKEDITOR.plugins.add('autolink2', {
        'modes': { 'wysiwyg': 1 },

        'init': function(editor) {
            editor.addCommand('autolink2', {
                'modes': { 'wysiwyg': 1 },
                'editorFocus': false,
                'exec': autolink
            } );

            editor.on('key', function(event) {
                if (this.mode !== 'wysiwyg') {
                    return;
                }

                if (event.data.keyCode === 32 || event.data.keyCode === 13) {
                    this.execCommand('autolink2');
                }
            });
        }
    });

    function autolink(editor) {
        var context = editor.editable().$;
        var selection = editor.getSelection();
        var rangeNative = selection.getNative().getRangeAt(0).cloneRange();
        var offset;
        var charCode;
        var start = rangeNative.startContainer;
        var execReg;
        var diff;

        while (start.nodeType === Node.ELEMENT_NODE && rangeNative.startOffset > 0) {
            start = rangeNative.startContainer.childNodes[ rangeNative.startOffset - 1 ];
            if (!start) {
                break;
            }

            rangeNative.setStart(start, getOffsetNode(start));
            rangeNative.collapse(true);
            start = rangeNative.startContainer;
        }

        do {
            diff = -1;

            if (rangeNative.startOffset === 0) {
                start = rangeNative.startContainer.previousSibling;

                while (start && start.nodeType === Node.ELEMENT_NODE) {
                    if (isEmptyNode(start)) {
                        break;
                    }

                    if (!(CKEDITOR.env.gecko && (start = start.firstChild))) {
                        start = start.lastChild;
                    }
                }

                if (!start) {
                    break;
                }

                offset = getOffsetNode(start) || 1;

                if (start.nodeType === Node.TEXT_NODE) {
                    if (!REG_CHECK_EMPTY_STRING.test(start.nodeValue)) {
                        if ((execReg = REG_BREAK_STRING.exec(start.nodeValue))) {
                            offset = execReg.index;
                            diff = 0;

                        } else {
                            break;
                        }
                    }
                }

            } else {
                start = rangeNative.startContainer;
                offset = rangeNative.startOffset;
            }

            offset = offset + diff;

            if (offset < 0) {
                break;
            }

            rangeNative.setStart(start, offset);
            charCode = rangeNative.toString().charCodeAt(0);

        } while (charCode !== 160 && charCode !== 32);

        var rangeString = rangeNative.toString().replace(REG_REPLACE_EMPTY_CHAR, '');
        var isLink = REG_CHECK_LINK.test(rangeString);
        var isEmail = REG_CHECK_EMAIL.test(rangeString);

        if (!isLink && !isEmail) {
            return;
        }

        var next;
        while ((rangeString = rangeNative.toString())) {
            if (isLink && REG_CHECK_LINK_START.test(rangeString)) {
                break;
            }

            if (isEmail && REG_CHECK_EMAIL_START.test(rangeString)) {
                break;
            }

            try {
                rangeNative.setStart(rangeNative.startContainer, rangeNative.startOffset + 1);

            } catch (error) {
                start = rangeNative.startContainer;

                while (!(next = start.nextSibling)) {
                    if (!context.contains(start)) {
                        return;
                    }

                    start = start.parentNode;
                }

                rangeNative.setStart(next, 0);
            }
        }

        var mailto = rangeNative.toString().match(REG_MAILTO);
        if (mailto) {
            if (!REG_EMAIL.test(mailto[ 1 ])) {
                return;
            }
        }

        var parent = rangeNative.startContainer;
        do {
            if (!context.contains(parent)) {
                break;
            }

            if (parent.tagName === 'A') {
                return;
            }

        } while ((parent = parent.parentNode));

        applyLink(rangeNative, editor);
    }

    function applyLink(rangeNative, editor) {
        editor.fire('saveSnapshot');

        var range = editor.createRange();
        var startNode = new CKEDITOR.dom.node(rangeNative.startContainer);
        var endNode = new CKEDITOR.dom.node(rangeNative.endContainer);

        range.setStart(startNode, rangeNative.startOffset);
        range.setEnd(endNode, rangeNative.endOffset);

        var href = rangeNative.toString().replace(REG_REPLACE_EMPTY_CHAR, '');
        href = CKEDITOR.tools.htmlDecodeAttr(href);

        if (!REG_PROTO_HTTP.test(href)) {
            if (REG_EMAIL.test(href)) {
                href = 'mailto:' + href;

            } else {
                href = 'http://' + href;
            }
        }

        var style = new CKEDITOR.style({
            'element': 'a',
            'attributes': { 'href': href }
        });

        style.type = CKEDITOR.STYLE_INLINE;
        style.applyToRange(range, editor);

        editor.fire('saveSnapshot');

        var linkNode = range.getCommonAncestor();
        var textNode = new CKEDITOR.dom.text('');
        textNode.insertAfter(linkNode);

        range = editor.createRange();
        range.setStart(textNode);
        range.collapse();
        editor.getSelection().selectRanges([ range ]);
    }

    function isEmptyNode(node) {
        if (CKEDITOR.dtd.$inline[ node.tagName.toLowerCase() ] &&
            !node.textContent.replace(REG_REPLACE_EMPTY_CHAR, '').length) {

            return true;
        }

        return false;
    }

    function getOffsetNode(node) {
        return node.nodeType === Node.ELEMENT_NODE ?
            node.childNodes.length :
            node.nodeValue.length;
    }

}());
<commit_msg>Exclude punctuation mark at the end of link.<commit_after>(function() {
    'use strict';

    var REG_CHECK_EMPTY_STRING = /^(\u200B|\ufeff)*$/;
    var REG_REPLACE_EMPTY_CHAR = /\u200B|\ufeff/g;
    var REG_CHECK_LINK = /(?:https?:\/\/|ssh:\/\/|ftp:\/\/|file:\/|www\.|mailto:)/i;
    var REG_CHECK_LINK_START = /^(?:https?:\/\/|ssh:\/\/|ftp:\/\/|file:\/|www\.|mailto:)/i;
    var REG_PROTO_HTTP = /^(?:https?:\/\/|ssh:\/\/|ftp:\/\/|file:\/|mailto:)/i;
    var REG_MAILTO = /^mailto:([^\?]+)/i;
    var REG_EMAIL = /^[a-zа-яёÇçĞğIıİiÖöŞşÜüẞß0-9!#$%&'*+\/=?.^_`{|}~-]+?@(?:[a-zа-яёÇçĞğIıİiÖöŞşÜüẞß0-9](?:[a-zа-яёÇçĞğIıİiÖöŞşÜüẞß0-9-_]*?[a-zа-яёÇçĞğIıİiÖöŞşÜüẞß0-9])?\.)+?(?:xn--[-a-z0-9]+|[a-zа-яё]{2,}|\d{1,3})$/i;
    var REG_CHECK_EMAIL = /(?:^|\s+)[a-zа-яёÇçĞğIıİiÖöŞşÜüẞß0-9!#$%&'*+\/=?.^_`{|}~-]+?@(?:[a-zа-яёÇçĞğIıİiÖöŞşÜüẞß0-9](?:[a-zа-яёÇçĞğIıİiÖöŞşÜüẞß0-9-_]*?[a-zа-яёÇçĞğIıİiÖöŞşÜüẞß0-9])?\.)+?(?:xn--[-a-z0-9]+|[a-zа-яё]{2,}|\d{1,3})(?:$|\s+)/i;
    var REG_CHECK_EMAIL_START = /^[a-zа-яёÇçĞğIıİiÖöŞşÜüẞß0-9!#$%&'*+\/=?.^_`{|}~-]+?@(?:[a-zа-яёÇçĞğIıİiÖöŞşÜüẞß0-9](?:[a-zа-яёÇçĞğIıİiÖöŞşÜüẞß0-9-_]*?[a-zа-яёÇçĞğIıİiÖöŞşÜüẞß0-9])?\.)+?(?:xn--[-a-z0-9]+|[a-zа-яё]{2,}|\d{1,3})/i;
    var REG_BREAK_STRING = /(?:^|\s)\S+$/;
    var TRAILING_PUNCTUATION = /([,.!:;?]+)$/;

    CKEDITOR.plugins.add('autolink2', {
        'modes': { 'wysiwyg': 1 },

        'init': function(editor) {
            editor.addCommand('autolink2', {
                'modes': { 'wysiwyg': 1 },
                'editorFocus': false,
                'exec': autolink
            } );

            editor.on('key', function(event) {
                if (this.mode !== 'wysiwyg') {
                    return;
                }

                if (event.data.keyCode === 32 || event.data.keyCode === 13) {
                    this.execCommand('autolink2');
                }
            });
        }
    });

    function autolink(editor) {
        var context = editor.editable().$;
        var selection = editor.getSelection();
        var rangeNative = selection.getNative().getRangeAt(0).cloneRange();
        var offset;
        var charCode;
        var start = rangeNative.startContainer;
        var execReg;
        var diff;
        var savedCursorPosition = saveCursorPosition(selection);

        while (start.nodeType === Node.ELEMENT_NODE && rangeNative.startOffset > 0) {
            start = rangeNative.startContainer.childNodes[ rangeNative.startOffset - 1 ];
            if (!start) {
                break;
            }

            rangeNative.setStart(start, getOffsetNode(start));
            rangeNative.collapse(true);
            start = rangeNative.startContainer;
        }

        do {
            diff = -1;

            if (rangeNative.startOffset === 0) {
                start = rangeNative.startContainer.previousSibling;

                while (start && start.nodeType === Node.ELEMENT_NODE) {
                    if (isEmptyNode(start)) {
                        break;
                    }

                    if (!(CKEDITOR.env.gecko && (start = start.firstChild))) {
                        start = start.lastChild;
                    }
                }

                if (!start) {
                    break;
                }

                offset = getOffsetNode(start) || 1;

                if (start.nodeType === Node.TEXT_NODE) {
                    if (!REG_CHECK_EMPTY_STRING.test(start.nodeValue)) {
                        if ((execReg = REG_BREAK_STRING.exec(start.nodeValue))) {
                            offset = execReg.index;
                            diff = 0;

                        } else {
                            break;
                        }
                    }
                }

            } else {
                start = rangeNative.startContainer;
                offset = rangeNative.startOffset;
            }

            offset = offset + diff;

            if (offset < 0) {
                break;
            }

            rangeNative.setStart(start, offset);
            charCode = rangeNative.toString().charCodeAt(0);

        } while (charCode !== 160 && charCode !== 32);

        var rangeString = rangeNative.toString().replace(REG_REPLACE_EMPTY_CHAR, '');
        var isLink = REG_CHECK_LINK.test(rangeString);
        var isEmail = REG_CHECK_EMAIL.test(rangeString);

        if (!isLink && !isEmail) {
            return;
        }

        var next;
        while ((rangeString = rangeNative.toString())) {
            if (isLink && REG_CHECK_LINK_START.test(rangeString)) {
                break;
            }

            if (isEmail && REG_CHECK_EMAIL_START.test(rangeString)) {
                break;
            }

            try {
                rangeNative.setStart(rangeNative.startContainer, rangeNative.startOffset + 1);

            } catch (error) {
                start = rangeNative.startContainer;

                while (!(next = start.nextSibling)) {
                    if (!context.contains(start)) {
                        return;
                    }

                    start = start.parentNode;
                }

                rangeNative.setStart(next, 0);
            }
        }

        var mailto = rangeNative.toString().match(REG_MAILTO);
        if (mailto) {
            if (!REG_EMAIL.test(mailto[ 1 ])) {
                return;
            }
        }

        var parent = rangeNative.startContainer;
        do {
            if (!context.contains(parent)) {
                break;
            }

            if (parent.tagName === 'A') {
                return;
            }

        } while ((parent = parent.parentNode));

        // Excluding of punctuation mark at the end of link.
        var linkEndsWithPunctuationMark = isLink && TRAILING_PUNCTUATION.exec(rangeString);
        if (linkEndsWithPunctuationMark) {
            var changedEndOffset = rangeNative.endOffset - linkEndsWithPunctuationMark[1].length;
            // changedEndOffset will be less than 0 if rangeNative contains not only TextNodes(e.g. HTMLImageElement)
            if (changedEndOffset >= 0) {
                rangeNative.setEnd(rangeNative.endContainer, changedEndOffset);
            }
        }

        applyLink(rangeNative, editor, savedCursorPosition);
    }

    function applyLink(rangeNative, editor, savedCursorPosition) {
        editor.fire('saveSnapshot');

        var range = editor.createRange();
        var startNode = new CKEDITOR.dom.node(rangeNative.startContainer);
        var endNode = new CKEDITOR.dom.node(rangeNative.endContainer);

        range.setStart(startNode, rangeNative.startOffset);
        range.setEnd(endNode, rangeNative.endOffset);

        var href = rangeNative.toString().replace(REG_REPLACE_EMPTY_CHAR, '');
        href = CKEDITOR.tools.htmlDecodeAttr(href);

        if (!REG_PROTO_HTTP.test(href)) {
            if (REG_EMAIL.test(href)) {
                href = 'mailto:' + href;

            } else {
                href = 'http://' + href;
            }
        }

        var style = new CKEDITOR.style({
            'element': 'a',
            'attributes': { 'href': href }
        });

        style.type = CKEDITOR.STYLE_INLINE;
        style.applyToRange(range, editor);

        editor.fire('saveSnapshot');
        restoreCursorPosition(editor, savedCursorPosition);
    }

    function saveCursorPosition(selection) {
        var savedCursorPosition = new CKEDITOR.dom.text('');
        var tempRange = selection.getRanges()[0].clone();
        tempRange.collapse();
        tempRange.insertNode(savedCursorPosition);
        return savedCursorPosition;
    }

    function restoreCursorPosition(editor, savedCursorPosition) {
        var range = editor.createRange();
        range.setStart(savedCursorPosition);
        range.collapse();
        editor.getSelection().selectRanges([ range ]);
    }

    function isEmptyNode(node) {
        if (CKEDITOR.dtd.$inline[ node.tagName.toLowerCase() ] &&
            !node.textContent.replace(REG_REPLACE_EMPTY_CHAR, '').length) {

            return true;
        }

        return false;
    }

    function getOffsetNode(node) {
        return node.nodeType === Node.ELEMENT_NODE ?
            node.childNodes.length :
            node.nodeValue.length;
    }

}());
<|endoftext|>