<commit_before>var Resources = require('../conf.js');
var Mongoose = require('mongoose');
var Tunnel = require('tunnel-ssh');
var Conf = require('../conf.js');
var TvMaze = require('../libs/tvMaze.js');
var Common = require('../common.js');
var ScheduleManager = require('../schedule/scheduleManager.js');
var Logger = require('../log/logger.js');
var BotGui = require('../gui/keyboards.js');

var db = undefined;
var Schema = Mongoose.Schema;
Mongoose.set('debug', true);

var Alert = Mongoose.model('Alert', new Schema({
    ids: String,
    show_name: String,
    showId: Number,
    language: Schema.Types.Mixed,
    nextepisode_airdate: String,
    nextepisode_season: Number,
    nextepisode_episode: Number
}, {
        _id: false
    }));
var User = Mongoose.model('User', new Schema({
    ids: String,
    chatId: Number,
    first_name: String,
    alerts: Array
}));
var Language = Mongoose.model('Language', new Schema({
    code: String,
    int: String,
    native: String
}, {
        _id: false
    }));

exports.Alert = Alert;
exports.User = User;
exports.Language = Language;
exports.mongoConnection = db;

exports.connectToDatabase = function () {
    var server = Tunnel(Conf.mongoConfig, function (error, server) {
        if (error) {
            console.log("SSH connection error: " + error);
        }
        // if(Conf.mongoHost == "raspi") Mongoose.connect('mongodb://127.0.0.1:');
        // else
        Mongoose.connect('mongodb://localhost:' + Conf.mongoConfig.localPort + '/' + Conf.dbName);
        db = Mongoose.connection;
        db.on('error', () => {
            console.log('DB connection error ')
        });
        db.once('open', function () {
            console.log("DB connection successful");
        });
    });
}

exports.subscribe = function (session, bot, from) {
    Logger.logEvent("alert", [], session);
    var alertsToStore = [];
    var alertsIdList = [];
    if (session.choosenSeriesAlert.show._links.nextepisode) {
        var nextepisodePromise = TvMaze.getNextEpisodeInformation(session.choosenSeriesAlert.show._links.nextepisode.href);

        nextepisodePromise.then(function (nextepisode) {
            session.chosenLanguagesAlert.forEach(function (languageElement, index) {
                var alertToStore = new Alert({
                    show_name: session.choosenSeriesAlert.show.name,
                    showId: session.choosenSeriesAlert.show.id,
                    language: languageElement,
                    nextepisode_airdate: nextepisode.airdate,
                    nextepisode_season: nextepisode.season,
                    nextepisode_episode: nextepisode.number
                    // FOR DEBUG:
                    // nextepisode_airdate: "today",
                    // nextepisode_season: "1",
                    // nextepisode_episode: "1"
                });
                if (alertToStore._id === undefined) {
                    delete alertToStore._id;
                }
                Alert.findOneAndUpdate({ showId: alertToStore.showId, language: languageElement },
                    alertToStore, { new: true, upsert: true },
                    function (err, storedAlert) {
                        if (err) console.log("ERROR IN SAVE MONGO", err);
                        else {
                            ScheduleManager.activateStoredSchedules(storedAlert._doc, bot);
                            alertsIdList.push(storedAlert._doc._id.toString());

                            if (index == session.chosenLanguagesAlert.length - 1) {
                                subscribeUser(alertsIdList, session, bot, from);
                            }
                        }
                    }
                );
            });
        });
    } else {
        bot.sendMessage(from.id, nextEpisodeNotAvailableMessage);
        Common.resetValues(session);
    }
}

function subscribeUser(alertsList, session, bot, from) {
    var alertsToAdd = [];
    User.findOne({ chatId: from.id }, function (err, user) {
        if (!user) {
            var newUser = new User({
                chatId: from.id,
                first_name: from.first_name,
                alerts: alertsList
            });
            User.create(newUser, function (err, value) {
                if (err) console.log("error saving new user");
            });
        } else {
            user._doc.alerts.addToSet(alertsList);
            user.save(function () {
                bot.sendMessage(from.id, Common.successSubscribeMessage(session.choosenSeriesAlert.show.name));
                Common.resetValues(session);
            });

        }
    });
}

exports.getAlertsFromUser = function(id, bot){
    var alerts = [];
    User.findOne({ chatId: id }, function (err, user) {
        if (user) {
            user._doc.alerts.forEach(function(alertId, index) {
                Alert.findById(Mongoose.Types.ObjectId(alertId), function (err, foundAlert) {
                    alerts.push(foundAlert);
                        if(index == user.alerts.length - 1){
                            if(alerts.length > 0) bot.sendMessage(id, Common.showAlertsMessage, BotGui.generateAlertsInlineKeyboard(alerts));
                    }
                });

            });
        }
    });
}<commit_msg>trying without port on mongo conn<commit_after>var Resources = require('../conf.js');
var Mongoose = require('mongoose');
var Tunnel = require('tunnel-ssh');
var Conf = require('../conf.js');
var TvMaze = require('../libs/tvMaze.js');
var Common = require('../common.js');
var ScheduleManager = require('../schedule/scheduleManager.js');
var Logger = require('../log/logger.js');
var BotGui = require('../gui/keyboards.js');

var db = undefined;
var Schema = Mongoose.Schema;
Mongoose.set('debug', true);

var Alert = Mongoose.model('Alert', new Schema({
    ids: String,
    show_name: String,
    showId: Number,
    language: Schema.Types.Mixed,
    nextepisode_airdate: String,
    nextepisode_season: Number,
    nextepisode_episode: Number
}, {
        _id: false
    }));
var User = Mongoose.model('User', new Schema({
    ids: String,
    chatId: Number,
    first_name: String,
    alerts: Array
}));
var Language = Mongoose.model('Language', new Schema({
    code: String,
    int: String,
    native: String
}, {
        _id: false
    }));

exports.Alert = Alert;
exports.User = User;
exports.Language = Language;
exports.mongoConnection = db;

exports.connectToDatabase = function () {
    var server = Tunnel(Conf.mongoConfig, function (error, server) {
        if (error) {
            console.log("SSH connection error: " + error);
        }
        // if(Conf.mongoHost == "raspi") Mongoose.connect('mongodb://127.0.0.1:');
        // else
        //Mongoose.connect('mongodb://localhost:' + Conf.mongoConfig.localPort + '/' + Conf.dbName);
        Mongoose.connect('mongodb://localhost/' + Conf.dbName);
        db = Mongoose.connection;
        db.on('error', () => {
            console.log('DB connection error ')
        });
        db.once('open', function () {
            console.log("DB connection successful");
        });
    });
}

exports.subscribe = function (session, bot, from) {
    Logger.logEvent("alert", [], session);
    var alertsToStore = [];
    var alertsIdList = [];
    if (session.choosenSeriesAlert.show._links.nextepisode) {
        var nextepisodePromise = TvMaze.getNextEpisodeInformation(session.choosenSeriesAlert.show._links.nextepisode.href);

        nextepisodePromise.then(function (nextepisode) {
            session.chosenLanguagesAlert.forEach(function (languageElement, index) {
                var alertToStore = new Alert({
                    show_name: session.choosenSeriesAlert.show.name,
                    showId: session.choosenSeriesAlert.show.id,
                    language: languageElement,
                    nextepisode_airdate: nextepisode.airdate,
                    nextepisode_season: nextepisode.season,
                    nextepisode_episode: nextepisode.number
                    // FOR DEBUG:
                    // nextepisode_airdate: "today",
                    // nextepisode_season: "1",
                    // nextepisode_episode: "1"
                });
                if (alertToStore._id === undefined) {
                    delete alertToStore._id;
                }
                Alert.findOneAndUpdate({ showId: alertToStore.showId, language: languageElement },
                    alertToStore, { new: true, upsert: true },
                    function (err, storedAlert) {
                        if (err) console.log("ERROR IN SAVE MONGO", err);
                        else {
                            ScheduleManager.activateStoredSchedules(storedAlert._doc, bot);
                            alertsIdList.push(storedAlert._doc._id.toString());

                            if (index == session.chosenLanguagesAlert.length - 1) {
                                subscribeUser(alertsIdList, session, bot, from);
                            }
                        }
                    }
                );
            });
        });
    } else {
        bot.sendMessage(from.id, nextEpisodeNotAvailableMessage);
        Common.resetValues(session);
    }
}

function subscribeUser(alertsList, session, bot, from) {
    var alertsToAdd = [];
    User.findOne({ chatId: from.id }, function (err, user) {
        if (!user) {
            var newUser = new User({
                chatId: from.id,
                first_name: from.first_name,
                alerts: alertsList
            });
            User.create(newUser, function (err, value) {
                if (err) console.log("error saving new user");
            });
        } else {
            user._doc.alerts.addToSet(alertsList);
            user.save(function () {
                bot.sendMessage(from.id, Common.successSubscribeMessage(session.choosenSeriesAlert.show.name));
                Common.resetValues(session);
            });

        }
    });
}

exports.getAlertsFromUser = function(id, bot){
    var alerts = [];
    User.findOne({ chatId: id }, function (err, user) {
        if (user) {
            user._doc.alerts.forEach(function(alertId, index) {
                Alert.findById(Mongoose.Types.ObjectId(alertId), function (err, foundAlert) {
                    alerts.push(foundAlert);
                        if(index == user.alerts.length - 1){
                            if(alerts.length > 0) bot.sendMessage(id, Common.showAlertsMessage, BotGui.generateAlertsInlineKeyboard(alerts));
                    }
                });

            });
        }
    });
}<|endoftext|>


<commit_before>/*global window, document, Reveal, pwl*/
;(function(Reveal, pwl){
    'use strict';
    var system = new pwl.System();

    var r = 114;
    document.body.addEventListener('keypress', function(event){
        if (event.charCode === r) {
            pwl.connector.reset();
        }
    });

    Reveal.addEventListener('slidechanged', function(){
        pwl.connector.reset();
    });

    var isRendered = { /* used to keep track of which slides are already rendered */ };
    Reveal.addEventListener('diagram.introduction', function(event){
	    if (!isRendered[event.type]) {
	        isRendered[event.type] = true;
	        var container = document.getElementById('diagram.introduction');
	        container.addEventListener('mousedown', function(event){
		        if (event.shiftKey) {
		            system.createProcess();
		        }
	        });

	        new pwl.SystemView(system, container, { width: 640, height: 480 });
	    }
    });
    Reveal.addEventListener('diagram.happend-before', function(event){
	    if (!isRendered[event.type]) {
	        isRendered[event.type] = true;
	        var container = document.getElementById('diagram.happend-before');
            var happendBefore = new pwl.System();
	        new pwl.SystemView(happendBefore, container, { width: 640, height: 480 });
            var p = happendBefore.createProcess();
            p.createEvent();
            p.createEvent();
	    }
    });

    window.system = system;
})(Reveal, pwl);
<commit_msg>abstract rendering of diagram<commit_after>/*global window, document, Reveal, pwl*/
;(function(Reveal, pwl){
    'use strict';
    var system = new pwl.System();

    var r = 114;
    document.body.addEventListener('keypress', function(event){
        if (event.charCode === r) {
            pwl.connector.reset();
        }
    });

    Reveal.addEventListener('slidechanged', function(){
        pwl.connector.reset();
    });

    var isRendered = { /* used to keep track of which slides are already rendered */ };
    function render(id, callback){
        Reveal.addEventListener(id, function(event){
	        if (!isRendered[event.type]) {
	            isRendered[event.type] = true;
                callback(id);
	        }
        });
    }
    render('diagram.introduction', function(){
	    var container = document.getElementById('diagram.introduction');
	    container.addEventListener('mousedown', function(event){
		    if (event.shiftKey) {
		        system.createProcess();
		    }
	    });

	    new pwl.SystemView(system, container, { width: 640, height: 480 });
    });
    render('diagram.happend-before', function(){
	    var container = document.getElementById('diagram.happend-before');
        var happendBefore = new pwl.System();
	    new pwl.SystemView(happendBefore, container, { width: 640, height: 480 });
        var p = happendBefore.createProcess();
        p.createEvent();
        p.createEvent();
    });

    window.system = system;
})(Reveal, pwl);
<|endoftext|>


<commit_before>$(function() {
    var masterURL = "http://download.go.cd/";
    init();

    function init() {
        fetchArtifacts(function(artifactList) {
            renderInstallersByOS(artifactList, "mac", 'mac-revisions', 'gocd');
            renderInstallersByOS(artifactList, "solaris", 'solaris-revisions', 'gocd');
            renderInstallersByOS(artifactList, "linuxDeb", 'linuxDeb-revisions', 'gocd-deb');
            renderInstallersByOS(artifactList, "linuxRpm", 'linuxRpm-revisions', 'gocd-rpm');
            renderInstallersByOS(artifactList, "package", 'package-revisions', 'gocd');
            renderInstallersByOS(artifactList, "windows", 'windows-revisions', 'gocd');
        });
    }

    function hideLoader() {
        $('#download-loader').remove();
    }

    function fetchArtifacts(callbackFn) {
        $.getJSON("http://download.go.cd/local/releases.json", function(ArtifactList, status) {
            var supported = _.where(ArtifactList, {release_type: "supported"});
            var unsupported = _.reject(ArtifactList, {release_type: "supported"}).reverse();
            callbackFn(supported.concat(unsupported));
            hideLoader();
        });

    }

    function renderInstallersByOS(artifactList, os, revisionHolder, subDirectory) {
        var i = 0;
        var revisionsString = '';
        while (i < artifactList.length) {
            var artifact = artifactList[i];
            var fileName = artifact.release_type;

            if (artifact.release_type == "supported") {
                $('#latestVersion').html(artifact.version);
            }
            if (artifact.release_type != "supported") {
                subDirectory = 'local/' + artifact.version;
            }

            revisionsString += "
";
            revisionsString += "
"
            revisionsString += "" + artifact.version + "" + " (" + artifact.git_revision + ")";

            var releasedTime = new Date(artifact.release_time * 1000);
            revisionsString += "" + $.timeago(releasedTime.getFullYear() + '-' + (releasedTime.getMonth() + 1) + '-' + releasedTime.getDate()) + "";

            revisionsString += "
"

            revisionsString += "
";
            revisionsString += "
";
            var j = 0;
            while (j < artifact.files.length) {
                if (!artifact.files[j].type.indexOf(os)) {
                    var fileName = artifact.files[j].name;
                    var splitArtifactType = artifact.files[j].type.split("-");
                    var GTMID = splitArtifactType[0].charAt(0).toUpperCase() + splitArtifactType[0].slice(1) + '-' + splitArtifactType[1].charAt(0).toUpperCase() + splitArtifactType[1].slice(1) + "-" + artifact.version;

                    if (artifact.files[j].name.indexOf("server") > 0) {
                        revisionsString += "Server + ";

                    } else if (artifact.files[j].name.indexOf("agent") > 0) {
                        revisionsString += "Agent";
                    }
                }
                j++;
            }
            revisionsString += "
";

            revisionsString += '
'
            var j = 0;
            while (j < artifact.files.length) {
                if (!artifact.files[j].type.indexOf(os)) {
                    var file = artifact.files[j];

                    if (artifact.files[j].name.indexOf("server") > 0) {
                        revisionsString += '
';
                        revisionsString += "
 Server MD5 " + file.md5sum + "
";
                        revisionsString += "
 Server SHA1 " + file.sha1sum + "
";
                        revisionsString += '
';

                    } else if (artifact.files[j].name.indexOf("agent") > 0) {
                        revisionsString += '
';
                        revisionsString += "
 Agent MD5 " + file.md5sum + "
";
                        revisionsString += "
 Agent SHA1 " + file.sha1sum + "
";
                        revisionsString += '
';
                    }
                }
                j++;
            }
            revisionsString += '
';

            revisionsString += "
"
            revisionsString += "
";
            i++;
        }
        $('#' + revisionHolder).append(revisionsString);
    }
});

$(window).load(function() {
    var userOnOS = detectOS();
    if (userOnOS == "NotDetected")
        userOnOS = "windows";
    $('a[href="#' + userOnOS + '"]').tab('show');

    function detectOS() {
        if (navigator.appVersion.indexOf("Win") != -1)
            return "windows";
        else if (navigator.appVersion.indexOf("Mac") != -1)
            return "mac";
        else if (navigator.appVersion.indexOf("Linux") != -1)
            return "linux-deb";
        else if (navigator.appVersion.indexOf("Solaris") != -1)
            return "solaris";
        else "NotDetected"
    }
});
<commit_msg>#57 - change separator for GTMIDs (part3)<commit_after>$(function() {
    var masterURL = "http://download.go.cd/";
    init();

    function init() {
        fetchArtifacts(function(artifactList) {
            renderInstallersByOS(artifactList, "mac", 'mac-revisions', 'gocd');
            renderInstallersByOS(artifactList, "solaris", 'solaris-revisions', 'gocd');
            renderInstallersByOS(artifactList, "linuxDeb", 'linuxDeb-revisions', 'gocd-deb');
            renderInstallersByOS(artifactList, "linuxRpm", 'linuxRpm-revisions', 'gocd-rpm');
            renderInstallersByOS(artifactList, "package", 'package-revisions', 'gocd');
            renderInstallersByOS(artifactList, "windows", 'windows-revisions', 'gocd');
        });
    }

    function hideLoader() {
        $('#download-loader').remove();
    }

    function fetchArtifacts(callbackFn) {
        $.getJSON("http://download.go.cd/local/releases.json", function(ArtifactList, status) {
            var supported = _.where(ArtifactList, {release_type: "supported"});
            var unsupported = _.reject(ArtifactList, {release_type: "supported"}).reverse();
            callbackFn(supported.concat(unsupported));
            hideLoader();
        });

    }

    function renderInstallersByOS(artifactList, os, revisionHolder, subDirectory) {
        var i = 0;
        var revisionsString = '';
        while (i < artifactList.length) {
            var artifact = artifactList[i];
            var fileName = artifact.release_type;

            if (artifact.release_type == "supported") {
                $('#latestVersion').html(artifact.version);
            }
            if (artifact.release_type != "supported") {
                subDirectory = 'local/' + artifact.version;
            }

            revisionsString += "
";
            revisionsString += "
"
            revisionsString += "" + artifact.version + "" + " (" + artifact.git_revision + ")";

            var releasedTime = new Date(artifact.release_time * 1000);
            revisionsString += "" + $.timeago(releasedTime.getFullYear() + '-' + (releasedTime.getMonth() + 1) + '-' + releasedTime.getDate()) + "";

            revisionsString += "
"

            revisionsString += "
";
            revisionsString += "
";
            var j = 0;
            while (j < artifact.files.length) {
                if (!artifact.files[j].type.indexOf(os)) {
                    var fileName = artifact.files[j].name;
                    var splitArtifactType = artifact.files[j].type.split("-");
                    var GTMID = splitArtifactType[0].charAt(0).toUpperCase() + splitArtifactType[0].slice(1) + '-' + splitArtifactType[1].charAt(0).toUpperCase() + splitArtifactType[1].slice(1) + "_" + artifact.version;

                    if (artifact.files[j].name.indexOf("server") > 0) {
                        revisionsString += "Server + ";

                    } else if (artifact.files[j].name.indexOf("agent") > 0) {
                        revisionsString += "Agent";
                    }
                }
                j++;
            }
            revisionsString += "
";

            revisionsString += '
'
            var j = 0;
            while (j < artifact.files.length) {
                if (!artifact.files[j].type.indexOf(os)) {
                    var file = artifact.files[j];

                    if (artifact.files[j].name.indexOf("server") > 0) {
                        revisionsString += '
';
                        revisionsString += "
 Server MD5 " + file.md5sum + "
";
                        revisionsString += "
 Server SHA1 " + file.sha1sum + "
";
                        revisionsString += '
';

                    } else if (artifact.files[j].name.indexOf("agent") > 0) {
                        revisionsString += '
';
                        revisionsString += "
 Agent MD5 " + file.md5sum + "
";
                        revisionsString += "
 Agent SHA1 " + file.sha1sum + "
";
                        revisionsString += '
';
                    }
                }
                j++;
            }
            revisionsString += '
';

            revisionsString += "
"
            revisionsString += "
";
            i++;
        }
        $('#' + revisionHolder).append(revisionsString);
    }
});

$(window).load(function() {
    var userOnOS = detectOS();
    if (userOnOS == "NotDetected")
        userOnOS = "windows";
    $('a[href="#' + userOnOS + '"]').tab('show');

    function detectOS() {
        if (navigator.appVersion.indexOf("Win") != -1)
            return "windows";
        else if (navigator.appVersion.indexOf("Mac") != -1)
            return "mac";
        else if (navigator.appVersion.indexOf("Linux") != -1)
            return "linux-deb";
        else if (navigator.appVersion.indexOf("Solaris") != -1)
            return "solaris";
        else "NotDetected"
    }
});
<|endoftext|>


<commit_before>// Portions of this code are from the book JavaScript: Making Isometric Social
// Real-Time Games with HTML5, CSS3 and Javascript (ISBN #978-1-4493-0475-1).
// Copyright 2011 by Mario Andres Pagella.

window.onload = function () {
	var tileMap = [];

	// 50px square tiles
	var tile = {
		width: 48,
		height: 48
	}

	// 10x10 of 50px tiles
	var grid = {
		width: 10,
		height: 10
	}

	var Keys = {
		UP: 38,
		DOWN: 40,
		LEFT: 37,
		RIGHT: 39
	}

	var scroll = {
		x: 0,
		y: 0
	}

	var canvas = document.getElementById('myCanvas');
	var c = canvas.getContext('2d');

	//Temp loading in image for toolbox placeholder
	this.tb1 = new Image();
	this.tb1.src = "image/orange.png";

	canvas.addEventListener('click', handleClick, false);

	drawGrid();

	function handleClick(e) {
		// When a click is detected, translate the mouse coordinates to pixel coordinates
		var row = Math.floor((e.clientX + scroll.x) / tile.width);
		var column = Math.floor((e.clientY + scroll.y) / tile.height);

		if (tileMap[row] == null) {
			tileMap[row] = [];
		}
		tileMap[row][column] = 1;
	}

	function drawGrid() {
		c.fillStyle = '#FFFFFF';
		c.fillRect (0, 0, canvas.width, canvas.height);

		var startRow = Math.floor(scroll.x / tile.width);
		var startCol = Math.floor(scroll.y / tile.height);
		var rowCount = startRow + Math.floor(canvas.width / tile.width) + 1;
		var colCount = startCol + Math.floor(canvas.height / tile.height) + 1;

		rowCount = ((startRow + rowCount) > grid.width) ? grid.width : rowCount;
		colCount = ((startCol + colCount) > grid.height) ? grid.height : colCount;

		for (var row = startRow; row < rowCount; row++) {
			for (var col = startCol; col < colCount; col++) {
				var tilePositionX = tile.width * row;
				var tilePositionY = tile.height * col;

				tilePositionX -= scroll.x;
				tilePositionY -= scroll.y;

				if (tileMap[row] != null && tileMap[row][col] != null) {

					//We're drawing the image on click, instead of changing the fill on the squares

					//c.fillStyle = '#CC0000';
					//c.fillRect(tilePositionX, tilePositionY, tile.width, tile.height);
					//c.fillStyle = '#000000';
					//c.strokeRect(tilePositionX, tilePositionY, tile.width, tile.height);
					c.drawImage(this.tb1, tilePositionX, tilePositionY, this.tb1.width, this.tb1.height);

				} else {
					c.strokeRect(tilePositionX, tilePositionY, tile.width, tile.height);
				}
			}
		}
		drawToolBox(); //Add the toolbox to the bottom of the grid

		setTimeout(drawGrid, 1);
	}

	function drawToolBox() {
		c.fillStyle = '#FFFFFF';
		c.fillRect (0, grid.height * tile.height, grid.width * tile.width, tile.height);
		c.strokeRect(0, grid.height * tile.height, grid.width * tile.width, tile.height);
	}
}
<commit_msg>Working on clicking items selected from toolbox<commit_after>// Portions of this code are from the book JavaScript: Making Isometric Social
// Real-Time Games with HTML5, CSS3 and Javascript (ISBN #978-1-4493-0475-1).
// Copyright 2011 by Mario Andres Pagella.

window.onload = function () {
	var tileMap = [];

	// 50px square tiles
	var tile = {
		width: 48,
		height: 48
	}

	// 10x10 of 50px tiles
	var grid = {
		width: 10,
		height: 10
	}

	var Keys = {
		UP: 38,
		DOWN: 40,
		LEFT: 37,
		RIGHT: 39
	}

	var canvas = document.getElementById('myCanvas');
	var c = canvas.getContext('2d');

	//Temp loading in image for toolbox placeholder
	this.tb1 = new Image();
	this.tb2 = new Image();
	this.tb1.src = "image/mirror45.png";
	this.tb2.src = "image/orange.png";

	//For determining which tile was selected from the toolbox
	tileType = 0;

	canvas.addEventListener('click', handleClick, false);
	canvas.addEventListener('click', addSelected, false);

	drawGrid();

	function handleClick(e) {
		//When a click is detected, translate the mouse coordinates to pixel coordinates
		var row = Math.floor((e.clientX) / tile.width);
		var column = Math.floor((e.clientY) / tile.height);

		if (tileMap[row] == null) {
			tileMap[row] = [];
		}
		tileMap[row][column] = 1;
	}

	function drawGrid() {
		c.fillStyle = '#FFFFFF';
		c.fillRect (0, 0, canvas.width, canvas.height);

		drawToolBox(); //Add the toolbox to the bottom of the grid

		var startRow = 0;
		var startCol = 0;
		var rowCount = startRow + Math.floor(canvas.width / tile.width) + 1;
		var colCount = startCol + Math.floor(canvas.height / tile.height) + 1;

		rowCount = ((startRow + rowCount) > grid.width) ? grid.width : rowCount;
		colCount = ((startCol + colCount) > grid.height) ? grid.height : colCount;

		for (var row = startRow; row < rowCount; row++) {
			for (var col = startCol; col < colCount; col++) {
				var tilePositionX = tile.width * row;
				var tilePositionY = tile.height * col;

				if (tileMap[row] != null && tileMap[row][col] != null) {

					switch(tileType){
						case 0:
							c.drawImage(this.tb1, tilePositionX, tilePositionY, this.tb1.width, this.tb1.height);
							break;
						case 1:
							c.drawImage(this.tb2, tilePositionX, tilePositionY, this.tb2.width, this.tb2.height);
							break;
					}
				} else {
					c.strokeRect(tilePositionX, tilePositionY, tile.width, tile.height);
				}
			}
		}
		setTimeout(drawGrid, 1);
	}

	function drawToolBox() {
		c.fillStyle = '#FFFFFF';
		c.fillRect (0, grid.height * tile.height, grid.width * tile.width, tile.height);
		c.strokeRect(0, grid.height * tile.height, grid.width * tile.width, tile.height);

		c.drawImage(this.tb1, 0, grid.height * tile.height, this.tb1.width, this.tb1.height);
		c.drawImage(this.tb2, this.tb1.width, grid.height * tile.height, this.tb2.width, this.tb2.height);
	}

	function addSelected(e) {
		var row = Math.floor(e.clientX / tile.width);
		var column = Math.floor(e.clientY / tile.height);

		if(column == 10) {
			switch(row){
				case 0:
					tileType = 0;
					break;
				case 1:
					tileType = 1;
					break;
			}
		}
	}
}
<|endoftext|>


<commit_before>/* jshint esversion: 6 */

"use strict";

const Server = require(__dirname + "/server.js");
const electron = require("electron");
const core = require(__dirname + "/app.js");

// Config
var config = {};
// Module to control application life.
const app = electron.app;
// Module to create native browser window.
const BrowserWindow = electron.BrowserWindow;

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow;

function createWindow() {
	// Create the browser window.
	if (config.kioskmode) {
		mainWindow = new BrowserWindow({width: 800, height: 600, x: 0, y: 0, kiosk:true, darkTheme: true, webPreferences: {nodeIntegration: false}});
	} else {
		mainWindow = new BrowserWindow({width: 800, height: 600, x: 0, y: 0, fullscreen: true, autoHideMenuBar: true, darkTheme: true, webPreferences: {nodeIntegration: false}});
	}

	// and load the index.html of the app.
	//mainWindow.loadURL('file://' + __dirname + '../../index.html');
	mainWindow.loadURL("http://localhost:" + config.port);

	// Open the DevTools if run with "npm start dev"
	if(process.argv[2] == "dev") {
		mainWindow.webContents.openDevTools();
	}

	// Set responders for window events.
	mainWindow.on("closed", function() {
		mainWindow = null;
	});

	if (config.kioskmode) {
		mainWindow.on("blur", function() {
			mainWindow.focus();
		});

		mainWindow.on("leave-full-screen", function() {
			// console.log("leave-full-screen");
			mainWindow.setFullScreen(true);
		});

		mainWindow.on("resize", function() {
			setTimeout(function() {
				mainWindow.reload();
			}, 1000);
		});
	}
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
app.on("ready", function() {
	console.log("Launching application.");
	createWindow();
});

// Quit when all windows are closed.
app.on("window-all-closed", function() {
	createWindow();
});

app.on("activate", function() {
	// On OS X it's common to re-create a window in the app when the
	// dock icon is clicked and there are no other windows open.
	if (mainWindow === null) {
		createWindow();
	}
});

// Start the core application.
// This starts all node helpers and starts the webserver.
core.start(function(c) {
	config = c;
});
<commit_msg>Cleanup<commit_after>/* jshint esversion: 6 */

"use strict";

const Server = require(__dirname + "/server.js");
const electron = require("electron");
const core = require(__dirname + "/app.js");

// Config
var config = {};
// Module to control application life.
const app = electron.app;
// Module to create native browser window.
const BrowserWindow = electron.BrowserWindow;

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow;

function createWindow() {
	// Create the browser window.
	if (config.kioskmode) {
		mainWindow = new BrowserWindow({width: 800, height: 600, x: 0, y: 0, kiosk:true, darkTheme: true, webPreferences: {nodeIntegration: false}});
	} else {
		mainWindow = new BrowserWindow({width: 800, height: 600, x: 0, y: 0, fullscreen: true, autoHideMenuBar: true, darkTheme: true, webPreferences: {nodeIntegration: false}});
	}

	// and load the index.html of the app.
	//mainWindow.loadURL('file://' + __dirname + '../../index.html');
	mainWindow.loadURL("http://localhost:" + config.port);

	// Open the DevTools if run with "npm start dev"
	if(process.argv[2] == "dev") {
		mainWindow.webContents.openDevTools();
	}

	// Set responders for window events.
	mainWindow.on("closed", function() {
		mainWindow = null;
	});

	if (config.kioskmode) {
		mainWindow.on("blur", function() {
			mainWindow.focus();
		});

		mainWindow.on("leave-full-screen", function() {
			mainWindow.setFullScreen(true);
		});

		mainWindow.on("resize", function() {
			setTimeout(function() {
				mainWindow.reload();
			}, 1000);
		});
	}
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
app.on("ready", function() {
	console.log("Launching application.");
	createWindow();
});

// Quit when all windows are closed.
app.on("window-all-closed", function() {
	createWindow();
});

app.on("activate", function() {
	// On OS X it's common to re-create a window in the app when the
	// dock icon is clicked and there are no other windows open.
	if (mainWindow === null) {
		createWindow();
	}
});

// Start the core application.
// This starts all node helpers and starts the webserver.
core.start(function(c) {
	config = c;
});
<|endoftext|>


<commit_before>'use strict';
Cryptodog.xmpp = {};
Cryptodog.xmpp.currentStatus = 'online';
Cryptodog.xmpp.connection = null;

Cryptodog.xmpp.defaultServer = {
    name: 'Cryptodog',
    domain: 'crypto.dog',
    conference: 'conference.crypto.dog',
    relay: 'wss://crypto.dog/websocket'
};

Cryptodog.xmpp.currentServer = {};

$(window).ready(function() {
    // Load custom server settings
    Cryptodog.storage.getItem('serverName', function(key) {
        Cryptodog.xmpp.currentServer.name = key ? key : Cryptodog.xmpp.defaultServer.name;
    });
    Cryptodog.storage.getItem('domain', function(key) {
        Cryptodog.xmpp.currentServer.domain = key ? key : Cryptodog.xmpp.defaultServer.domain;
    });
    Cryptodog.storage.getItem('conferenceServer', function(key) {
        Cryptodog.xmpp.currentServer.conference = key ? key : Cryptodog.xmpp.defaultServer.conference;
    });
    Cryptodog.storage.getItem('relay', function(key) {
        Cryptodog.xmpp.currentServer.relay = key ? key : Cryptodog.xmpp.defaultServer.relay;
    });

    // Prepares necessary encryption key operations before XMPP connection.
    // Shows a progress bar while doing so.
    Cryptodog.xmpp.showKeyPreparationDialog = function(callback) {
        Cryptodog.storage.getItem('persistenceEnabled', function(key) {
            var key = key || {};
            if (key.enabled) {
                Cryptodog.me.mpPrivateKey = BigInt.base642bigInt(key.mp);
                Cryptodog.me.otrKey = DSA.parsePrivate(key.otr);
            } else {
                Cryptodog.me.mpPrivateKey = Cryptodog.multiParty.genPrivateKey();
            }

            Cryptodog.me.mpPublicKey = Cryptodog.multiParty.genPublicKey(Cryptodog.me.mpPrivateKey);
            Cryptodog.me.mpFingerprint = Cryptodog.multiParty.genFingerprint();

            // If we already have keys, just skip to the callback.
            if (Cryptodog.me.otrKey) {
                callback();
                return;
            }

            $('#loginInfo').text(Cryptodog.locale['loginMessage']['generatingKeys']);

            // Add delay to key generation when on the file protocol
            // Since the UI freezes when generating keys without WebWorkers
            if (window.location.protocol === 'file:') {
                setTimeout(function() {
                    Cryptodog.xmpp.prepareKeys(callback);
                }, 100);
            } else {
                Cryptodog.xmpp.prepareKeys(callback);
            }
        });
    };

    // See above.
    Cryptodog.xmpp.prepareKeys = function(callback) {
        // Create DSA key for OTR.
        // file protocol doesn't support WebWorkers
        if (window.location.protocol === 'file:') {
            Cryptodog.me.otrKey = new DSA();

            if (callback) {
                callback();
            }
        } else {
            DSA.createInWebWorker(
                {
                    path: 'js/workers/dsa.js',
                    seed: Cryptodog.random.generateSeed
                },
                function(key) {
                    Cryptodog.me.otrKey = key;

                    if (callback) {
                        callback();
                    }
                }
            );
        }
    };

    // Connect anonymously and join conversation.
    Cryptodog.xmpp.connect = function() {
        Cryptodog.xmpp.connection = new Strophe.Connection(Cryptodog.xmpp.currentServer.relay);

        Cryptodog.xmpp.connection.connect(Cryptodog.xmpp.currentServer.domain, null, function(status) {
            if (status === Strophe.Status.CONNECTING) {
                $('#loginInfo').text(Cryptodog.locale['loginMessage']['connecting']);
            } else if (status === Strophe.Status.CONNECTED) {
                Cryptodog.xmpp.connection.muc.join(
                    Cryptodog.me.conversation + '@' + Cryptodog.xmpp.currentServer.conference,
                    Cryptodog.me.nickname,
                    function(message) {
                        if (Cryptodog.xmpp.onMessage(message)) {
                            return true;
                        }
                    },
                    function(presence) {
                        if (Cryptodog.xmpp.onPresence(presence)) {
                            return true;
                        }
                    }
                );
                Cryptodog.xmpp.onConnected();

                document.title = Cryptodog.me.nickname + '@' + Cryptodog.me.conversation;
                $('.conversationName').text(document.title);

                Cryptodog.storage.setItem('nickname', Cryptodog.me.nickname);
            } else if (status === Strophe.Status.CONNFAIL || status === Strophe.Status.DISCONNECTED) {
                if (Cryptodog.loginError) {
                    Cryptodog.xmpp.reconnect();
                }
            }
        });
    };

    // Executes on successfully completed XMPP connection.
    Cryptodog.xmpp.onConnected = function() {
        afterConnect();

        $('#loginInfo').text('✓');
        $('#status').attr('src', 'img/icons/checkmark.svg');
        $('#buddy-groupChat,#status').show();
        $('#buddy-groupChat').insertBefore('#buddiesOnline');
        $('#fill')
            .stop()
            .animate(
                {
                    width: '100%',
                    opacity: '1'
                },
                250,
                'linear'
            );

        window.setTimeout(function() {
            $('#dialogBoxClose').click();
        }, 400);

        window.setTimeout(function() {
            $('#loginOptions,#languages,#customServerDialog').fadeOut(200);
            $('#version,#logoText,#loginInfo,#info').fadeOut(200);
            $('#header').animate({ 'background-color': '#444' });
            $('.logo').animate({ margin: '-11px 5px 0 0' });

            $('#login').fadeOut(200, function() {
                $('#conversationInfo').fadeIn();

                $('#buddy-groupChat').click(function() {
                    Cryptodog.onBuddyClick($(this));
                });

                $('#buddy-groupChat').click();
                $('#conversationWrapper').fadeIn();
                $('#optionButtons').fadeIn();

                $('#footer')
                    .delay(200)
                    .animate({ height: 60 }, function() {
                        $('#userInput').fadeIn(200, function() {
                            $('#userInputText').focus();
                        });
                    });

                $('#buddyWrapper').slideDown();
            });
        }, 800);

        Cryptodog.loginError = true;
    };

    // Reconnect to the same chatroom, on accidental connection loss.
    Cryptodog.xmpp.reconnect = function() {
        if (Cryptodog.xmpp.connection) {
            Cryptodog.xmpp.connection.reset();
        }

        Cryptodog.xmpp.connection = new Strophe.Connection(Cryptodog.xmpp.currentServer.relay);

        Cryptodog.xmpp.connection.connect(Cryptodog.xmpp.currentServer.domain, null, function(status) {
            if (status === Strophe.Status.CONNECTING) {
                $('.conversationName').animate({ 'background-color': '#F00' });
            } else if (status === Strophe.Status.CONNECTED) {
                afterConnect();

                Cryptodog.xmpp.connection.muc.join(
                    Cryptodog.me.conversation + '@' + Cryptodog.xmpp.currentServer.conference,
                    Cryptodog.me.nickname
                );
            } else if (status === Strophe.Status.CONNFAIL || status === Strophe.Status.DISCONNECTED) {
                if (Cryptodog.loginError) {
                    window.setTimeout(function() {
                        Cryptodog.xmpp.reconnect();
                    }, 5000);
                }
            }
        });
    };

    // Handle incoming messages from the XMPP server.
    Cryptodog.xmpp.onMessage = function(message) {
        var nickname = extractNickname($(message).attr('from'));

        var body = $(message)
            .find('body')
            .text();

        var type = $(message).attr('type');

        // If archived message, ignore.
        if ($(message).find('delay').length !== 0) {
            return true;
        }

        // If message is from me, ignore.
        if (nickname === Cryptodog.me.nickname) {
            return true;
        }

        // If message is from someone not on buddy list, ignore.
        if (!Cryptodog.buddies.hasOwnProperty(nickname)) {
            return true;
        }

        // Check if message has a 'composing' notification.
        if ($(message).attr('id') === 'composing' && !body.length) {
            $('#buddy-' + Cryptodog.buddies[nickname].id).addClass('composing');
            return true;
        }

        // Check if message has a 'paused' (stopped writing) notification.
        if ($(message).attr('id') === 'paused') {
            $('#buddy-' + Cryptodog.buddies[nickname].id).removeClass('composing');
        } else if (type === 'groupchat' && body.length) {
            // Check if message is a group chat message.
            $('#buddy-' + Cryptodog.buddies[nickname].id).removeClass('composing');

            body = Cryptodog.multiParty.receiveMessage(nickname, Cryptodog.me.nickname, body);

            if (typeof body === 'string') {
                Cryptodog.addToConversation(body, nickname, 'groupChat', 'message');
            }
        } else if (type === 'chat') {
            // Check if this is a private OTR message.
            $('#buddy-' + Cryptodog.buddies[nickname].id).removeClass('composing');

            if (body.length > Cryptodog.otr.maxMessageLength) {
                console.log('xmpp: refusing to decrypt large OTR message (' + body.length + ' bytes) from ' + nickname);
                return true;
            }

            Cryptodog.buddies[nickname].otr.receiveMsg(body);
        }
        return true;
    };

    // Handle incoming presence updates from the XMPP server.
    Cryptodog.xmpp.onPresence = function(presence) {
        var status;
        var nickname = extractNickname($(presence).attr('from'));

        // If invalid nickname, do not process.
        if ($(presence).attr('type') === 'error') {
            if (
                $(presence)
                    .find('error')
                    .attr('code') === '409'
            ) {
                // Delay logout in order to avoid race condition with window animation.
                window.setTimeout(function() {
                    Cryptodog.logout();
                    Cryptodog.UI.loginFail(Cryptodog.locale['loginMessage']['nicknameInUse']);
                }, 3000);

                return false;
            }
            return true;
        }

        if (nickname === Cryptodog.me.nickname) {
            // Unavailable presence from us: we've been kicked, so try to reconnect.
            if ($(presence).attr('type') === 'unavailable') {
                Cryptodog.xmpp.reconnect();
            }

            // Ignore if presence status is coming from myself.
            return true;
        }

        // Detect nickname change (which may be done by non-Cryptodog XMPP clients).
        if (
            $(presence)
                .find('status')
                .attr('code') === '303'
        ) {
            Cryptodog.removeBuddy(nickname);
            return true;
        }

        // Detect buddy going offline.
        if ($(presence).attr('type') === 'unavailable') {
            Cryptodog.removeBuddy(nickname);
            return true;
        } else if (!Cryptodog.buddies.hasOwnProperty(nickname)) {
            // Create buddy element if buddy is new
            Cryptodog.addBuddy(nickname, null, 'online');

            // Propagate away status to newcomers.
            Cryptodog.xmpp.sendStatus();
        } else if (
            $(presence)
                .find('show')
                .text() === '' ||
            $(presence)
                .find('show')
                .text() === 'chat'
        ) {
            status = 'online';
        } else {
            status = 'away';
        }

        Cryptodog.buddyStatus(nickname, status);
        return true;
    };

    /* Send our multiparty public key to all room occupants. */
    Cryptodog.xmpp.sendPublicKey = function() {
        Cryptodog.xmpp.connection.muc.message(
            Cryptodog.me.conversation + '@' + Cryptodog.xmpp.currentServer.conference,
            null,
            JSON.stringify(new Cryptodog.multiParty.PublicKey(Cryptodog.me.mpPublicKey)),
            null,
            'groupchat',
            'active'
        );
    };

    /* Request public key from `nickname`.
       If `nickname` is omitted, request from all room occupants. */
    Cryptodog.xmpp.requestPublicKey = function(nickname) {
        Cryptodog.xmpp.connection.muc.message(
            Cryptodog.me.conversation + '@' + Cryptodog.xmpp.currentServer.conference,
            null,
            JSON.stringify(new Cryptodog.multiParty.PublicKeyRequest(nickname)),
            null,
            'groupchat',
            'active'
        );
    };

    // Send our current status to the XMPP server.
    Cryptodog.xmpp.sendStatus = function() {
        var status = '';

        if (Cryptodog.xmpp.currentStatus === 'away') {
            status = 'away';
        }

        Cryptodog.xmpp.connection.muc.setStatus(
            Cryptodog.me.conversation + '@' + Cryptodog.xmpp.currentServer.conference,
            Cryptodog.me.nickname,
            status,
            status
        );
    };

    var autoIgnore;

    // Executed (manually) after connection.
    var afterConnect = function() {
        Cryptodog.xmpp.connection.ping.addPingHandler(function(ping) {
            Cryptodog.xmpp.connection.ping.pong(ping);
            return true;
        });

        Cryptodog.xmpp.connection.ibb.addIBBHandler(Cryptodog.otr.ibbHandler);
        Cryptodog.xmpp.connection.si_filetransfer.addFileHandler(Cryptodog.otr.fileHandler);

        $('.conversationName').animate({ 'background-color': '#bb7a20' });

        Cryptodog.xmpp.sendStatus();
        Cryptodog.xmpp.sendPublicKey();
        Cryptodog.xmpp.requestPublicKey();

        clearInterval(autoIgnore);

        autoIgnore = setInterval(function() {
            for (var nickname in Cryptodog.buddies) {
                var buddy = Cryptodog.buddies[nickname];

                if (Cryptodog.autoIgnore && buddy.messageCount > Cryptodog.maxMessageCount) {
                    buddy.toggleIgnored();
                    console.log('Automatically ignored ' + nickname);
                }

                buddy.messageCount = 0;
            }
        }, Cryptodog.maxMessageInterval);
    };

    // Extract nickname (part after forward slash) from JID
    var extractNickname = function(from) {
        var name = from.match(/\/([\s\S]+)/);

        if (name) {
            return name[1];
        }
        return false;
    };
});
<commit_msg>Handle OTR and multiparty exceptions<commit_after>'use strict';
Cryptodog.xmpp = {};
Cryptodog.xmpp.currentStatus = 'online';
Cryptodog.xmpp.connection = null;

Cryptodog.xmpp.defaultServer = {
    name: 'Cryptodog',
    domain: 'crypto.dog',
    conference: 'conference.crypto.dog',
    relay: 'wss://crypto.dog/websocket'
};

Cryptodog.xmpp.currentServer = {};

$(window).ready(function() {
    // Load custom server settings
    Cryptodog.storage.getItem('serverName', function(key) {
        Cryptodog.xmpp.currentServer.name = key ? key : Cryptodog.xmpp.defaultServer.name;
    });
    Cryptodog.storage.getItem('domain', function(key) {
        Cryptodog.xmpp.currentServer.domain = key ? key : Cryptodog.xmpp.defaultServer.domain;
    });
    Cryptodog.storage.getItem('conferenceServer', function(key) {
        Cryptodog.xmpp.currentServer.conference = key ? key : Cryptodog.xmpp.defaultServer.conference;
    });
    Cryptodog.storage.getItem('relay', function(key) {
        Cryptodog.xmpp.currentServer.relay = key ? key : Cryptodog.xmpp.defaultServer.relay;
    });

    // Prepares necessary encryption key operations before XMPP connection.
    // Shows a progress bar while doing so.
    Cryptodog.xmpp.showKeyPreparationDialog = function(callback) {
        Cryptodog.storage.getItem('persistenceEnabled', function(key) {
            var key = key || {};
            if (key.enabled) {
                Cryptodog.me.mpPrivateKey = BigInt.base642bigInt(key.mp);
                Cryptodog.me.otrKey = DSA.parsePrivate(key.otr);
            } else {
                Cryptodog.me.mpPrivateKey = Cryptodog.multiParty.genPrivateKey();
            }

            Cryptodog.me.mpPublicKey = Cryptodog.multiParty.genPublicKey(Cryptodog.me.mpPrivateKey);
            Cryptodog.me.mpFingerprint = Cryptodog.multiParty.genFingerprint();

            // If we already have keys, just skip to the callback.
            if (Cryptodog.me.otrKey) {
                callback();
                return;
            }

            $('#loginInfo').text(Cryptodog.locale['loginMessage']['generatingKeys']);

            // Add delay to key generation when on the file protocol
            // Since the UI freezes when generating keys without WebWorkers
            if (window.location.protocol === 'file:') {
                setTimeout(function() {
                    Cryptodog.xmpp.prepareKeys(callback);
                }, 100);
            } else {
                Cryptodog.xmpp.prepareKeys(callback);
            }
        });
    };

    // See above.
    Cryptodog.xmpp.prepareKeys = function(callback) {
        // Create DSA key for OTR.
        // file protocol doesn't support WebWorkers
        if (window.location.protocol === 'file:') {
            Cryptodog.me.otrKey = new DSA();

            if (callback) {
                callback();
            }
        } else {
            DSA.createInWebWorker(
                {
                    path: 'js/workers/dsa.js',
                    seed: Cryptodog.random.generateSeed
                },
                function(key) {
                    Cryptodog.me.otrKey = key;

                    if (callback) {
                        callback();
                    }
                }
            );
        }
    };

    // Connect anonymously and join conversation.
    Cryptodog.xmpp.connect = function() {
        Cryptodog.xmpp.connection = new Strophe.Connection(Cryptodog.xmpp.currentServer.relay);

        Cryptodog.xmpp.connection.connect(Cryptodog.xmpp.currentServer.domain, null, function(status) {
            if (status === Strophe.Status.CONNECTING) {
                $('#loginInfo').text(Cryptodog.locale['loginMessage']['connecting']);
            } else if (status === Strophe.Status.CONNECTED) {
                Cryptodog.xmpp.connection.muc.join(
                    Cryptodog.me.conversation + '@' + Cryptodog.xmpp.currentServer.conference,
                    Cryptodog.me.nickname,
                    function(message) {
                        if (Cryptodog.xmpp.onMessage(message)) {
                            return true;
                        }
                    },
                    function(presence) {
                        if (Cryptodog.xmpp.onPresence(presence)) {
                            return true;
                        }
                    }
                );
                Cryptodog.xmpp.onConnected();

                document.title = Cryptodog.me.nickname + '@' + Cryptodog.me.conversation;
                $('.conversationName').text(document.title);

                Cryptodog.storage.setItem('nickname', Cryptodog.me.nickname);
            } else if (status === Strophe.Status.CONNFAIL || status === Strophe.Status.DISCONNECTED) {
                if (Cryptodog.loginError) {
                    Cryptodog.xmpp.reconnect();
                }
            }
        });
    };

    // Executes on successfully completed XMPP connection.
    Cryptodog.xmpp.onConnected = function() {
        afterConnect();

        $('#loginInfo').text('✓');
        $('#status').attr('src', 'img/icons/checkmark.svg');
        $('#buddy-groupChat,#status').show();
        $('#buddy-groupChat').insertBefore('#buddiesOnline');
        $('#fill')
            .stop()
            .animate(
                {
                    width: '100%',
                    opacity: '1'
                },
                250,
                'linear'
            );

        window.setTimeout(function() {
            $('#dialogBoxClose').click();
        }, 400);

        window.setTimeout(function() {
            $('#loginOptions,#languages,#customServerDialog').fadeOut(200);
            $('#version,#logoText,#loginInfo,#info').fadeOut(200);
            $('#header').animate({ 'background-color': '#444' });
            $('.logo').animate({ margin: '-11px 5px 0 0' });

            $('#login').fadeOut(200, function() {
                $('#conversationInfo').fadeIn();

                $('#buddy-groupChat').click(function() {
                    Cryptodog.onBuddyClick($(this));
                });

                $('#buddy-groupChat').click();
                $('#conversationWrapper').fadeIn();
                $('#optionButtons').fadeIn();

                $('#footer')
                    .delay(200)
                    .animate({ height: 60 }, function() {
                        $('#userInput').fadeIn(200, function() {
                            $('#userInputText').focus();
                        });
                    });

                $('#buddyWrapper').slideDown();
            });
        }, 800);

        Cryptodog.loginError = true;
    };

    // Reconnect to the same chatroom, on accidental connection loss.
    Cryptodog.xmpp.reconnect = function() {
        if (Cryptodog.xmpp.connection) {
            Cryptodog.xmpp.connection.reset();
        }

        Cryptodog.xmpp.connection = new Strophe.Connection(Cryptodog.xmpp.currentServer.relay);

        Cryptodog.xmpp.connection.connect(Cryptodog.xmpp.currentServer.domain, null, function(status) {
            if (status === Strophe.Status.CONNECTING) {
                $('.conversationName').animate({ 'background-color': '#F00' });
            } else if (status === Strophe.Status.CONNECTED) {
                afterConnect();

                Cryptodog.xmpp.connection.muc.join(
                    Cryptodog.me.conversation + '@' + Cryptodog.xmpp.currentServer.conference,
                    Cryptodog.me.nickname
                );
            } else if (status === Strophe.Status.CONNFAIL || status === Strophe.Status.DISCONNECTED) {
                if (Cryptodog.loginError) {
                    window.setTimeout(function() {
                        Cryptodog.xmpp.reconnect();
                    }, 5000);
                }
            }
        });
    };

    // Handle incoming messages from the XMPP server.
    Cryptodog.xmpp.onMessage = function(message) {
        var nickname = extractNickname($(message).attr('from'));

        var body = $(message)
            .find('body')
            .text();

        var type = $(message).attr('type');

        // If archived message, ignore.
        if ($(message).find('delay').length !== 0) {
            return true;
        }

        // If message is from me, ignore.
        if (nickname === Cryptodog.me.nickname) {
            return true;
        }

        // If message is from someone not on buddy list, ignore.
        if (!Cryptodog.buddies.hasOwnProperty(nickname)) {
            return true;
        }

        // Check if message has a 'composing' notification.
        if ($(message).attr('id') === 'composing' && !body.length) {
            $('#buddy-' + Cryptodog.buddies[nickname].id).addClass('composing');
            return true;
        }

        // Check if message has a 'paused' (stopped writing) notification.
        if ($(message).attr('id') === 'paused') {
            $('#buddy-' + Cryptodog.buddies[nickname].id).removeClass('composing');
        } else if (type === 'groupchat' && body.length) {
            // Check if message is a group chat message.
            $('#buddy-' + Cryptodog.buddies[nickname].id).removeClass('composing');

            try {
                body = Cryptodog.multiParty.receiveMessage(nickname, Cryptodog.me.nickname, body);
            } catch (e) {
                console.warn('xmpp: exception handling multiParty message from ' + nickname + ': ' + e);
                return true;
            }

            if (typeof body === 'string') {
                Cryptodog.addToConversation(body, nickname, 'groupChat', 'message');
            }
        } else if (type === 'chat') {
            // Check if this is a private OTR message.
            $('#buddy-' + Cryptodog.buddies[nickname].id).removeClass('composing');

            if (body.length > Cryptodog.otr.maxMessageLength) {
                console.log('xmpp: refusing to decrypt large OTR message (' + body.length + ' bytes) from ' + nickname);
                return true;
            }

            try {
                Cryptodog.buddies[nickname].otr.receiveMsg(body);
            } catch (e) {
                console.warn('xmpp: exception handling OTR message from ' + nickname + ': ' + e);
            }
        }
        return true;
    };

    // Handle incoming presence updates from the XMPP server.
    Cryptodog.xmpp.onPresence = function(presence) {
        var status;
        var nickname = extractNickname($(presence).attr('from'));

        // If invalid nickname, do not process.
        if ($(presence).attr('type') === 'error') {
            if (
                $(presence)
                    .find('error')
                    .attr('code') === '409'
            ) {
                // Delay logout in order to avoid race condition with window animation.
                window.setTimeout(function() {
                    Cryptodog.logout();
                    Cryptodog.UI.loginFail(Cryptodog.locale['loginMessage']['nicknameInUse']);
                }, 3000);

                return false;
            }
            return true;
        }

        if (nickname === Cryptodog.me.nickname) {
            // Unavailable presence from us: we've been kicked, so try to reconnect.
            if ($(presence).attr('type') === 'unavailable') {
                Cryptodog.xmpp.reconnect();
            }

            // Ignore if presence status is coming from myself.
            return true;
        }

        // Detect nickname change (which may be done by non-Cryptodog XMPP clients).
        if (
            $(presence)
                .find('status')
                .attr('code') === '303'
        ) {
            Cryptodog.removeBuddy(nickname);
            return true;
        }

        // Detect buddy going offline.
        if ($(presence).attr('type') === 'unavailable') {
            Cryptodog.removeBuddy(nickname);
            return true;
        } else if (!Cryptodog.buddies.hasOwnProperty(nickname)) {
            // Create buddy element if buddy is new
            Cryptodog.addBuddy(nickname, null, 'online');

            // Propagate away status to newcomers.
            Cryptodog.xmpp.sendStatus();
        } else if (
            $(presence)
                .find('show')
                .text() === '' ||
            $(presence)
                .find('show')
                .text() === 'chat'
        ) {
            status = 'online';
        } else {
            status = 'away';
        }

        Cryptodog.buddyStatus(nickname, status);
        return true;
    };

    /* Send our multiparty public key to all room occupants. */
    Cryptodog.xmpp.sendPublicKey = function() {
        Cryptodog.xmpp.connection.muc.message(
            Cryptodog.me.conversation + '@' + Cryptodog.xmpp.currentServer.conference,
            null,
            JSON.stringify(new Cryptodog.multiParty.PublicKey(Cryptodog.me.mpPublicKey)),
            null,
            'groupchat',
            'active'
        );
    };

    /* Request public key from `nickname`.
       If `nickname` is omitted, request from all room occupants. */
    Cryptodog.xmpp.requestPublicKey = function(nickname) {
        Cryptodog.xmpp.connection.muc.message(
            Cryptodog.me.conversation + '@' + Cryptodog.xmpp.currentServer.conference,
            null,
            JSON.stringify(new Cryptodog.multiParty.PublicKeyRequest(nickname)),
            null,
            'groupchat',
            'active'
        );
    };

    // Send our current status to the XMPP server.
    Cryptodog.xmpp.sendStatus = function() {
        var status = '';

        if (Cryptodog.xmpp.currentStatus === 'away') {
            status = 'away';
        }

        Cryptodog.xmpp.connection.muc.setStatus(
            Cryptodog.me.conversation + '@' + Cryptodog.xmpp.currentServer.conference,
            Cryptodog.me.nickname,
            status,
            status
        );
    };

    var autoIgnore;

    // Executed (manually) after connection.
    var afterConnect = function() {
        Cryptodog.xmpp.connection.ping.addPingHandler(function(ping) {
            Cryptodog.xmpp.connection.ping.pong(ping);
            return true;
        });

        Cryptodog.xmpp.connection.ibb.addIBBHandler(Cryptodog.otr.ibbHandler);
        Cryptodog.xmpp.connection.si_filetransfer.addFileHandler(Cryptodog.otr.fileHandler);

        $('.conversationName').animate({ 'background-color': '#bb7a20' });

        Cryptodog.xmpp.sendStatus();
        Cryptodog.xmpp.sendPublicKey();
        Cryptodog.xmpp.requestPublicKey();

        clearInterval(autoIgnore);

        autoIgnore = setInterval(function() {
            for (var nickname in Cryptodog.buddies) {
                var buddy = Cryptodog.buddies[nickname];

                if (Cryptodog.autoIgnore && buddy.messageCount > Cryptodog.maxMessageCount) {
                    buddy.toggleIgnored();
                    console.log('Automatically ignored ' + nickname);
                }

                buddy.messageCount = 0;
            }
        }, Cryptodog.maxMessageInterval);
    };

    // Extract nickname (part after forward slash) from JID
    var extractNickname = function(from) {
        var name = from.match(/\/([\s\S]+)/);

        if (name) {
            return name[1];
        }
        return false;
    };
});
<|endoftext|>


<commit_before>/* Examples
 * */

Examples.push({
    name: "Bill Calculator",
    fxn : "100*(salary - rent - studentloans - carpayments - grocery-spendingmoney-retirement) - netflix -tivo -petfood -gas-electric + 100*(subleaseincome + stockportfolio)",
    url : "salary-rent-studentloans-carpayments-grocery-spendingmoney-retirement-netflix-tivo-petfood-gas-electric+subleaseincome+stockportfolio=0:0:0:0:0:0:0:7:0:0:0:0:0:0:{8000:3400:500:600:1000:500:1000:27:30:200:500:200:1000:1000:}100:100:50:50:20:10:100:3:3:20:30:10:100:50:[4000:400:100:250:300:500:300:13:12:100:120:90:600:100:;0:1:1:1:1:1:1:1:1:1:1:1:1:1:=Bill%20Calculator]"
});

Examples.push({
    name: "Drake Equation",
    fxn : "StarFormationRate * StarsWithPlanets * LifeSustainingPlanets * PlanetsWhichActuallyDevelopLife * PlanetsWithIntelligentLife * CivilizationsWithDetectors * DurationOfSpaceSignals",
    url : "StarFormationRate*StarsWithPlanets*LifeSustainingPlanets*PlanetsWhichActuallyDevelopLife*PlanetsWithIntelligentLife*CivilizationsWithDetectors*DurationOfSpaceSignals=0:0:0:0:0:0:0:{20:1:10:1:1:1:20:}1:0.1:1:0.1:0.1:0.1:1:[10:0.5:2:1:0.1:0.1:10:;1:1:1:1:1:1:1:=Drake%20Equation]"

    });

Examples.push({
    name: "Monthly Loan Payments Calculator",
    fxn : "principal*((rate/1200)*(1 + rate/1200)^months)/((1 + rate/1200)^months - 1)",
    url : "principal*((rate/1200)*(1+rate/1200)^months)/((1+rate/1200)^months-1)=0:0:0:{200:100:100:}10:1:1:[110:9:23:;1:1:1:=Loan%20Calculator]"
});

Examples.push({
    name: "Force of Gravity",
    fxn : "GravConstant * massOne * massTwo / distance^2",
    url : "GravConstant*massOne*massTwo/distance^2=0:0:0:0:{20:100:100:100:}0.01:1:1:1:[8.73:29:19:3:;1:1:1:1:=Gravity]"
});

Examples.push({
    name: "E = mc^2",
    fxn : "mass*299792458^2",
    url : "mass*299792458^2=0:{100:}1:[20:;1:=E]"
});

Examples.push({
    name: "Area of Circle",
    fxn : "pi * radius^2",
    url : "pi*radius^2=0:{100:}1:[13:;1:=Circle%20Area]"
});

Examples.push({
    name: "Circumference of a Circle",
    fxn : "2*pi*radius",
    url : "2*pi*radius=0:{100:}1:[13:;1:=Circle%20Circumference]"
});

Examples.push({
    name: "Flake Equation (xkcd.com/718)",
    fxn : "7*1000^3 * (CrazyPeople + Misinterpret)/10000 * TellProbability/10 * NumberPeopleTold * FirstHandRetellings * IgnoredDataProbability/10 * WiderAudienceFraction/100",
    url : "7*1000^3*(CrazyPeople+Misinterpret)/10000*TellProbability/10*NumberPeopleTold*FirstHandRetellings*IgnoredDataProbability/10*WiderAudienceFraction/100=0:0:0:0:0:0:0:{10:10:10:100:100:10:100:}1:1:1:1:1:1:1:[1:1:1:10:10:9:1:;1:1:1:1:1:1:1:=Flake%20Equation%20(XKCD)]"
});

Examples.push({
    name: "Dateable Ages (xkcd.com/314)",
    fxn : "Age/2 + 7",
    url : "Age/2+7=18:{126:}1:[27:;1:=Who%20Can%20You%20Date]"
});

Examples.push({
    name: "TV Romantic Drama Equation (Straight) (xkcd.com/216)",
    fxn : "SameSex*(AllCast - SameSex)",
    url : "SameSex*(AllCast-SameSex)=0:0:{100:100:}1:1:[17:44:;1:1:=Romantic%20Pairings]"
});

Examples.push({
    name: "TV Romantic Drama Equation (Gay) (xkcd.com/216)",
    fxn : "AllCast*(AllCast - 1)/2 + SameSex*(SameSex - AllCast)",
    url : "AllCast*(AllCast-1)/2+SameSex*(SameSex-AllCast)=0:0:{100:100:}1:1:[45:25:;1:1:=Romantic%20Pairings]"
});

Examples.push({
    name: "Post-Game Seasonal Batting Average",
    fxn : "(SeasonBats * (SeasonalAverage/100) + Hits)/(SeasonBats + TimesAtBat)",
    url : "(SeasonBats*(SeasonalAverage/100)+Hits)/(SeasonBats+TimesAtBat)=0:0:0:0:{100:100:100:13:}1:1:1:1:[40:60:81:13:;1:1:1:1:=Post%20Game%20Batting%20Average]"
});

Examples.push({
    name: "Focal Length",
    fxn : "(ObjectDistance * LensToImageDistance)/(ObjectDistance + LensToImageDistance)",
    url : "(ObjectDistance*LensToImageDistance)/(ObjectDistance+LensToImageDistance)=0:0:{100:100:}1:1:[37:20:;1:1:=Focal%20Length]"
});

Examples.push({
    name: "Population Growth",
    fxn : "LastYearPopulation + LastYearPopulation*(ReproductiveRate - AttritionRate)",
    url : "LastYearPopulation+LastYearPopulation*(ReproductiveRate-AttritionRate)=0:0:0:{10000:1:1:}1:0.01:0.01:[4162:0.37:0.16:;0:1:1:=Population]"
});

Examples.push({
    name: "Fiber Optic Response Time",
    fxn : "ProcessingTime + (2*Distance)/(200*(1000^2))",
    url : "ProcessingTime+(2*Distance)/(200*(1000^2))=0:0:{100:100:}1:1:[12:40:;1:1:=Fiber%20Response%20Time]"
});

Examples.push({
    name: "Watts",
    fxn : "Amps * Volts",
    url : "Amps*Volts=0:0:{100:100:}0.01:0.01:[41.04:28.32:;1:1:=Watts]"
});

Examples.push({
    name: "Velocity - 1st Integral of Acceleration",
    fxn : "InitialVelocity + Acceleration*Time",
    url : "InitialVelocity+Acceleration*Time=0:0:0:{100:100:100:}1:0.1:1:[42:9.8:10:;1:1:1:=Velocity]"
});

Examples.push({
    name: "Position - 2nd Integral of Acceleration",
    fxn : "InitialPosition + InitialVelocity*Time + 1/2 * acceleration * Time^2",
    url : "InitialPosition+InitialVelocity*Time+1/2*acceleration*Time^2=0:0:0:0:{100:100:100:100:}1:1:0.1:0.1:[18:41:31:9.8:;1:1:1:1:=Position]"
});

Examples.push({
    name: "Torque",
    fxn : "radius * force * sin(angle)",
    url : "radius*force*sin(angle)=0:0:-360:{100:100:360:}1:1:1:[19:53:69:;1:1:1:=Torque]"
});

Examples.push({
    name: "Surface Area of Cylinder",
    fxn : "2*pi*radius*length + 2*pi*radius^2",
    url : "2*pi*radius*length+2*pi*radius^2=0:0:{100:100:}1:1:[31:17:;1:1:=Surface%20Area]"
});

Examples.push({
    name: "First Order Derivitive of x^n",
    fxn : "n*x^(n-1)",
    url : "n*x^(n-1)=0:0:{100:100:}1:1:[7:1:;1:1:=Derivative%20of%20x^N]"
});

Examples.push({
    name: "First Order Integral of x^n dx",
    fxn : "1/(n+1) * x^(n+1) + C",
    url : "1/(n+1)*x^(n+1)+C=0:0:0:{100:100:100:}1:1:1:[14:2:10:;1:1:1:=First%20Order%20Integral]"
});

Examples.push({
    name: "Glomerular Filtration Rate (Creatinine Clearance CCr) (Kidney Filtration Rate)",
    fxn : "(CreatineConcentration * FlowRate)/PlasmaConcentration",
    url : "(CreatineConcentration*FlowRate)/PlasmaConcentration=0:0:0:{100:100:100:}1:1:1:[53:31:10:;1:1:1:=Glomular%20Filtration]"
});

Examples.push({
    name: "IPAT Environmental Impact Equation",
    fxn : "Population * Affluence * Technology",
    url : "Population*Affluence*Technology=0:0:0:{100:100:100:}1:1:1:[20:40:31:;1:1:1:=IPAT]"
});

Examples.push({
    name: "Vertical Change Delta for a Weighted String between 2 Points",
    fxn : "sqrt(((StringLength + PointsDistance)/2)*((StringLength - PointsDistance)/2))",
    url : "sqrt(((StringLength+PointsDistance)/2)*((StringLength-PointsDistance)/2))=0:0:{100:100:}1:1:[33:18:;1:1:=Weighed%20String]"
});

Examples.push({
    name: "Gaussian",
    fxn : "a * e^(-1*((x-b)^2/2*c^2))",
    url : "a*e^(-1*((x-b)^2/2*c^2))=0:0:0:0:{100:100:100:100:}1:1:1:1:[8:30:17:5:;1:1:1:1:=Gaussian]"
});

Examples.push({
    name: "Mechanical Work",
    fxn : "1/2 * mass * (secondVelocity^2 - firstVelocity^2)",
    url : "1/2*mass*(secondVelocity^2-firstVelocity^2)=0:0:0:{100:100:100:}1:1:1:[71:34:42:;1:1:1:=Mechanical%20Work]"
});

Examples.push({
    name: "Procrastination Equation",
    fxn : "ExpectationOfSuccess*ValueofCompletion / (ImmediacyOfTask * PersonalDelaySensitivity)",
    url : "ExpectationOfSuccess*ValueofCompletion/(ImmediacyOfTask*PersonalDelaySensitivity)=0:0:0:0:{100:100:100:100:}1:1:1:1:[6:9:6:11:;1:1:1:1:=Procrastination%20Likelihood]"
});

Examples.push({
    name: "Pressure Loss via Friction",
    fxn : "FrictionCoefficient * (length / hydraulicDiameter) * (density * velocity^2 /2)",
    url : "FrictionCoefficient*(length/hydraulicDiameter)*(density*velocity^2/2)=0:0:0:0:0:{0.5:100:100:100:100:}0.001:1:1:1:1:[0.029:13:25:14:20:;1:1:1:1:1:=Pressure%20Loss]"
});

Examples.push({
    name: "Lorentz Factor",
    fxn : "1 / sqrt(1-(velocity^2/c^2))",
    url : "1/sqrt(1-(velocity^2/c^2))=290000000:290000000:{300000000:310000000:}1:[299792000:299792458:;1000:1000:=Lorentz%20Factor]"
});

Examples.push({
    name: "Euclidean Distance in 2D",
    fxn : "sqrt((xTwo-xOne)^2 + (yTwo-yOne)^2)",
    url : "sqrt((xTwo-xOne)^2+(yTwo-yOne)^2)=0:0:0:0:{100:100:100:100:}1:1:1:1:[27:53:40:53:;1:1:1:1:=Euclidean%20Distance]"
});

Examples.push({
    name: "Quadratic Equation (First Solution)",
    fxn : "(-x + sqrt(b^2 - 4*a*c))/2*a",
    url : "(-x+sqrt(b^2-4*a*c))/2*a=0:0:0:0:{100:100:100:100:}1:1:1:1:[5:22:3:5:;1:1:1:1:=Quadratic%20Graph]"
});
Examples.push({
    name: "Complex Parenthesis Function",
    fxn : "sum(b*sin((x^(n-1))*pi),n*sin((x^(n-1))*pi),x^(n-2),(7*x*n))",
    url : "sum(b*sin((x^(n-1))*pi),n*sin((x^(n-1))*pi),x^(n-2),(7*x*n))=-100:-10:-4:{100:100:100:}1:1:1:[-85:-2:15:;1:1:1:=Complex%20Function]"
});
<commit_msg>Adjusting range for integral<commit_after>/* Examples
 * */

Examples.push({
    name: "Bill Calculator",
    fxn : "100*(salary - rent - studentloans - carpayments - grocery-spendingmoney-retirement) - netflix -tivo -petfood -gas-electric + 100*(subleaseincome + stockportfolio)",
    url : "salary-rent-studentloans-carpayments-grocery-spendingmoney-retirement-netflix-tivo-petfood-gas-electric+subleaseincome+stockportfolio=0:0:0:0:0:0:0:7:0:0:0:0:0:0:{8000:3400:500:600:1000:500:1000:27:30:200:500:200:1000:1000:}100:100:50:50:20:10:100:3:3:20:30:10:100:50:[4000:400:100:250:300:500:300:13:12:100:120:90:600:100:;0:1:1:1:1:1:1:1:1:1:1:1:1:1:=Bill%20Calculator]"
});

Examples.push({
    name: "Drake Equation",
    fxn : "StarFormationRate * StarsWithPlanets * LifeSustainingPlanets * PlanetsWhichActuallyDevelopLife * PlanetsWithIntelligentLife * CivilizationsWithDetectors * DurationOfSpaceSignals",
    url : "StarFormationRate*StarsWithPlanets*LifeSustainingPlanets*PlanetsWhichActuallyDevelopLife*PlanetsWithIntelligentLife*CivilizationsWithDetectors*DurationOfSpaceSignals=0:0:0:0:0:0:0:{20:1:10:1:1:1:20:}1:0.1:1:0.1:0.1:0.1:1:[10:0.5:2:1:0.1:0.1:10:;1:1:1:1:1:1:1:=Drake%20Equation]"

    });

Examples.push({
    name: "Monthly Loan Payments Calculator",
    fxn : "principal*((rate/1200)*(1 + rate/1200)^months)/((1 + rate/1200)^months - 1)",
    url : "principal*((rate/1200)*(1+rate/1200)^months)/((1+rate/1200)^months-1)=0:0:0:{200:100:100:}10:1:1:[110:9:23:;1:1:1:=Loan%20Calculator]"
});

Examples.push({
    name: "Force of Gravity",
    fxn : "GravConstant * massOne * massTwo / distance^2",
    url : "GravConstant*massOne*massTwo/distance^2=0:0:0:0:{20:100:100:100:}0.01:1:1:1:[8.73:29:19:3:;1:1:1:1:=Gravity]"
});

Examples.push({
    name: "E = mc^2",
    fxn : "mass*299792458^2",
    url : "mass*299792458^2=0:{100:}1:[20:;1:=E]"
});

Examples.push({
    name: "Area of Circle",
    fxn : "pi * radius^2",
    url : "pi*radius^2=0:{100:}1:[13:;1:=Circle%20Area]"
});

Examples.push({
    name: "Circumference of a Circle",
    fxn : "2*pi*radius",
    url : "2*pi*radius=0:{100:}1:[13:;1:=Circle%20Circumference]"
});

Examples.push({
    name: "Flake Equation (xkcd.com/718)",
    fxn : "7*1000^3 * (CrazyPeople + Misinterpret)/10000 * TellProbability/10 * NumberPeopleTold * FirstHandRetellings * IgnoredDataProbability/10 * WiderAudienceFraction/100",
    url : "7*1000^3*(CrazyPeople+Misinterpret)/10000*TellProbability/10*NumberPeopleTold*FirstHandRetellings*IgnoredDataProbability/10*WiderAudienceFraction/100=0:0:0:0:0:0:0:{10:10:10:100:100:10:100:}1:1:1:1:1:1:1:[1:1:1:10:10:9:1:;1:1:1:1:1:1:1:=Flake%20Equation%20(XKCD)]"
});

Examples.push({
    name: "Dateable Ages (xkcd.com/314)",
    fxn : "Age/2 + 7",
    url : "Age/2+7=18:{126:}1:[27:;1:=Who%20Can%20You%20Date]"
});

Examples.push({
    name: "TV Romantic Drama Equation (Straight) (xkcd.com/216)",
    fxn : "SameSex*(AllCast - SameSex)",
    url : "SameSex*(AllCast-SameSex)=0:0:{100:100:}1:1:[17:44:;1:1:=Romantic%20Pairings]"
});

Examples.push({
    name: "TV Romantic Drama Equation (Gay) (xkcd.com/216)",
    fxn : "AllCast*(AllCast - 1)/2 + SameSex*(SameSex - AllCast)",
    url : "AllCast*(AllCast-1)/2+SameSex*(SameSex-AllCast)=0:0:{100:100:}1:1:[45:25:;1:1:=Romantic%20Pairings]"
});

Examples.push({
    name: "Post-Game Seasonal Batting Average",
    fxn : "(SeasonBats * (SeasonalAverage/100) + Hits)/(SeasonBats + TimesAtBat)",
    url : "(SeasonBats*(SeasonalAverage/100)+Hits)/(SeasonBats+TimesAtBat)=0:0:0:0:{100:100:100:13:}1:1:1:1:[40:60:81:13:;1:1:1:1:=Post%20Game%20Batting%20Average]"
});

Examples.push({
    name: "Focal Length",
    fxn : "(ObjectDistance * LensToImageDistance)/(ObjectDistance + LensToImageDistance)",
    url : "(ObjectDistance*LensToImageDistance)/(ObjectDistance+LensToImageDistance)=0:0:{100:100:}1:1:[37:20:;1:1:=Focal%20Length]"
});

Examples.push({
    name: "Population Growth",
    fxn : "LastYearPopulation + LastYearPopulation*(ReproductiveRate - AttritionRate)",
    url : "LastYearPopulation+LastYearPopulation*(ReproductiveRate-AttritionRate)=0:0:0:{10000:1:1:}1:0.01:0.01:[4162:0.37:0.16:;0:1:1:=Population]"
});

Examples.push({
    name: "Fiber Optic Response Time",
    fxn : "ProcessingTime + (2*Distance)/(200*(1000^2))",
    url : "ProcessingTime+(2*Distance)/(200*(1000^2))=0:0:{100:100:}1:1:[12:40:;1:1:=Fiber%20Response%20Time]"
});

Examples.push({
    name: "Watts",
    fxn : "Amps * Volts",
    url : "Amps*Volts=0:0:{100:100:}0.01:0.01:[41.04:28.32:;1:1:=Watts]"
});

Examples.push({
    name: "Velocity - 1st Integral of Acceleration",
    fxn : "InitialVelocity + Acceleration*Time",
    url : "InitialVelocity+Acceleration*Time=0:0:0:{100:100:100:}1:0.1:1:[42:9.8:10:;1:1:1:=Velocity]"
});

Examples.push({
    name: "Position - 2nd Integral of Acceleration",
    fxn : "InitialPosition + InitialVelocity*Time + 1/2 * acceleration * Time^2",
    url : "InitialPosition+InitialVelocity*Time+1/2*acceleration*Time^2=0:0:0:0:{100:100:100:100:}1:1:0.1:0.1:[18:41:31:9.8:;1:1:1:1:=Position]"
});

Examples.push({
    name: "Torque",
    fxn : "radius * force * sin(angle)",
    url : "radius*force*sin(angle)=0:0:-360:{100:100:360:}1:1:1:[19:53:69:;1:1:1:=Torque]"
});

Examples.push({
    name: "Surface Area of Cylinder",
    fxn : "2*pi*radius*length + 2*pi*radius^2",
    url : "2*pi*radius*length+2*pi*radius^2=0:0:{100:100:}1:1:[31:17:;1:1:=Surface%20Area]"
});

Examples.push({
    name: "First Order Derivitive of x^n",
    fxn : "n*x^(n-1)",
    url : "n*x^(n-1)=0:0:{100:100:}1:1:[7:1:;1:1:=Derivative%20of%20x^N]"
});

Examples.push({
    name: "First Order Integral of x^n dx",
    fxn : "1/(n+1) * x^(n+1) + C",
    url : "1/(n+1)*x^(n+1)+C=0:-10:0:{3:10:100:}1:0.001:1:[1:12:13:;0:1:0:=First%20Order%20Integral]"
});

Examples.push({
    name: "Glomerular Filtration Rate (Creatinine Clearance CCr) (Kidney Filtration Rate)",
    fxn : "(CreatineConcentration * FlowRate)/PlasmaConcentration",
    url : "(CreatineConcentration*FlowRate)/PlasmaConcentration=0:0:0:{100:100:100:}1:1:1:[53:31:10:;1:1:1:=Glomular%20Filtration]"
});

Examples.push({
    name: "IPAT Environmental Impact Equation",
    fxn : "Population * Affluence * Technology",
    url : "Population*Affluence*Technology=0:0:0:{100:100:100:}1:1:1:[20:40:31:;1:1:1:=IPAT]"
});

Examples.push({
    name: "Vertical Change Delta for a Weighted String between 2 Points",
    fxn : "sqrt(((StringLength + PointsDistance)/2)*((StringLength - PointsDistance)/2))",
    url : "sqrt(((StringLength+PointsDistance)/2)*((StringLength-PointsDistance)/2))=0:0:{100:100:}1:1:[33:18:;1:1:=Weighed%20String]"
});

Examples.push({
    name: "Gaussian",
    fxn : "a * e^(-1*((x-b)^2/2*c^2))",
    url : "a*e^(-1*((x-b)^2/2*c^2))=0:0:0:0:{100:100:100:100:}1:1:1:1:[8:30:17:5:;1:1:1:1:=Gaussian]"
});

Examples.push({
    name: "Mechanical Work",
    fxn : "1/2 * mass * (secondVelocity^2 - firstVelocity^2)",
    url : "1/2*mass*(secondVelocity^2-firstVelocity^2)=0:0:0:{100:100:100:}1:1:1:[71:34:42:;1:1:1:=Mechanical%20Work]"
});

Examples.push({
    name: "Procrastination Equation",
    fxn : "ExpectationOfSuccess*ValueofCompletion / (ImmediacyOfTask * PersonalDelaySensitivity)",
    url : "ExpectationOfSuccess*ValueofCompletion/(ImmediacyOfTask*PersonalDelaySensitivity)=0:0:0:0:{100:100:100:100:}1:1:1:1:[6:9:6:11:;1:1:1:1:=Procrastination%20Likelihood]"
});

Examples.push({
    name: "Pressure Loss via Friction",
    fxn : "FrictionCoefficient * (length / hydraulicDiameter) * (density * velocity^2 /2)",
    url : "FrictionCoefficient*(length/hydraulicDiameter)*(density*velocity^2/2)=0:0:0:0:0:{0.5:100:100:100:100:}0.001:1:1:1:1:[0.029:13:25:14:20:;1:1:1:1:1:=Pressure%20Loss]"
});

Examples.push({
    name: "Lorentz Factor",
    fxn : "1 / sqrt(1-(velocity^2/c^2))",
    url : "1/sqrt(1-(velocity^2/c^2))=290000000:290000000:{300000000:310000000:}1:[299792000:299792458:;1000:1000:=Lorentz%20Factor]"
});

Examples.push({
    name: "Euclidean Distance in 2D",
    fxn : "sqrt((xTwo-xOne)^2 + (yTwo-yOne)^2)",
    url : "sqrt((xTwo-xOne)^2+(yTwo-yOne)^2)=0:0:0:0:{100:100:100:100:}1:1:1:1:[27:53:40:53:;1:1:1:1:=Euclidean%20Distance]"
});

Examples.push({
    name: "Quadratic Equation (First Solution)",
    fxn : "(-x + sqrt(b^2 - 4*a*c))/2*a",
    url : "(-x+sqrt(b^2-4*a*c))/2*a=0:0:0:0:{100:100:100:100:}1:1:1:1:[5:22:3:5:;1:1:1:1:=Quadratic%20Graph]"
});
Examples.push({
    name: "Complex Parenthesis Function",
    fxn : "sum(b*sin((x^(n-1))*pi),n*sin((x^(n-1))*pi),x^(n-2),(7*x*n))",
    url : "sum(b*sin((x^(n-1))*pi),n*sin((x^(n-1))*pi),x^(n-2),(7*x*n))=-100:-10:-4:{100:100:100:}1:1:1:[-85:-2:15:;1:1:1:=Complex%20Function]"
});
<|endoftext|>


<commit_before>$(function() {
	if(window.location.protocol === "https:") {
		location.href = "http://mywebservice.info/beauty/";
	}

	var url = "http://mywebservice.info/beautyUniversity/data_out/school/university";

	$( '.swipebox' ).swipebox( {
		afterOpen: function() {
			$("div.slide > img").attr("data-caption", "This test data-caption");
			$('img.caption').captionjs({
				'class_name'      : 'captionjs', // Class name for each

				'schema'          : true,        // Use schema.org markup (i.e., itemtype, itemprop)
				'mode'            : 'default',   // default | stacked | animated | hide
				'debug_mode'      : false,       // Output debug info to the JS console
				'force_dimensions': true,        // Force the dimensions in case they cannot be detected (e.g., image is not yet painted to viewport)
				'is_responsive'   : false,       // Ensure the figure and image change size when in responsive layout. Requires a container to control responsiveness!
				'inherit_styles'  : false        // Have the caption.js container inherit box-model properties from the original image
			});
		}
	});

	jsonGet(url);
	$(window).on('ajaxComplete', function() {
  		setTimeout(function() {
  			$(window).lazyLoadXT();
  		}, 50);
	});

	$("#go-top").click(function(event) {
		event.preventDefault();
		$("html, body").animate({ scrollTop: 0 }, "slow");
	});

	$("#go-school-btn").click(function(event) {
		event.preventDefault();
		$("#img-contents").html("");
		if($("#fans-page-name").text() === "表特大學") {
			$("#go-school-btn").text("表特大學");
			$("#fans-page-name").text("表特輔仁");
			url = "http://mywebservice.info/beautyUniversity/data_out/school/FJU";
		}
		else {
			$("#go-school-btn").text("表特輔仁");
			$("#fans-page-name").text("表特大學");
			url = "http://mywebservice.info/beautyUniversity/data_out/school/university";
		}
		jsonGet(url);
	});

	/*
	$("#highchart-btn").click(function(event) {
		event.preventDefault();
		var str = "";
		if($("#fans-page-name").text() === "表特輔仁") {
			str = "FJU";
		}
		else {
			str = "university";
		}
		$("#img-contents").html("");
		$("#chart-container").html("");

		//using high chart

		 $('#chart-container').highcharts({
			chart: {
				plotBackgroundColor: null,
				plotBorderWidth: null,
				plotShadow: false,
				type: 'pie'
			},
			title: {
				text: 'Browser market shares January, 2015 to May, 2015'
			},
			tooltip: {
				pointFormat: '{series.name}: {point.percentage:.1f}%'
			},
        plotOptions: {
            pie: {
                allowPointSelect: true,
                cursor: 'pointer',
                dataLabels: {
                    enabled: true,
                    format: '{point.name}: {point.percentage:.1f} %',
                    style: {
                        color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
                    }
                }
            }
        },
        series: [{
            name: 'Brands',
            colorByPoint: true,
            data: [{
                name: 'Microsoft Internet Explorer',
                y: 56.33
            }, {
                name: 'Chrome',
                y: 24.03,
                sliced: true,
                selected: true
            }, {
                name: 'Firefox',
                y: 10.38
            }, {
                name: 'Safari',
                y: 4.77
            }, {
                name: 'Opera',
                y: 0.91
            }, {
                name: 'Proprietary or Undetectable',
                y: 0.2
            }]
        }]
    });
	});
	*/
});

function jsonGet(url) {
	$.getJSON(url, function(data) {
		var str = "";
		var j = 0;
		if(url.indexOf("university") !== -1) {
			for (var i = data.length - 1; i >= 0; i--) {
				if(data[i]["message"] === "" || data[i]["object_id"] === "") {
					continue;
				}

				str += "";
				str += "";
				str += "";
				j++;
			}
		}
		else {
			for (var i = 0; i < data.length; i++) {
				if(data[i]["message"] === "" || data[i]["object_id"] === "") {
					continue;
				}

				str += "";
				str += "";
				str += "";
				j++;
			}
		}
		console.log(j);
		$("#img-contents").append(str);
	 });
}

function getAnalytic(url) {

}<commit_msg>change captionjs option<commit_after>$(function() {
	if(window.location.protocol === "https:") {
		location.href = "http://mywebservice.info/beauty/";
	}

	var url = "http://mywebservice.info/beautyUniversity/data_out/school/university";

	$( '.swipebox' ).swipebox( {
		afterOpen: function() {
			$("div.slide > img").attr("data-caption", "This test data-caption");
			$('img.caption').captionjs({
				'class_name'      : 'captionjs', // Class name for each

				'schema'          : true,        // Use schema.org markup (i.e., itemtype, itemprop)
				'mode'            : 'stacked',   // default | stacked | animated | hide
				'debug_mode'      : true,       // Output debug info to the JS console
				'force_dimensions': true,        // Force the dimensions in case they cannot be detected (e.g., image is not yet painted to viewport)
				'is_responsive'   : true,       // Ensure the figure and image change size when in responsive layout. Requires a container to control responsiveness!
				'inherit_styles'  : false        // Have the caption.js container inherit box-model properties from the original image
			});
		}
	});

	jsonGet(url);
	$(window).on('ajaxComplete', function() {
  		setTimeout(function() {
  			$(window).lazyLoadXT();
  		}, 50);
	});

	$("#go-top").click(function(event) {
		event.preventDefault();
		$("html, body").animate({ scrollTop: 0 }, "slow");
	});

	$("#go-school-btn").click(function(event) {
		event.preventDefault();
		$("#img-contents").html("");
		if($("#fans-page-name").text() === "表特大學") {
			$("#go-school-btn").text("表特大學");
			$("#fans-page-name").text("表特輔仁");
			url = "http://mywebservice.info/beautyUniversity/data_out/school/FJU";
		}
		else {
			$("#go-school-btn").text("表特輔仁");
			$("#fans-page-name").text("表特大學");
			url = "http://mywebservice.info/beautyUniversity/data_out/school/university";
		}
		jsonGet(url);
	});

	/*
	$("#highchart-btn").click(function(event) {
		event.preventDefault();
		var str = "";
		if($("#fans-page-name").text() === "表特輔仁") {
			str = "FJU";
		}
		else {
			str = "university";
		}
		$("#img-contents").html("");
		$("#chart-container").html("");

		//using high chart

		 $('#chart-container').highcharts({
			chart: {
				plotBackgroundColor: null,
				plotBorderWidth: null,
				plotShadow: false,
				type: 'pie'
			},
			title: {
				text: 'Browser market shares January, 2015 to May, 2015'
			},
			tooltip: {
				pointFormat: '{series.name}: {point.percentage:.1f}%'
			},
        plotOptions: {
            pie: {
                allowPointSelect: true,
                cursor: 'pointer',
                dataLabels: {
                    enabled: true,
                    format: '{point.name}: {point.percentage:.1f} %',
                    style: {
                        color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
                    }
                }
            }
        },
        series: [{
            name: 'Brands',
            colorByPoint: true,
            data: [{
                name: 'Microsoft Internet Explorer',
                y: 56.33
            }, {
                name: 'Chrome',
                y: 24.03,
                sliced: true,
                selected: true
            }, {
                name: 'Firefox',
                y: 10.38
            }, {
                name: 'Safari',
                y: 4.77
            }, {
                name: 'Opera',
                y: 0.91
            }, {
                name: 'Proprietary or Undetectable',
                y: 0.2
            }]
        }]
    });
	});
	*/
});

function jsonGet(url) {
	$.getJSON(url, function(data) {
		var str = "";
		var j = 0;
		if(url.indexOf("university") !== -1) {
			for (var i = data.length - 1; i >= 0; i--) {
				if(data[i]["message"] === "" || data[i]["object_id"] === "") {
					continue;
				}

				str += "";
				str += "";
				str += "";
				j++;
			}
		}
		else {
			for (var i = 0; i < data.length; i++) {
				if(data[i]["message"] === "" || data[i]["object_id"] === "") {
					continue;
				}

				str += "";
				str += "";
				str += "";
				j++;
			}
		}
		console.log(j);
		$("#img-contents").append(str);
	 });
}

function getAnalytic(url) {

}<|endoftext|>


<commit_before>var EventEmitter = function(){
  var self = this;
  this.apply = function(target, prefix){
    if(!prefix) prefix = "";
    for(var func in self){
      if(self.hasOwnProperty(func) && func !== "apply"){
        target[prefix+func] = this[func];
      }
    }
  };
  this.__events = new Array();
  this.on = function(type, listener, opts){
    if(typeof listener !== "function") return;
    var event_id = self.__events.length > 0 ? 1 + self.__events[self.__events.length-1].id : 0
    var params = {
      id: event_id,
      type: type,
      listener: listener
    };
    for(i in opts){
      if(!params[i]) params[i] = opts[i];
    };
    self.__events.push(params);
    return event_id;
  };

  this.once = function(type, listener){
    self.on(type, listener, {once: true});
  };

  this.emit = function(type, data){
    for(var i = 0; i < self.__events.length; i++){
      var e = self.__events[i];
      switch(e.type){
      case type:
        e.listener(data);
        if(e.once) self.removeListener(e.id);
        break
      case '*':
        e.listener(type, data);
        if(e.once) self.removeListener(e.id);
        break
      }
    }
  };

  this.removeListener = function(id_or_type){
    for(var i = self.__events.length-1; i >= 0; i--){
      var e = self.__events[i];
      switch(typeof id_or_type){
      case "number":
        if(e.id == id_or_type) self.__events.splice(i,1);
        break
      case "string":
        if(e.type == id_or_type) self.__events.splice(i,1);
        break
      }
    }
  };

};

if(typeof module !== 'undefined' && typeof module.exports !== 'undefined'){
  module.exports = EventEmitter;
}
<commit_msg>bugfix for multiple once  #5<commit_after>var EventEmitter = function(){
  var self = this;
  this.apply = function(target, prefix){
    if(!prefix) prefix = "";
    for(var func in self){
      if(self.hasOwnProperty(func) && func !== "apply"){
        target[prefix+func] = this[func];
      }
    }
  };
  this.__events = new Array();
  this.on = function(type, listener, opts){
    if(typeof listener !== "function") return;
    var event_id = self.__events.length > 0 ? 1 + self.__events[self.__events.length-1].id : 0
    var params = {
      id: event_id,
      type: type,
      listener: listener
    };
    for(i in opts){
      if(!params[i]) params[i] = opts[i];
    };
    self.__events.push(params);
    return event_id;
  };

  this.once = function(type, listener){
    self.on(type, listener, {once: true});
  };

  this.emit = function(type, data){
    for(var i = 0; i < self.__events.length; i++){
      var e = self.__events[i];
      switch(e.type){
      case type:
        e.listener(data);
        if(e.once) e.type = null;
        break
      case "*":
        e.listener(type, data);
        if(e.once) e.type = null;
        break
      }
    }
    self.removeListener();
  };

  this.removeListener = function(id_or_type){
    for(var i = self.__events.length-1; i >= 0; i--){
      var e = self.__events[i];
      switch(typeof id_or_type){
      case "number":
        if(e.id === id_or_type) self.__events.splice(i,1);
        break
      case "string":
      case "object":
        if(e.type === id_or_type) self.__events.splice(i,1);
        break
      }
    }
  };

};

if(typeof module !== "undefined" && typeof module.exports !== "undefined"){
  module.exports = EventEmitter;
}
<|endoftext|>


<commit_before>const utils = require(`${__baseDir}/modules/utils`);

module.exports = bot => {
    bot.on('guildCreate', g => {
        if (g.members.filter(m => m.bot).size / g.members.size >= 0.75) {
            logger.info(`Leaving bot collection '${g.name}' (${g.id})`);
            g.leave();
        } else {
            bot.editStatus('online', {name: `${bot.config.gameName || `${bot.config.mainPrefix}help for commands!`} | ${bot.guilds.size} ${bot.guilds.size === 1 ? 'server' : 'servers'}`, type: bot.config.gameURL ? 1 : 0, url: `${bot.config.gameURL || null}`});
            bot.postGuildCount();
        }
    });

    bot.on('guildDelete', () => {
        if (!(g.members.filter(m => m.bot).size/g.members.size >= 0.75)) {
            bot.editStatus('online', {name: `${bot.config.gameName || `${bot.config.mainPrefix}help for commands!`} | ${bot.guilds.size} ${bot.guilds.size === 1 ? 'server' : 'servers'}`, type: bot.config.gameURL ? 1 : 0, url: `${bot.config.gameURL || null}`});
            bot.postGuildCount();
        }
    });

    bot.on('guildMemberAdd', (g, m) => {
        bot.getGuildSettings(g.id).then(res => {
            if (!res || !res.greeting || !res.greeting.enabled || !res.greeting.channelID || !res.greeting.message) {
                return null;
            } else {
                let msg = res.greeting.message.replace(/\{\{user\}\}/g, m.mention).replace(/\{\{name\}\}/g, utils.formatUsername(m));
                return g.channels.get(res.greeting.channelID).createMessage(msg);
            }
        });
    });

    bot.on('guildMemberDelete', (g, m) => {
        bot.guildSettings(g.id).then(res => {
            if (!res || !res.greeting || !res.greeting.enabled || !res.greeting.channelID || !res.parting.message) {
                return null;
            } else {
                let msg = res.parting.message.replace(/\{\user\}\}/g, m.mention).replace(/\{name\}\}/g, utils.formatUsername(m));
                return g.channels.get(res.greeting.channelID).createMessage(msg);
            }
        });
    });
};
<commit_msg>ovypls you hecking child<commit_after>const utils = require(`${__baseDir}/modules/utils`);

module.exports = bot => {
    bot.on('guildCreate', g => {
        if (g.members.filter(m => m.bot).size / g.members.size >= 0.75) {
            logger.info(`Leaving bot collection '${g.name}' (${g.id})`);
            g.leave();
        } else {
            bot.editStatus('online', {name: `${bot.config.gameName || `${bot.config.mainPrefix}help for commands!`} | ${bot.guilds.size} ${bot.guilds.size === 1 ? 'server' : 'servers'}`, type: bot.config.gameURL ? 1 : 0, url: `${bot.config.gameURL || null}`});
            bot.postGuildCount();
        }
    });

    bot.on('guildDelete', () => {
        if (!(g.members.filter(m => m.bot).size/g.members.size >= 0.50)) {
            bot.editStatus('online', {name: `${bot.config.gameName || `${bot.config.mainPrefix}help for commands!`} | ${bot.guilds.size} ${bot.guilds.size === 1 ? 'server' : 'servers'}`, type: bot.config.gameURL ? 1 : 0, url: `${bot.config.gameURL || null}`});
            bot.postGuildCount();
        }
    });

    bot.on('guildMemberAdd', (g, m) => {
        bot.getGuildSettings(g.id).then(res => {
            if (!res || !res.greeting || !res.greeting.enabled || !res.greeting.channelID || !res.greeting.message) {
                return null;
            } else {
                let msg = res.greeting.message.replace(/\{\{user\}\}/g, m.mention).replace(/\{\{name\}\}/g, utils.formatUsername(m));
                return g.channels.get(res.greeting.channelID).createMessage(msg);
            }
        });
    });

    bot.on('guildMemberDelete', (g, m) => {
        bot.guildSettings(g.id).then(res => {
            if (!res || !res.greeting || !res.greeting.enabled || !res.greeting.channelID || !res.parting.message) {
                return null;
            } else {
                let msg = res.parting.message.replace(/\{\user\}\}/g, m.mention).replace(/\{name\}\}/g, utils.formatUsername(m));
                return g.channels.get(res.greeting.channelID).createMessage(msg);
            }
        });
    });
};
<|endoftext|>