<commit_before>/*global Prism*/
var highlightCorrection = -1;

function highlightLines(jPre, lineNumber, secondLineNumber, connected) {
    var line, secondLine, lineHeight = parseFloat(jPre.css("line-height"));

    lineNumber = lineNumber + highlightCorrection;
    if (secondLineNumber !== undefined) {
        secondLineNumber = secondLineNumber + highlightCorrection;
    }

    line = jPre.find(".line-highlight").eq(0);
    secondLine = jPre.find(".line-highlight").eq(1);
    line.show();

    line.css("top", lineNumber * Math.floor(lineHeight) + 'px');

    if (connected === true) {
        //create a bunch of new lines, which will cause this to highlight multiple lines
        line.text(new Array(secondLineNumber - lineNumber + 2).join(' \r\n'));
        secondLine.hide();
    } else if (secondLineNumber !== undefined) {
        line.text("\r\n");
        secondLine.css("top", secondLineNumber * Math.floor(lineHeight) + 'px');
        secondLine.show();
    } else {
        line.text("\r\n");
        secondLine.hide();
    }
}

function getMouseOverLine(jPre, yOffset) {
    var lineHeight = parseFloat(jPre.css("line-height"));
    return Math.floor((yOffset - 5) / lineHeight) + 1;		//+1 to account for the top buffer zone
}

function checkEndPointsForNum(first, second, test) {
    if (test === parseInt(first, 10) || test === parseInt(second, 10)) {
        return true;
    }
    return false;
}

function checkRangeForNum(first, second, test) {
    if (test >= parseInt(first, 10) && test <= parseInt(second, 10)) {
        return true;
    }
    return false;
}

//returns true if this comment is relevent to the selected line
function handleHighlightsAndComment(jComment, selectedLine, enclosingObject) {
    var dataString, splits;

    if (jComment !== undefined) {
        dataString = jComment.data("show");
    }

    if (typeof (dataString) == "string") {
        if (dataString.indexOf("-") != -1) {
            splits = dataString.split("-");
            if (checkRangeForNum(splits[0], splits[1], selectedLine)) {
                jComment.show();
                highlightLines(enclosingObject, parseInt(splits[0], 10), parseInt(splits[1], 10), true);
                return true;
            }
        } else if (dataString.indexOf("+") != -1) {
            splits = dataString.split("+");
            if (checkEndPointsForNum(splits[0], splits[1], selectedLine)) {
                jComment.show();
                highlightLines(enclosingObject, parseInt(splits[0], 10), parseInt(splits[1], 10));
                return true;
            }
        }
        else {
            console.log("not supported data string " + dataString);
        }
    }
    else {
        if (selectedLine == dataString) {
            jComment.show();
            highlightLines(enclosingObject, selectedLine);
            return true;
        }
    }
    highlightLines(enclosingObject, selectedLine);
    return false;
}

var isAnimating = false;

function adjustCodeCommentBoxForMousePosition(codeComment, y) {
    var height = parseInt(codeComment.css("height"), 10), currTop = parseInt(codeComment.css("top"), 10), newTop,
	//rect is the code comment's rectangle relative to the viewport
	rect = codeComment.get(0).getBoundingClientRect(), parent, parentHeight;

    parent = codeComment.closest(".codeContainer");

    if (!isAnimating && currTop + 0.2 * height > y) {
        //scroll up
        newTop = Math.max(y - (0.3 * height), 10, currTop - (rect.top - 60));	//-60 because the nav bar's height is 50 and I want some space
        codeComment.animate({ top: newTop }, 150);
        isAnimating = true;
        setTimeout(function () { isAnimating = false; }, 150);
    }

    else if (!isAnimating && currTop + 0.8 * height < y) {
        //scroll down
        parentHeight = parseInt(parent.css("height"), 10);
        //the top should never be less than 10, but we don't want it to scroll down off the edge (10px margin)
        newTop = Math.max(10, Math.min((y - (0.7 * height)), parentHeight - (height + 10), currTop + (window.innerHeight - rect.bottom) - 10));
        codeComment.animate({ top: newTop }, 150);
        isAnimating = true;
        setTimeout(function () { isAnimating = false; }, 150);
    }
}

Prism.hooks.add('after-highlight', function (env) {
    var numbersToHighlight, lineNumbers, container, mouseComments;
    if (env.code == "Loading…") {
        return;
    }
    numbersToHighlight = [];
    console.log("call ");
    console.log(env);

    container = $(env.element).closest(".codeContainer");

    mouseComments = container.find(".mouseComment");
    mouseComments.each(function (j, mc) {
        var i, show, range = false, lines;
        show = mc.getAttribute("data-show");
        lines = show.split(/[\+\-]/);
        if (show.indexOf("+") === -1) {
            range = true;
        }
        if (range && lines.length > 1) {
            for (i = parseInt(lines[0], 10) ; i <= parseInt(lines[1], 10) ; i++) {
                numbersToHighlight.push(i - 1);
            }
        } else {
            for (i = 0; i < lines.length; i++) {
                numbersToHighlight.push(parseInt(lines[i], 10)-1);		//subtract 1 because these lines are 1 indexed, not 0-indexed
            }
        }
    });

    console.log(numbersToHighlight);

    if (numbersToHighlight.length > 0) {
        lineNumbers = container.find(".line-numbers-rows span");
        lineNumbers.each(function (j, n) {
            if (-1 !== numbersToHighlight.indexOf(j)) {
                n.setAttribute("data-comment", "*");
                n.className = "starredBolded";
            }
        });
    }
});

$(document).ready(function () {
    console.log("codeCommentary.js");
    $(".codeContainer").on("mousemove", "pre", function (e) {
        var selectedLine, y, comments, enclosingObject = $(this);

        y = e.offsetY === undefined ? e.layerY : e.offsetY;

        selectedLine = getMouseOverLine(enclosingObject, y);

        comments = enclosingObject.closest(".codeContainer").find(".mouseComment");
        comments.hide();

        if (comments.size() > 0) {
            comments.each(function (i, element) {
                if (handleHighlightsAndComment($(element), selectedLine, enclosingObject)) {
                    //break
                    return false;
                }
            });
        } else {
            handleHighlightsAndComment(undefined, selectedLine, enclosingObject);
        }
        adjustCodeCommentBoxForMousePosition(enclosingObject.closest(".codeContainer").find(".codeComment"), y);
    });

});<commit_msg>JSHint<commit_after>/*global Prism*/
var highlightCorrection = -1;

function highlightLines(jPre, lineNumber, secondLineNumber, connected) {
    var line, secondLine, lineHeight = parseFloat(jPre.css("line-height"));

    lineNumber = lineNumber + highlightCorrection;
    if (secondLineNumber !== undefined) {
        secondLineNumber = secondLineNumber + highlightCorrection;
    }

    line = jPre.find(".line-highlight").eq(0);
    secondLine = jPre.find(".line-highlight").eq(1);
    line.show();

    line.css("top", lineNumber * Math.floor(lineHeight) + 'px');

    if (connected === true) {
        //create a bunch of new lines, which will cause this to highlight multiple lines
        line.text(new Array(secondLineNumber - lineNumber + 2).join(' \r\n'));
        secondLine.hide();
    } else if (secondLineNumber !== undefined) {
        line.text("\r\n");
        secondLine.css("top", secondLineNumber * Math.floor(lineHeight) + 'px');
        secondLine.show();
    } else {
        line.text("\r\n");
        secondLine.hide();
    }
}

function getMouseOverLine(jPre, yOffset) {
    var lineHeight = parseFloat(jPre.css("line-height"));
    return Math.floor((yOffset - 5) / lineHeight) + 1;		//+1 to account for the top buffer zone
}

function checkEndPointsForNum(first, second, test) {
    if (test === parseInt(first, 10) || test === parseInt(second, 10)) {
        return true;
    }
    return false;
}

function checkRangeForNum(first, second, test) {
    if (test >= parseInt(first, 10) && test <= parseInt(second, 10)) {
        return true;
    }
    return false;
}

//returns true if this comment is relevent to the selected line
function handleHighlightsAndComment(jComment, selectedLine, enclosingObject) {
    var dataString, splits;

    if (jComment !== undefined) {
        dataString = jComment.data("show");
    }

    if (typeof (dataString) == "string") {
        if (dataString.indexOf("-") != -1) {
            splits = dataString.split("-");
            if (checkRangeForNum(splits[0], splits[1], selectedLine)) {
                jComment.show();
                highlightLines(enclosingObject, parseInt(splits[0], 10), parseInt(splits[1], 10), true);
                return true;
            }
        } else if (dataString.indexOf("+") != -1) {
            splits = dataString.split("+");
            if (checkEndPointsForNum(splits[0], splits[1], selectedLine)) {
                jComment.show();
                highlightLines(enclosingObject, parseInt(splits[0], 10), parseInt(splits[1], 10));
                return true;
            }
        }
        else {
            console.log("not supported data string " + dataString);
        }
    }
    else {
        if (selectedLine == dataString) {
            jComment.show();
            highlightLines(enclosingObject, selectedLine);
            return true;
        }
    }
    highlightLines(enclosingObject, selectedLine);
    return false;
}

var isAnimating = false;

function adjustCodeCommentBoxForMousePosition(codeComment, y) {
    var height = parseInt(codeComment.css("height"), 10), currTop = parseInt(codeComment.css("top"), 10), newTop,
	//rect is the code comment's rectangle relative to the viewport
	rect = codeComment.get(0).getBoundingClientRect(), parent, parentHeight;

    parent = codeComment.closest(".codeContainer");

    if (!isAnimating && currTop + 0.2 * height > y) {
        //scroll up
        newTop = Math.max(y - (0.3 * height), 10, currTop - (rect.top - 60));	//-60 because the nav bar's height is 50 and I want some space
        codeComment.animate({ top: newTop }, 150);
        isAnimating = true;
        setTimeout(function () { isAnimating = false; }, 150);
    }

    else if (!isAnimating && currTop + 0.8 * height < y) {
        //scroll down
        parentHeight = parseInt(parent.css("height"), 10);
        //the top should never be less than 10, but we don't want it to scroll down off the edge (10px margin)
        newTop = Math.max(10, Math.min((y - (0.7 * height)), parentHeight - (height + 10), currTop + (window.innerHeight - rect.bottom) - 10));
        codeComment.animate({ top: newTop }, 150);
        isAnimating = true;
        setTimeout(function () { isAnimating = false; }, 150);
    }
}

Prism.hooks.add('after-highlight', function (env) {
    var numbersToHighlight, lineNumbers, container, mouseComments;
    if (env.code == "Loading…") {
        return;
    }
    numbersToHighlight = [];
    console.log("call ");
    console.log(env);

    container = $(env.element).closest(".codeContainer");

    mouseComments = container.find(".mouseComment");
    mouseComments.each(function (j, mc) {
        var i, show, range = false, lines;
        show = mc.getAttribute("data-show");
        lines = show.split(/[\+\-]/);
        if (show.indexOf("+") === -1) {
            range = true;
        }
        if (range && lines.length > 1) {
            for (i = parseInt(lines[0], 10) ; i <= parseInt(lines[1], 10) ; i++) {
                numbersToHighlight.push(i - 1);
            }
        } else {
            for (i = 0; i < lines.length; i++) {
                numbersToHighlight.push(parseInt(lines[i], 10) - 1);		//subtract 1 because these lines are 1 indexed, not 0-indexed
            }
        }
    });

    console.log(numbersToHighlight);

    if (numbersToHighlight.length > 0) {
        lineNumbers = container.find(".line-numbers-rows span");
        lineNumbers.each(function (j, n) {
            if (-1 !== numbersToHighlight.indexOf(j)) {
                n.setAttribute("data-comment", "*");
                n.className = "starredBolded";
            }
        });
    }
});

$(document).ready(function () {
    console.log("codeCommentary.js");
    $(".codeContainer").on("mousemove", "pre", function (e) {
        var selectedLine, y, comments, enclosingObject = $(this);

        y = e.offsetY === undefined ? e.layerY : e.offsetY;

        selectedLine = getMouseOverLine(enclosingObject, y);

        comments = enclosingObject.closest(".codeContainer").find(".mouseComment");
        comments.hide();

        if (comments.size() > 0) {
            comments.each(function (i, element) {
                if (handleHighlightsAndComment($(element), selectedLine, enclosingObject)) {
                    //break
                    return false;
                }
            });
        } else {
            handleHighlightsAndComment(undefined, selectedLine, enclosingObject);
        }
        adjustCodeCommentBoxForMousePosition(enclosingObject.closest(".codeContainer").find(".codeComment"), y);
    });

});<|endoftext|>


<commit_before>var _ = require('lodash');
var fs = require('fs');
var path = require('path');
var async = require('async');
var mkdirp = require('mkdirp');
var childProcess = require('child_process');
var util = require('util');
var sha1 = require('sha1');

module.exports = function(animeData, episodesData, opts, callback) {
  async.eachSeries(episodesData, function onEpisode(episode, nextEpisode) {
    var titleForFilename = animeData.anime.title;
    titleForFilename = titleForFilename.split('/').pop();
    titleForFilename = _.trim(titleForFilename);
    titleForFilename = titleForFilename.replace(/[\/\\:\*\?"<>\|]/g, '-');
    var fileName = titleForFilename + ' - ' + _.padLeft(episode.index + 1, 3, '0') + episode.typeDescription + '.mp4';
    var destDir = path.join(__dirname, 'downloads');
    if (opts['downloads-dest']) {
      destDir = opts['downloads-dest'];
    }
    var filePath = path.join(destDir, titleForFilename);
    if (!fs.existsSync(filePath)) {
      mkdirp.sync(filePath);
    }
    if (fs.existsSync(path.join(filePath, fileName))) {
      console.log('Episode %d exists, skipping...', episode.index + 1);
      return nextEpisode();
    }
    console.log('Downloading episode %d...', episode.index + 1);
    var tempFileName = sha1(fileName);
    var axelBinaryPath = 'axel';
    var isWindows = /^win/.test(process.platform);
    if (isWindows) {
      axelBinaryPath = path.join(__dirname, 'bin', 'windows', 'axel.exe');
    }
    var axel = childProcess.spawn(axelBinaryPath, ['-a', '-n 8', '-o' + tempFileName, episode.url], {cwd: filePath});
    axel.stdout.on('data', function(data) {
      if (isWindows) {
        data = data.replace(/\r/g, '\033[0G');
      }
      process.stdout.write(data);
    });
    axel.stderr.on('data', function(data) {
      console.error(data);
    });
    axel.on('error', function(err) {
      console.error('Error while downloading episode %d: %s', episode.index + 1, err.message);
      process.exit(1);
    });
    axel.on('close', function(code) {
      if (code) {
        console.error('Error while downloading episode %d.', episode.index + 1);
        process.exit(1);
      }
      console.log('Episode %d download done.', episode.index + 1);
      fs.rename(path.join(filePath, tempFileName), path.join(filePath, fileName));
      nextEpisode();
    });

    //var len;
    //var cur = 0;
    //var downloadStatus = _.throttle(function() {
    //  process.stdout.write("Downloading episode " + (episode.index + 1).toString() + " - " + (100.0 * cur / len).toFixed(2) + "% - " + filesize(cur).human() + "          \r");
    //}, 300);
    //request(episode.url)
    //  .on('response', function(response) {
    //    len = parseInt(response.headers['content-length'], 10);
    //  })
    //  .on('data', function(chunk) {
    //    cur += chunk.length;
    //    downloadStatus();
    //  })
    //  .on('end', function() {
    //    console.log('\nEpisode %d download done.', episode.index + 1);
    //    nextEpisode();
    //  })
    //  .on('error', function (err) {
    //    console.log('\nError when downloading file %s: %s', episode.url, err.message);
    //    process.exit(1);
    //  })
    //  .pipe(fs.createWriteStream(path.join(filePath, fileName)));

  }, callback);
};<commit_msg>Improved Axel output on Windows.<commit_after>var _ = require('lodash');
var fs = require('fs');
var path = require('path');
var async = require('async');
var mkdirp = require('mkdirp');
var childProcess = require('child_process');
var util = require('util');
var sha1 = require('sha1');

module.exports = function(animeData, episodesData, opts, callback) {
  async.eachSeries(episodesData, function onEpisode(episode, nextEpisode) {
    var titleForFilename = animeData.anime.title;
    titleForFilename = titleForFilename.split('/').pop();
    titleForFilename = _.trim(titleForFilename);
    titleForFilename = titleForFilename.replace(/[\/\\:\*\?"<>\|]/g, '-');
    var fileName = titleForFilename + ' - ' + _.padLeft(episode.index + 1, 3, '0') + episode.typeDescription + '.mp4';
    var destDir = path.join(__dirname, 'downloads');
    if (opts['downloads-dest']) {
      destDir = opts['downloads-dest'];
    }
    var filePath = path.join(destDir, titleForFilename);
    if (!fs.existsSync(filePath)) {
      mkdirp.sync(filePath);
    }
    if (fs.existsSync(path.join(filePath, fileName))) {
      console.log('Episode %d exists, skipping...', episode.index + 1);
      return nextEpisode();
    }
    console.log('Downloading episode %d...', episode.index + 1);
    var tempFileName = sha1(fileName);
    var axelBinaryPath = 'axel';
    var isWindows = /^win/.test(process.platform);
    if (isWindows) {
      axelBinaryPath = path.join(__dirname, 'bin', 'windows', 'axel.exe');
    }
    var axel = childProcess.spawn(axelBinaryPath, ['-a', '-n 8', '-o' + tempFileName, episode.url], {cwd: filePath});
    axel.stdout.on('data', function(data) {
      if (isWindows) {
        data = data.toString().replace(/\r/g, '\033[0G');
      }
      process.stdout.write(data);
    });
    axel.stderr.on('data', function(data) {
      console.error(data);
    });
    axel.on('error', function(err) {
      console.error('Error while downloading episode %d: %s', episode.index + 1, err.message);
      process.exit(1);
    });
    axel.on('close', function(code) {
      if (code) {
        console.error('Error while downloading episode %d.', episode.index + 1);
        process.exit(1);
      }
      console.log('Episode %d download done.', episode.index + 1);
      fs.rename(path.join(filePath, tempFileName), path.join(filePath, fileName));
      nextEpisode();
    });

    //var len;
    //var cur = 0;
    //var downloadStatus = _.throttle(function() {
    //  process.stdout.write("Downloading episode " + (episode.index + 1).toString() + " - " + (100.0 * cur / len).toFixed(2) + "% - " + filesize(cur).human() + "          \r");
    //}, 300);
    //request(episode.url)
    //  .on('response', function(response) {
    //    len = parseInt(response.headers['content-length'], 10);
    //  })
    //  .on('data', function(chunk) {
    //    cur += chunk.length;
    //    downloadStatus();
    //  })
    //  .on('end', function() {
    //    console.log('\nEpisode %d download done.', episode.index + 1);
    //    nextEpisode();
    //  })
    //  .on('error', function (err) {
    //    console.log('\nError when downloading file %s: %s', episode.url, err.message);
    //    process.exit(1);
    //  })
    //  .pipe(fs.createWriteStream(path.join(filePath, fileName)));

  }, callback);
};<|endoftext|>


<commit_before>/**
 * Main file
 * Pokemon Showdown - http://pokemonshowdown.com/
 *
 * This is the main Pokemon Showdown app, and the file you should be
 * running to start Pokemon Showdown if you're using it normally.
 *
 * This file sets up our SockJS server, which handles communication
 * between users and your server, and also sets up globals. You can
 * see details in their corresponding files, but here's an overview:
 *
 * Users - from users.js
 *
 *   Most of the communication with users happens in users.js, we just
 *   forward messages between the sockets.js and users.js.
 *
 * Rooms - from rooms.js
 *
 *   Every chat room and battle is a room, and what they do is done in
 *   rooms.js. There's also a global room which every user is in, and
 *   handles miscellaneous things like welcoming the user.
 *
 * Dex - from sim/dex.js
 *
 *   Handles getting data about Pokemon, items, etc.
 *
 * Ladders - from ladders.js and ladders-remote.js
 *
 *   Handles Elo rating tracking for players.
 *
 * Chat - from chat.js
 *
 *   Handles chat and parses chat commands like /me and /ban
 *
 * Sockets - from sockets.js
 *
 *   Used to abstract out network connections. sockets.js handles
 *   the actual server and connection set-up.
 *
 * @license MIT license
 */

'use strict';

// Check for version and dependencies
try {
	// I've gotten enough reports by people who don't use the launch
	// script that this is worth repeating here
	eval('{ let a = async () => {}; }');
} catch (e) {
	throw new Error("We require Node.js version 8 or later; you're using " + process.version);
}
try {
	require.resolve('sockjs');
} catch (e) {
	throw new Error("Dependencies are unmet; run node pokemon-showdown before launching Pokemon Showdown again.");
}

const FS = require('./lib/fs');

/*********************************************************
 * Load configuration
 *********************************************************/

try {
	require.resolve('./config/config');
} catch (err) {
	if (err.code !== 'MODULE_NOT_FOUND') throw err; // should never happen
	throw new Error('config.js does not exist; run node pokemon-showdown to set up the default config file before launching Pokemon Showdown again.');
}

global.Config = require('./config/config');

global.Monitor = require('./monitor');

if (Config.watchconfig) {
	let configPath = require.resolve('./config/config');
	FS(configPath).onModify(() => {
		try {
			delete require.cache[configPath];
			global.Config = require('./config/config');
			if (global.Users) Users.cacheGroupData();
			Monitor.notice('Reloaded config/config.js');
		} catch (e) {
			Monitor.adminlog(`Error reloading config/config.js: ${e.stack}`);
		}
	});
}

/*********************************************************
 * Set up most of our globals
 *********************************************************/

global.Dex = require('./sim/dex');
global.toId = Dex.getId;

global.LoginServer = require('./loginserver');

global.Ladders = require('./ladders');

global.Users = require('./users');

global.Punishments = require('./punishments');

global.Chat = require('./chat');

global.Rooms = require('./rooms');

global.Verifier = require('./verifier');
Verifier.PM.spawn();

global.Tournaments = require('./tournaments');

global.Dnsbl = require('./dnsbl');
Dnsbl.loadDatacenters();

if (Config.crashguard) {
	// graceful crash - allow current battles to finish before restarting
	process.on('uncaughtException', err => {
		let crashType = require('./lib/crashlogger')(err, 'The main process');
		if (crashType === 'lockdown') {
			Rooms.global.startLockdown(err);
		} else {
			Rooms.global.reportCrash(err);
		}
	});
	process.on('unhandledRejection', err => {
		let crashType = require('./lib/crashlogger')(err, 'A Promise in the main process');
		if (crashType === 'lockdown') {
			Rooms.global.startLockdown(err);
		} else {
			Rooms.global.reportCrash(err);
		}
	});
}

/*********************************************************
 * Start networking processes to be connected to
 *********************************************************/

global.Sockets = require('./sockets');

exports.listen = function (port, bindAddress, workerCount) {
	Sockets.listen(port, bindAddress, workerCount);
};

if (require.main === module) {
	// Launch the server directly when app.js is the main module. Otherwise,
	// in the case of app.js being imported as a module (e.g. unit tests),
	// postpone launching until app.listen() is called.
	let port;
	if (process.argv[2]) port = parseInt(process.argv[2]);
	Sockets.listen(port);
}

/*********************************************************
 * Set up our last global
 *********************************************************/

global.TeamValidatorAsync = require('./team-validator-async');
TeamValidatorAsync.PM.spawn();

/*********************************************************
 * Start up the REPL server
 *********************************************************/

require('./lib/repl').start('app', cmd => eval(cmd));
<commit_msg>Clarify crash type message<commit_after>/**
 * Main file
 * Pokemon Showdown - http://pokemonshowdown.com/
 *
 * This is the main Pokemon Showdown app, and the file you should be
 * running to start Pokemon Showdown if you're using it normally.
 *
 * This file sets up our SockJS server, which handles communication
 * between users and your server, and also sets up globals. You can
 * see details in their corresponding files, but here's an overview:
 *
 * Users - from users.js
 *
 *   Most of the communication with users happens in users.js, we just
 *   forward messages between the sockets.js and users.js.
 *
 * Rooms - from rooms.js
 *
 *   Every chat room and battle is a room, and what they do is done in
 *   rooms.js. There's also a global room which every user is in, and
 *   handles miscellaneous things like welcoming the user.
 *
 * Dex - from sim/dex.js
 *
 *   Handles getting data about Pokemon, items, etc.
 *
 * Ladders - from ladders.js and ladders-remote.js
 *
 *   Handles Elo rating tracking for players.
 *
 * Chat - from chat.js
 *
 *   Handles chat and parses chat commands like /me and /ban
 *
 * Sockets - from sockets.js
 *
 *   Used to abstract out network connections. sockets.js handles
 *   the actual server and connection set-up.
 *
 * @license MIT license
 */

'use strict';

// Check for version and dependencies
try {
	// I've gotten enough reports by people who don't use the launch
	// script that this is worth repeating here
	eval('{ let a = async () => {}; }');
} catch (e) {
	throw new Error("We require Node.js version 8 or later; you're using " + process.version);
}
try {
	require.resolve('sockjs');
} catch (e) {
	throw new Error("Dependencies are unmet; run node pokemon-showdown before launching Pokemon Showdown again.");
}

const FS = require('./lib/fs');

/*********************************************************
 * Load configuration
 *********************************************************/

try {
	require.resolve('./config/config');
} catch (err) {
	if (err.code !== 'MODULE_NOT_FOUND') throw err; // should never happen
	throw new Error('config.js does not exist; run node pokemon-showdown to set up the default config file before launching Pokemon Showdown again.');
}

global.Config = require('./config/config');

global.Monitor = require('./monitor');

if (Config.watchconfig) {
	let configPath = require.resolve('./config/config');
	FS(configPath).onModify(() => {
		try {
			delete require.cache[configPath];
			global.Config = require('./config/config');
			if (global.Users) Users.cacheGroupData();
			Monitor.notice('Reloaded config/config.js');
		} catch (e) {
			Monitor.adminlog(`Error reloading config/config.js: ${e.stack}`);
		}
	});
}

/*********************************************************
 * Set up most of our globals
 *********************************************************/

global.Dex = require('./sim/dex');
global.toId = Dex.getId;

global.LoginServer = require('./loginserver');

global.Ladders = require('./ladders');

global.Users = require('./users');

global.Punishments = require('./punishments');

global.Chat = require('./chat');

global.Rooms = require('./rooms');

global.Verifier = require('./verifier');
Verifier.PM.spawn();

global.Tournaments = require('./tournaments');

global.Dnsbl = require('./dnsbl');
Dnsbl.loadDatacenters();

if (Config.crashguard) {
	// graceful crash - allow current battles to finish before restarting
	process.on('uncaughtException', err => {
		let crashType = require('./lib/crashlogger')(err, 'The main process');
		if (crashType === 'lockdown') {
			Rooms.global.startLockdown(err);
		} else {
			Rooms.global.reportCrash(err);
		}
	});
	process.on('unhandledRejection', err => {
		let crashType = require('./lib/crashlogger')(err, 'A main process Promise');
		if (crashType === 'lockdown') {
			Rooms.global.startLockdown(err);
		} else {
			Rooms.global.reportCrash(err);
		}
	});
}

/*********************************************************
 * Start networking processes to be connected to
 *********************************************************/

global.Sockets = require('./sockets');

exports.listen = function (port, bindAddress, workerCount) {
	Sockets.listen(port, bindAddress, workerCount);
};

if (require.main === module) {
	// Launch the server directly when app.js is the main module. Otherwise,
	// in the case of app.js being imported as a module (e.g. unit tests),
	// postpone launching until app.listen() is called.
	let port;
	if (process.argv[2]) port = parseInt(process.argv[2]);
	Sockets.listen(port);
}

/*********************************************************
 * Set up our last global
 *********************************************************/

global.TeamValidatorAsync = require('./team-validator-async');
TeamValidatorAsync.PM.spawn();

/*********************************************************
 * Start up the REPL server
 *********************************************************/

require('./lib/repl').start('app', cmd => eval(cmd));
<|endoftext|>


<commit_before>/*! UIkit 2.24.3 | http://www.getuikit.com | (c) 2014 YOOtheme | MIT License */
!function(e){function t(e,t,n,o){return Math.abs(e-t)>=Math.abs(n-o)?e-t>0?"Left":"Right":n-o>0?"Up":"Down"}function n(){p=null,g.last&&(void 0!==g.el&&g.el.trigger("longTap"),g={})}function o(){p&&clearTimeout(p),p=null}function i(){a&&clearTimeout(a),l&&clearTimeout(l),u&&clearTimeout(u),p&&clearTimeout(p),a=l=u=p=null,g={}}function r(e){return e.pointerType==e.MSPOINTER_TYPE_TOUCH&&e.isPrimary}if(!e.fn.swipeLeft){var a,l,u,p,c,g={},s=750;e(function(){var v,y,w,f=0,d=0;"MSGesture"in window&&(c=new MSGesture,c.target=document.body),e(document).on("MSGestureEnd gestureend",function(e){var t=e.originalEvent.velocityX>1?"Right":e.originalEvent.velocityX<-1?"Left":e.originalEvent.velocityY>1?"Down":e.originalEvent.velocityY<-1?"Up":null;t&&void 0!==g.el&&(g.el.trigger("swipe"),g.el.trigger("swipe"+t))}).on("touchstart MSPointerDown pointerdown",function(t){("MSPointerDown"!=t.type||r(t.originalEvent))&&(w="MSPointerDown"==t.type||"pointerdown"==t.type?t:t.originalEvent.touches[0],v=Date.now(),y=v-(g.last||v),g.el=e("tagName"in w.target?w.target:w.target.parentNode),a&&clearTimeout(a),g.x1=w.pageX,g.y1=w.pageY,y>0&&250>=y&&(g.isDoubleTap=!0),g.last=v,p=setTimeout(n,s),!c||"MSPointerDown"!=t.type&&"pointerdown"!=t.type&&"touchstart"!=t.type||c.addPointer(t.originalEvent.pointerId))}).on("touchmove MSPointerMove pointermove",function(e){("MSPointerMove"!=e.type||r(e.originalEvent))&&(w="MSPointerMove"==e.type||"pointermove"==e.type?e:e.originalEvent.touches[0],o(),g.x2=w.pageX,g.y2=w.pageY,f+=Math.abs(g.x1-g.x2),d+=Math.abs(g.y1-g.y2))}).on("touchend MSPointerUp pointerup",function(n){("MSPointerUp"!=n.type||r(n.originalEvent))&&(o(),g.x2&&Math.abs(g.x1-g.x2)>30||g.y2&&Math.abs(g.y1-g.y2)>30?u=setTimeout(function(){void 0!==g.el&&(g.el.trigger("swipe"),g.el.trigger("swipe"+t(g.x1,g.x2,g.y1,g.y2))),g={}},0):"last"in g&&(isNaN(f)||30>f&&30>d?l=setTimeout(function(){var t=e.Event("tap");t.cancelTouch=i,void 0!==g.el&&g.el.trigger(t),g.isDoubleTap?(void 0!==g.el&&g.el.trigger("doubleTap"),g={}):a=setTimeout(function(){a=null,void 0!==g.el&&g.el.trigger("singleTap"),g={}},250)},0):g={},f=d=0))}).on("touchcancel MSPointerCancel",i),e(window).on("scroll",i)}),["swipe","swipeLeft","swipeRight","swipeUp","swipeDown","doubleTap","tap","singleTap","longTap"].forEach(function(t){e.fn[t]=function(n){return e(this).on(t,n)}})}}(jQuery);<commit_msg>UIkit 2.26.2<commit_after>/*! UIkit 2.26.2 | http://www.getuikit.com | (c) 2014 YOOtheme | MIT License */
!function(e){function t(e,t,n,o){return Math.abs(e-t)>=Math.abs(n-o)?e-t>0?"Left":"Right":n-o>0?"Up":"Down"}function n(){p=null,g.last&&(void 0!==g.el&&g.el.trigger("longTap"),g={})}function o(){p&&clearTimeout(p),p=null}function i(){a&&clearTimeout(a),l&&clearTimeout(l),u&&clearTimeout(u),p&&clearTimeout(p),a=l=u=p=null,g={}}function r(e){return e.pointerType==e.MSPOINTER_TYPE_TOUCH&&e.isPrimary}if(!e.fn.swipeLeft){var a,l,u,p,c,g={},s=750;e(function(){var v,y,w,f=0,d=0;"MSGesture"in window&&(c=new MSGesture,c.target=document.body),e(document).on("MSGestureEnd gestureend",function(e){var t=e.originalEvent.velocityX>1?"Right":e.originalEvent.velocityX<-1?"Left":e.originalEvent.velocityY>1?"Down":e.originalEvent.velocityY<-1?"Up":null;t&&void 0!==g.el&&(g.el.trigger("swipe"),g.el.trigger("swipe"+t))}).on("touchstart MSPointerDown pointerdown",function(t){("MSPointerDown"!=t.type||r(t.originalEvent))&&(w="MSPointerDown"==t.type||"pointerdown"==t.type?t:t.originalEvent.touches[0],v=Date.now(),y=v-(g.last||v),g.el=e("tagName"in w.target?w.target:w.target.parentNode),a&&clearTimeout(a),g.x1=w.pageX,g.y1=w.pageY,y>0&&250>=y&&(g.isDoubleTap=!0),g.last=v,p=setTimeout(n,s),!c||"MSPointerDown"!=t.type&&"pointerdown"!=t.type&&"touchstart"!=t.type||c.addPointer(t.originalEvent.pointerId))}).on("touchmove MSPointerMove pointermove",function(e){("MSPointerMove"!=e.type||r(e.originalEvent))&&(w="MSPointerMove"==e.type||"pointermove"==e.type?e:e.originalEvent.touches[0],o(),g.x2=w.pageX,g.y2=w.pageY,f+=Math.abs(g.x1-g.x2),d+=Math.abs(g.y1-g.y2))}).on("touchend MSPointerUp pointerup",function(n){("MSPointerUp"!=n.type||r(n.originalEvent))&&(o(),g.x2&&Math.abs(g.x1-g.x2)>30||g.y2&&Math.abs(g.y1-g.y2)>30?u=setTimeout(function(){void 0!==g.el&&(g.el.trigger("swipe"),g.el.trigger("swipe"+t(g.x1,g.x2,g.y1,g.y2))),g={}},0):"last"in g&&(isNaN(f)||30>f&&30>d?l=setTimeout(function(){var t=e.Event("tap");t.cancelTouch=i,void 0!==g.el&&g.el.trigger(t),g.isDoubleTap?(void 0!==g.el&&g.el.trigger("doubleTap"),g={}):a=setTimeout(function(){a=null,void 0!==g.el&&g.el.trigger("singleTap"),g={}},250)},0):g={},f=d=0))}).on("touchcancel MSPointerCancel",i),e(window).on("scroll",i)}),["swipe","swipeLeft","swipeRight","swipeUp","swipeDown","doubleTap","tap","singleTap","longTap"].forEach(function(t){e.fn[t]=function(n){return e(this).on(t,n)}})}}(jQuery);
<|endoftext|>


<commit_before>var THREE = require('three'),
    shaders = require('./shaders'),
    texture = THREE.ImageUtils.loadTexture('/textures/planet.png'),
    geometry = new THREE.SphereGeometry(1000, 128, 128),
    materials = {},
    atmosphereGeometry = geometry.clone(),
    atmosphereMaterial;

module.exports = Planet;

function Planet(name, colour, camera) {
  if (!atmosphereMaterial) {
    atmosphereMaterial = generateAtmosphereMaterial(camera);
  }

  var pivot = new THREE.Object3D(),
      mesh = new THREE.Mesh(geometry, selectMaterial(colour)),
      atmosphereMesh = new THREE.Mesh(atmosphereGeometry, atmosphereMaterial);

  atmosphereMesh.scale.multiplyScalar(1.05);

  pivot.add(mesh);
  pivot.add(atmosphereMesh);

  this.mesh = mesh;
  this.pivot = pivot;
}

function selectMaterial(colour) {
  if (materials[colour]) {
    return materials[colour];
}
  materials[colour] = generateMaterial(colour);
  return materials[colour];
}

function generateMaterial(color) {
  return new THREE.MeshPhongMaterial({
    color: color,
    map: texture
  });
}

function generateAtmosphereMaterial (camera) {
  return new THREE.ShaderMaterial({
    uniforms: {
      c: { type: "f", value: 0.5 },
      p: { type: "f", value: 1 },
      alpha: { type: "f", value: 0.4 },
      glowColor: { type: "c", value: new THREE.Color(0x72A7E5) },
      viewVector: { type: "v3", value: camera.position }
    },
    vertexShader: shaders.glowVert,
    fragmentShader: shaders.glowFrag,
    side: THREE.FrontSide,
    blending: THREE.AdditiveBlending,
    transparent: true
  });
}<commit_msg>Increase the colour saturation of the planet<commit_after>var THREE = require('three'),
    shaders = require('./shaders'),
    texture = THREE.ImageUtils.loadTexture('/textures/planet.png'),
    geometry = new THREE.SphereGeometry(1000, 128, 128),
    materials = {},
    atmosphereGeometry = geometry.clone(),
    atmosphereMaterial;

module.exports = Planet;

function Planet(name, colour, camera) {
  if (!atmosphereMaterial) {
    atmosphereMaterial = generateAtmosphereMaterial(camera);
  }

  var pivot = new THREE.Object3D(),
      mesh = new THREE.Mesh(geometry, selectMaterial(colour)),
      atmosphereMesh = new THREE.Mesh(atmosphereGeometry, atmosphereMaterial);

  atmosphereMesh.scale.multiplyScalar(1.05);

  pivot.add(mesh);
  pivot.add(atmosphereMesh);

  this.mesh = mesh;
  this.pivot = pivot;
}

function selectMaterial(colour) {
  if (materials[colour]) {
    return materials[colour];
  }
  materials[colour] = generateMaterial(colour);
  return materials[colour];
}

function generateMaterial(colour) {
  colour = new THREE.Color(colour);
  var hsl = colour.getHSL();
  colour.setHSL(hsl.h, 1, hsl.l);
  return new THREE.MeshPhongMaterial({
    color: colour,
    map: texture
  });
}

function generateAtmosphereMaterial (camera) {
  return new THREE.ShaderMaterial({
    uniforms: {
      c: { type: "f", value: 0.5 },
      p: { type: "f", value: 1 },
      alpha: { type: "f", value: 0.4 },
      glowColor: { type: "c", value: new THREE.Color(0x72A7E5) },
      viewVector: { type: "v3", value: camera.position }
    },
    vertexShader: shaders.glowVert,
    fragmentShader: shaders.glowFrag,
    side: THREE.FrontSide,
    blending: THREE.AdditiveBlending,
    transparent: true
  });
}<|endoftext|>


<commit_before>/**
 * Pad the string at the start.
 *
 * @method padStart
 * @for utils.Pad
 * @param {string} n The string to pad
 * @param {number} width The width to which the string needs to be padded
 * @param {string} [z='0'] The character to pad the string with
 * @return {string} The padded string
 */
export function padStart(n, width, z = '0') {
  let nstr = String(n)
  return nstr.length >= width ? nstr : new Array(width - nstr.length + 1).join(z) + nstr
}

export default padStart

/**
 * Pad the string at the end.
 *
 * @method padEnd
 * @for utils.Pad
 * @param {string} n The string to pad
 * @param {number} width The width to which the string needs to be padded
 * @param {string} [z='0'] The character to pad the string with
 * @return {string} The padded string
 */
export function padEnd(n, width, z = '0') {
  let nstr = String(n)
  return nstr.length >= width ? nstr : nstr + new Array(width - nstr.length + 1).join(z)
}

/*
 * Template literal function for padding the string at the start.
 *
 * padStartTpl`${1}:${2}`(2) === '01:02'
 * padStartTpl(2)`${1}:${2}` === '01:02'
 */
export function padStartTpl(strings, ...values) {
  if (Array.isArray(strings)) {
    return (width, z) =>
      processTpl(strings, values, width, z, padStart)
  }

  let width = strings
  let z     = values[0]

  return (strings, ...values) =>
    processTpl(strings, values, width, z, padStart)
}

export { padStartTpl as padTpl }

/*
 * Template literal function for padding the string at the end.
 *
 * padEndTpl`${1}:${2}`(2) === '10:20'
 * padEndTpl(2)`${1}:${2}` === '10:20'
 */
export function padEndTpl(strings, ...values) {
  if (Array.isArray(strings)) {
    return (width, z) =>
      processTpl(strings, values, width, z, padEnd)
  }

  let width = strings
  let z     = values[0]

  return (strings, ...values) =>
    processTpl(strings, values, width, z, padEnd)
}

function processTpl(strings, values, width, z, pad) {
  let reducer = (str, v, i) =>
    str + strings[i] + pad(v, width, z)
  return values.reduce(reducer, '')
}
<commit_msg>Deduplicate pad logic<commit_after>function pad(nstr, width, z) {
  return new Array(width - nstr.length + 1).join(z)
}

/**
 * Pad the string at the start.
 *
 * @method padStart
 * @for utils.Pad
 * @param {string} n The string to pad
 * @param {number} width The width to which the string needs to be padded
 * @param {string} [z='0'] The character to pad the string with
 * @return {string} The padded string
 */
export function padStart(n, width, z = '0') {
  let nstr = String(n)

  if (nstr.length >= width) {
    return nstr
  }

  return pad(nstr, width, z) + nstr
}

export default padStart

/**
 * Pad the string at the end.
 *
 * @method padEnd
 * @for utils.Pad
 * @param {string} n The string to pad
 * @param {number} width The width to which the string needs to be padded
 * @param {string} [z='0'] The character to pad the string with
 * @return {string} The padded string
 */
export function padEnd(n, width, z = '0') {
  let nstr = String(n)

  if (nstr.length >= width) {
    return nstr
  }

  return nstr + pad(nstr, width, z)
}

/*
 * Template literal function for padding the string at the start.
 *
 * padStartTpl`${1}:${2}`(2) === '01:02'
 * padStartTpl(2)`${1}:${2}` === '01:02'
 */
export function padStartTpl(strings, ...values) {
  if (Array.isArray(strings)) {
    return (width, z) =>
      processTpl(strings, values, width, z, padStart)
  }

  let width = strings
  let z     = values[0]

  return (strings, ...values) =>
    processTpl(strings, values, width, z, padStart)
}

export { padStartTpl as padTpl }

/*
 * Template literal function for padding the string at the end.
 *
 * padEndTpl`${1}:${2}`(2) === '10:20'
 * padEndTpl(2)`${1}:${2}` === '10:20'
 */
export function padEndTpl(strings, ...values) {
  if (Array.isArray(strings)) {
    return (width, z) =>
      processTpl(strings, values, width, z, padEnd)
  }

  let width = strings
  let z     = values[0]

  return (strings, ...values) =>
    processTpl(strings, values, width, z, padEnd)
}

function processTpl(strings, values, width, z, pad) {
  let reducer = (str, v, i) =>
    str + strings[i] + pad(v, width, z)
  return values.reduce(reducer, '')
}
<|endoftext|>


<commit_before>'use strict';
const debug = require('debug')('twitterstreamingbot');
const TelegramBot = require('node-telegram-bot-api');
const fs = require('fs');
const Twitter = require('twitter');
const crontab = require('node-crontab');

const Utils = require('./lib/utils');

let isLocal = process.env.LOCAL === 'true';
debug('isLocal =', isLocal);

let TOKEN = process.env.TELEGRAM_TOKEN;
let options = {
    webHook: {
        port: process.env.PORT || 5000
    }
};

if (isLocal) {
    options.key = `${__dirname}/private.key`;  // Path to file with PEM private key
    options.cert = `${__dirname}/cert.pem`;  // Path to file with PEM certificate
    options.request = {proxy: 'http://127.0.0.1:9090'}
}

let botname = '@bot_name';
let url = process.env.APP_URL;
const tgbot = new TelegramBot(TOKEN, options);
let list = process.env.TWITTER_LIST, twitter_id = process.env.TWITTER_ID, chat_id = process.env.OWNER_ID;

if (isLocal) {
    tgbot.setWebHook(`${url}/bot${TOKEN}`, {
        certificate: `${__dirname}/cert.pem`,
    });
} else {
    tgbot.setWebHook(`${url}/bot${TOKEN}`);
}

let twitter_options = {
    consumer_key: process.env.TWITTER_CONSUMER_KEY,
    consumer_secret: process.env.TWITTER_CONSUMER_SECRET,
    access_token_key: process.env.TWITTER_ACCESS_TOKEN_KEY,
    access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET
};

if (isLocal) {
    twitter_options.request_options = {proxy: 'http://127.0.0.1:9090'}
}

const client = new Twitter(twitter_options);

tgbot.getMe().then(async (msg) => {
    botname = '@' + msg.username;
    let members = Utils.LoadJSON('members.json');
    if (!members || members.length === 0) {
        members = await client.get('lists/members', {slug: list, owner_screen_name: twitter_id, count: 5000});
        if (members.users) {
            members = members.users.map((user) => user.id);
            Utils.SaveJSON('members.json', members)
        }
    }

    client.stream('statuses/filter', {follow: members.join(',')}, (stream) => {
        stream.on('data', async (tweet) => {
            let tweet_id = tweet.id_str;
            let user_name = tweet.user.name;
            let user_tid = tweet.user.screen_name;
            let retweeted_status = tweet.retweeted_status;
            let is_reply = tweet.in_reply_to_screen_name !== null;
            let text = tweet.text;
            let medias = tweet.entities.media;
            if (!retweeted_status && !is_reply && !!medias) {
                let msg_id = -1;
                if (medias.length > 1) {
                    debug(JSON.stringify(medias));
                    for (let media of medias) {
                        if (media.type === 'photo') {
                            msg_id = await tgbot.sendPhoto(chat_id, media.media_url_https);
                            msg_id = msg_id.message_id;
                        }
                    }
                }
                debug(`${user_name}(@${user_tid})\n${text}`);
                let options = {parse_mode: 'HTML'};
                if (msg_id !== -1) {
                    options.reply_to_message_id = msg_id;
                }
                if (!text.includes('https://t.co/')) {
                    options.disable_web_page_preview = true;
                }
                await tgbot.sendMessage(chat_id, `${text}\n\n${user_name}(<a href="https://twitter.com/${user_tid}">@${user_tid}</a>)\n<a href="http://twitter.com/${user_tid}/status/${tweet_id}">${tweet_id}</a>`, options);
            }
        });

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

// reset at 00:00 every day
crontab.scheduleJob('0 0 * * *', () => {
    Utils.SaveJSON('members.json', [])
});

process.on('unhandledRejection', (reason) => {
    console.error(reason);
    //   process.exit(1);
});

require('heroku-self-ping')(url, {interval: 25 * 60 * 1000});
<commit_msg>update<commit_after>'use strict';
const debug = require('debug')('twitterstreamingbot');
const TelegramBot = require('node-telegram-bot-api');
const fs = require('fs');
const Twitter = require('twitter');
const crontab = require('node-crontab');

const Utils = require('./lib/utils');

let isLocal = process.env.LOCAL === 'true';
debug('isLocal =', isLocal);

let TOKEN = process.env.TELEGRAM_TOKEN;
let options = {
    webHook: {
        port: process.env.PORT || 5000
    }
};

if (isLocal) {
    options.key = `${__dirname}/private.key`;  // Path to file with PEM private key
    options.cert = `${__dirname}/cert.pem`;  // Path to file with PEM certificate
    options.request = {proxy: 'http://127.0.0.1:9090'}
}

let botname = '@bot_name';
let url = process.env.APP_URL;
const tgbot = new TelegramBot(TOKEN, options);
let list = process.env.TWITTER_LIST, twitter_id = process.env.TWITTER_ID, chat_id = process.env.OWNER_ID;

if (isLocal) {
    tgbot.setWebHook(`${url}/bot${TOKEN}`, {
        certificate: `${__dirname}/cert.pem`,
    });
} else {
    tgbot.setWebHook(`${url}/bot${TOKEN}`);
}

let twitter_options = {
    consumer_key: process.env.TWITTER_CONSUMER_KEY,
    consumer_secret: process.env.TWITTER_CONSUMER_SECRET,
    access_token_key: process.env.TWITTER_ACCESS_TOKEN_KEY,
    access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET
};

if (isLocal) {
    twitter_options.request_options = {proxy: 'http://127.0.0.1:9090'}
}

const client = new Twitter(twitter_options);

tgbot.getMe().then(async (msg) => {
    botname = '@' + msg.username;
    let members = Utils.LoadJSON('members.json');
    if (!members || members.length === 0) {
        members = await client.get('lists/members', {slug: list, owner_screen_name: twitter_id, count: 5000});
        if (members.users) {
            members = members.users.map((user) => user.id);
            Utils.SaveJSON('members.json', members)
        }
    }

    client.stream('statuses/filter', {follow: members.join(',')}, (stream) => {
        stream.on('data', async (tweet) => {
            let tweet_id = tweet.id_str;
            let user_name = tweet.user.name;
            let user_tid = tweet.user.screen_name;
            let retweeted_status = tweet.retweeted_status;
            let is_reply = tweet.in_reply_to_screen_name !== null;
            let text = tweet.text;
            let medias = tweet.entities.media;
            if (!retweeted_status && !is_reply && !!medias) {
                let msg_id = -1;
                if (medias.length > 0) {
                    debug(JSON.stringify(medias));
                    for (let media of medias) {
                        if (media.type === 'photo') {
                            msg_id = await tgbot.sendPhoto(chat_id, media.media_url_https);
                            msg_id = msg_id.message_id;
                        }
                    }
                }
                debug(`${user_name}(@${user_tid})\n${text}`);
                let options = {parse_mode: 'HTML'};
                if (msg_id !== -1) {
                    options.reply_to_message_id = msg_id;
                }
                if (!text.includes('https://t.co/')) {
                    options.disable_web_page_preview = true;
                }
                await tgbot.sendMessage(chat_id, `${text}\n\n${user_name}(<a href="https://twitter.com/${user_tid}">@${user_tid}</a>)\n<a href="http://twitter.com/${user_tid}/status/${tweet_id}">${tweet_id}</a>`, options);
            }
        });

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

// reset at 00:00 every day
crontab.scheduleJob('0 0 * * *', () => {
    Utils.SaveJSON('members.json', [])
});

process.on('unhandledRejection', (reason) => {
    console.error(reason);
    //   process.exit(1);
});

require('heroku-self-ping')(url, {interval: 25 * 60 * 1000});
<|endoftext|>


<commit_before>/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

var path = require('path');
var fs = require('fs');
var loader = require('./vs/loader');

function uriFromPath(_path) {
	var pathName = path.resolve(_path).replace(/\\/g, '/');

	if (pathName.length > 0 && pathName.charAt(0) !== '/') {
		pathName = '/' + pathName;
	}

	return encodeURI('file://' + pathName);
}

function readFile(file) {
	return new Promise(function (resolve, reject) {
		fs.readFile(file, 'utf8', function (err, data) {
			if (err) {
				reject(err);
				return;
			}
			resolve(data);
		});
	});
}

const writeFile = (file, content) => new Promise((c, e) => fs.writeFile(file, content, 'utf8', err => err ? e(err) : c()));

var rawNlsConfig = process.env['VSCODE_NLS_CONFIG'];
var nlsConfig = rawNlsConfig ? JSON.parse(rawNlsConfig) : { availableLanguages: {} };

// We have a special location of the nls files. They come from a language pack
if (nlsConfig._resolvedLanguagePackCoreLocation) {
	let bundles = Object.create(null);
	nlsConfig.loadBundle = function (bundle, language, cb) {
		let result = bundles[bundle];
		if (result) {
			cb(undefined, result);
			return;
		}
		let bundleFile = path.join(nlsConfig._resolvedLanguagePackCoreLocation, bundle.replace(/\//g, '!') + '.nls.json');
		readFile(bundleFile).then(function (content) {
			let json = JSON.parse(content);
			bundles[bundle] = json;
			cb(undefined, json);
		}).catch((error) => {
			try {
				if (nlsConfig._corruptedFile) {
					writeFile(nlsConfig._corruptedFile, 'corrupted').catch(function (error) { console.error(error); });
				}
			} finally {
				cb(error, undefined);
			}
		});
	};
}

loader.config({
	baseUrl: uriFromPath(__dirname),
	catchError: true,
	nodeRequire: require,
	nodeMain: __filename,
	'vs/nls': nlsConfig,
	nodeCachedDataDir: process.env['VSCODE_NODE_CACHED_DATA_DIR_' + process.pid]
});

loader.define('fs', ['original-fs'], function (originalFS) { return originalFS; }); // replace the patched electron fs with the original node fs for all AMD code

if (nlsConfig.pseudo) {
	loader(['vs/nls'], function (nlsPlugin) {
		nlsPlugin.setPseudoTranslation(nlsConfig.pseudo);
	});
}

exports.bootstrap = function (entrypoint, onLoad, onError) {
	if (!entrypoint) {
		return;
	}

	onLoad = onLoad || function () { };
	onError = onError || function (err) { console.error(err); };

	loader([entrypoint], onLoad, onError);
};
<commit_msg>Fixes #54550: Define `fs` as `original-fs` only when running in Electron<commit_after>/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

var path = require('path');
var fs = require('fs');
var loader = require('./vs/loader');

function uriFromPath(_path) {
	var pathName = path.resolve(_path).replace(/\\/g, '/');

	if (pathName.length > 0 && pathName.charAt(0) !== '/') {
		pathName = '/' + pathName;
	}

	return encodeURI('file://' + pathName);
}

function readFile(file) {
	return new Promise(function (resolve, reject) {
		fs.readFile(file, 'utf8', function (err, data) {
			if (err) {
				reject(err);
				return;
			}
			resolve(data);
		});
	});
}

const writeFile = (file, content) => new Promise((c, e) => fs.writeFile(file, content, 'utf8', err => err ? e(err) : c()));

var rawNlsConfig = process.env['VSCODE_NLS_CONFIG'];
var nlsConfig = rawNlsConfig ? JSON.parse(rawNlsConfig) : { availableLanguages: {} };

// We have a special location of the nls files. They come from a language pack
if (nlsConfig._resolvedLanguagePackCoreLocation) {
	let bundles = Object.create(null);
	nlsConfig.loadBundle = function (bundle, language, cb) {
		let result = bundles[bundle];
		if (result) {
			cb(undefined, result);
			return;
		}
		let bundleFile = path.join(nlsConfig._resolvedLanguagePackCoreLocation, bundle.replace(/\//g, '!') + '.nls.json');
		readFile(bundleFile).then(function (content) {
			let json = JSON.parse(content);
			bundles[bundle] = json;
			cb(undefined, json);
		}).catch((error) => {
			try {
				if (nlsConfig._corruptedFile) {
					writeFile(nlsConfig._corruptedFile, 'corrupted').catch(function (error) { console.error(error); });
				}
			} finally {
				cb(error, undefined);
			}
		});
	};
}

loader.config({
	baseUrl: uriFromPath(__dirname),
	catchError: true,
	nodeRequire: require,
	nodeMain: __filename,
	'vs/nls': nlsConfig,
	nodeCachedDataDir: process.env['VSCODE_NODE_CACHED_DATA_DIR_' + process.pid]
});

if (process.env['ELECTRON_RUN_AS_NODE'] || process.versions.electron) {
	// running in Electron
	loader.define('fs', ['original-fs'], function (originalFS) { return originalFS; }); // replace the patched electron fs with the original node fs for all AMD code
}

if (nlsConfig.pseudo) {
	loader(['vs/nls'], function (nlsPlugin) {
		nlsPlugin.setPseudoTranslation(nlsConfig.pseudo);
	});
}

exports.bootstrap = function (entrypoint, onLoad, onError) {
	if (!entrypoint) {
		return;
	}

	onLoad = onLoad || function () { };
	onError = onError || function (err) { console.error(err); };

	loader([entrypoint], onLoad, onError);
};
<|endoftext|>


<commit_before>/*eslint-env jquery, node*/

/*globals distNameIsAvailable modelUpdateNode RegisterModelObserver selSetCenterPanelTitle ace sUTL lsUTLLibDists NotifyErrorMessage modelGetLibDist modelGetNodeFullNameById modelGetLib modelSetLib*/

var setupEditor = function(aId)
{
    var editor = ace.edit(aId);
    editor.setTheme("ace/theme/monokai");
    editor.getSession().setMode("ace/mode/json");
    editor.getSession().setTabSize(2);
    editor.getSession().setUseSoftTabs(true);
    editor.setFontSize(14);
    return editor;
};

var EditorIsInvalid = function(aEditor, aPrefix)
{
    var retval = null;

    var ljsonString = aEditor.getValue();
    try
    {
        JSON.parse(ljsonString);
    }
    catch (err)
    {
        retval = err.message;
    }

	if (retval)
		NotifyErrorMessage(aPrefix + ": " + retval);

    return retval;
};

var GetRequires = function(aStrRequires)
{
	var retval = null;

	if (aStrRequires)
	{
	    try
	    {
	    	retval = aStrRequires.split(" ");
	    }
	    catch (err)
	    {
	    	console.log(err);
	    }
	}

	return retval;
};

//var ValidateJson = function(aEditor, aMessageSelector)
//{
//    $(aMessageSelector).text(EditorIsInvalid(aEditor));
//};
//
var _selectedNode = null;
var _edSource = null;
var _edTransform = null;
var _edResult = null;
var _dontUpdate = false;

var _sourceTimeout = null;
var _transformTimeout = null;

var declUpdateDeclDetail = function(aNode)
{
  var lsrcgen = null;
  if (aNode.srcgen)
  	lsrcgen = aNode.srcgen;
  $('#lbsrcgen').attr('href', lsrcgen);

  var SetTitle = function(aNode)
  {
  	selSetCenterPanelTitle(aNode.name, aNode.state);
  };

  SetTitle(aNode);
};

var declUpdateResult = function(aNode)
{
    if (!(EditorIsInvalid(_edTransform, "Transform") || EditorIsInvalid(_edSource, "Source")))
    {
		NotifyErrorMessage("");

        var lsourceJson = JSON.parse(_edSource.getValue());
        var ltransform = JSON.parse(_edTransform.getValue());
        var lrequires = GetRequires($('#vbDeclRequires').textbox('getValue'));
        var ldists = modelGetLibDist(_selectedNode.id);
		var lfullname = modelGetNodeFullNameById(_selectedNode.id);

        try
        {
            var lresult = null;

            var ldecl = {
            	"transform-t": ltransform,
            	"name": lfullname
            };

            if (lrequires)
            {
            	ldecl["requires"] = lrequires;
            }

            var llib = modelGetLib(_selectedNode.id);

            var clresult;
            if (llib)
            {
            	clresult = {"lib": llib, "noset": true};
        	}
            else
            {
	            clresult = sUTL.compilelib([ldecl], [ldists], false);
            }

            if (!clresult)
            {
              lresult = "** Can't load libs **";
            }
            else if ("fail" in clresult)
            {
              lresult = clresult["fail"];
            }
            else
            {
            	if (!clresult["noset"])
	            	modelSetLib(_selectedNode.id, clresult["lib"]);
                lresult = sUTL.evaluate(lsourceJson, ltransform, clresult["lib"] || {}, 0);
            }

            _edResult.setValue(JSON.stringify(lresult, null, 2));
            _edResult.gotoLine(0);

			NotifyErrorMessage("");
        }
        catch (e)
        {
            console.log(e);
            var lerrorMessage = "Result Exception: " + e.message;
			NotifyErrorMessage(lerrorMessage);
            _edResult.setValue(lerrorMessage);
            _edResult.gotoLine(0);
        }
    }
};

var declSetSelected = function(aNode)
{
  if (aNode && !(_selectedNode && (aNode.id === _selectedNode.id)))
  {
	  _selectedNode = aNode;

  	  NotifyErrorMessage("");

  	  if (!_edSource )
  	  {
		  _edSource = setupEditor("edSource");
		  _edTransform = setupEditor("edTransform");
		  _edResult = setupEditor("edResult");
	  }

	  _dontUpdate = true;
	  if (_edSource.getValue() !== aNode.source)
	  {
	  	if (aNode.source)
		  _edSource.setValue(aNode.source);
		else
		  _edSource.setValue("");
		_edSource.gotoLine(0);
	  }
	  if (_edTransform.getValue() !== aNode.transform)
	  {
	  	if (aNode.transform)
		  _edTransform.setValue(aNode.transform);
		else
		  _edTransform.setValue("");
		_edTransform.gotoLine(0);
	  }

	  _edResult.setValue("");
	  declUpdateResult();
	  _dontUpdate = false;

	  _edSource.getSession().on('change', function()
	  {
	  	if (!_dontUpdate)
	  	{
			if (_sourceTimeout)
				clearTimeout(_sourceTimeout);

		    _sourceTimeout = setTimeout(
		    	function() {
		    		modelUpdateNode(_selectedNode.id, {"source": _edSource.getValue(), "state": "updated"});
		    		_sourceTimeout = null;
		    	},
		    	1000
		    );

		    declUpdateResult();
	    }
	  });

	  _edTransform.getSession().on('change', function() {
	  	if (!_dontUpdate)
	  	{
		    //ValidateJson(_edTransform, "#transformmsg");
			if (_transformTimeout)
				clearTimeout(_transformTimeout);

		    _transformTimeout = setTimeout(
		    	function() {
					modelUpdateNode(_selectedNode.id, {"transform": _edTransform.getValue(), "state": "updated"});
					_transformTimeout = null;
		    	},
		    	1000
		    );
		    declUpdateResult();
	    }
	  });

	  $('#sbDeclPublished').switchbutton({
	      checked: _selectedNode.published,
	      onChange: function(checked){
	        modelUpdateNode(_selectedNode.id, {"published": checked, "state": "updated"});
	      }
	  });

	  var IsValid = function(value)
	  {
	  	return value.length > 0;
	  };

	  $.extend(
	      $.fn.validatebox.defaults.rules, {
	      distname: {
	          validator: function(value, params){
	          	return IsValid(value);
	          },
	          message: 'Please provide a declaration name.'
	      }
	  });

	  $('#vbDeclName').textbox({
	      value: _selectedNode.name,
	  });

	  $('#vbDeclName').textbox({
	      onChange: function(value, params){
		    modelSetLib(_selectedNode.id, null);
		    var lvalue = $('#vbDeclName').textbox('getValue');
	      	if (IsValid(lvalue))
	      	{
		        modelUpdateNode(_selectedNode.id, {"name": lvalue, "state": "updated"});
	        }
	      }
	  });

	  var lrequires = _selectedNode.requires;
	  if (!lrequires)
	  	lrequires = null;
	  $('#vbDeclRequires').textbox({
	      value: lrequires,
	  });

	  $('#vbDeclRequires').textbox({
	      onChange: function(value, params){
		    modelSetLib(_selectedNode.id, null);
		    var lvalue = $('#vbDeclRequires').textbox('getValue');
		    modelUpdateNode(_selectedNode.id, {"requires": lvalue, "state": "updated"});
		    declUpdateResult();
	      }
	  });

	  $('#accBody').accordion("resize");

	  _dontUpdate = true;
	  declUpdateResult();
	  _dontUpdate = false;
  }
  else
  {
	  _selectedNode = aNode;
  }

  declUpdateDeclDetail(aNode);
};

var declSetUnselected = function(aNode)
{
  if (aNode && _selectedNode && aNode.id !== _selectedNode.id)
  {
  	if (_sourceTimeout)
  	{
		modelUpdateNode(_selectedNode.id, {"source": _edSource.getValue(), "state": "updated"});
		_sourceTimeout = null;
  	}

  	if (_transformTimeout)
  	{
		modelUpdateNode(_selectedNode.id, {"transform": _edTransform.getValue(), "state": "updated"});
		_transformTimeout = null;
  	}
  }
}

RegisterModelObserver("decldetail", function(aNotifyObj)
{
	if (aNotifyObj)
	{
		if (aNotifyObj.type === "treereplace")
		{
			_selectedNode = null;
			_edSource = null;
			_edTransform = null;
			_edResult = null;
			_dontUpdate = false;
		}
		else if (aNotifyObj.type === "nodeupdated")
		{
			if (aNotifyObj.node.type === "decl")
			{
				declUpdateDeclDetail(aNotifyObj.node);
			}
		}
		else if (aNotifyObj.type === "nodeselected")
		{
			if (aNotifyObj.node.type === "decl")
			{
				declSetSelected(aNotifyObj.node);
			}
			else
			{
				declSetSelected(null);
			}
		}
		else if (aNotifyObj.type === "nodeunselected")
		{
			if (aNotifyObj.node.type === "decl")
			{
				declSetUnselected(aNotifyObj.node);
			}
		}
		else if (aNotifyObj.type === "libupdated")
		{
			if (aNotifyObj.node.type === "decl" && aNotifyObj.node.id === _selectedNode.id)
			{
				declUpdateResult();
			}
		}
	}
});
<commit_msg>Put result update into save timer<commit_after>/*eslint-env jquery, node*/

/*globals distNameIsAvailable modelUpdateNode RegisterModelObserver selSetCenterPanelTitle ace sUTL lsUTLLibDists NotifyErrorMessage modelGetLibDist modelGetNodeFullNameById modelGetLib modelSetLib*/

var setupEditor = function(aId)
{
    var editor = ace.edit(aId);
    editor.setTheme("ace/theme/monokai");
    editor.getSession().setMode("ace/mode/json");
    editor.getSession().setTabSize(2);
    editor.getSession().setUseSoftTabs(true);
    editor.setFontSize(14);
    return editor;
};

var EditorIsInvalid = function(aEditor, aPrefix)
{
    var retval = null;

    var ljsonString = aEditor.getValue();
    try
    {
        JSON.parse(ljsonString);
    }
    catch (err)
    {
        retval = err.message;
    }

	if (retval)
		NotifyErrorMessage(aPrefix + ": " + retval);

    return retval;
};

var GetRequires = function(aStrRequires)
{
	var retval = null;

	if (aStrRequires)
	{
	    try
	    {
	    	retval = aStrRequires.split(" ");
	    }
	    catch (err)
	    {
	    	console.log(err);
	    }
	}

	return retval;
};

//var ValidateJson = function(aEditor, aMessageSelector)
//{
//    $(aMessageSelector).text(EditorIsInvalid(aEditor));
//};
//
var _selectedNode = null;
var _edSource = null;
var _edTransform = null;
var _edResult = null;
var _dontUpdate = false;

var _sourceTimeout = null;
var _transformTimeout = null;

var declUpdateDeclDetail = function(aNode)
{
  var lsrcgen = null;
  if (aNode.srcgen)
  	lsrcgen = aNode.srcgen;
  $('#lbsrcgen').attr('href', lsrcgen);

  var SetTitle = function(aNode)
  {
  	selSetCenterPanelTitle(aNode.name, aNode.state);
  };

  SetTitle(aNode);
};

var declUpdateResult = function(aNode)
{
    if (!(EditorIsInvalid(_edTransform, "Transform") || EditorIsInvalid(_edSource, "Source")))
    {
		NotifyErrorMessage("");

        var lsourceJson = JSON.parse(_edSource.getValue());
        var ltransform = JSON.parse(_edTransform.getValue());
        var lrequires = GetRequires($('#vbDeclRequires').textbox('getValue'));
        var ldists = modelGetLibDist(_selectedNode.id);
		var lfullname = modelGetNodeFullNameById(_selectedNode.id);

        try
        {
            var lresult = null;

            var ldecl = {
            	"transform-t": ltransform,
            	"name": lfullname
            };

            if (lrequires)
            {
            	ldecl["requires"] = lrequires;
            }

            var llib = modelGetLib(_selectedNode.id);

            var clresult;
            if (llib)
            {
            	clresult = {"lib": llib, "noset": true};
        	}
            else
            {
	            clresult = sUTL.compilelib([ldecl], [ldists], false);
            }

            if (!clresult)
            {
              lresult = "** Can't load libs **";
            }
            else if ("fail" in clresult)
            {
              lresult = clresult["fail"];
            }
            else
            {
            	if (!clresult["noset"])
	            	modelSetLib(_selectedNode.id, clresult["lib"]);
                lresult = sUTL.evaluate(lsourceJson, ltransform, clresult["lib"] || {}, 0);
            }

            _edResult.setValue(JSON.stringify(lresult, null, 2));
            _edResult.gotoLine(0);

			NotifyErrorMessage("");
        }
        catch (e)
        {
            console.log(e);
            var lerrorMessage = "Result Exception: " + e.message;
			NotifyErrorMessage(lerrorMessage);
            _edResult.setValue(lerrorMessage);
            _edResult.gotoLine(0);
        }
    }
};

var declSetSelected = function(aNode)
{
  if (aNode && !(_selectedNode && (aNode.id === _selectedNode.id)))
  {
	  _selectedNode = aNode;

  	  NotifyErrorMessage("");

  	  if (!_edSource )
  	  {
		  _edSource = setupEditor("edSource");
		  _edTransform = setupEditor("edTransform");
		  _edResult = setupEditor("edResult");
	  }

	  _dontUpdate = true;
	  if (_edSource.getValue() !== aNode.source)
	  {
	  	if (aNode.source)
		  _edSource.setValue(aNode.source);
		else
		  _edSource.setValue("");
		_edSource.gotoLine(0);
	  }
	  if (_edTransform.getValue() !== aNode.transform)
	  {
	  	if (aNode.transform)
		  _edTransform.setValue(aNode.transform);
		else
		  _edTransform.setValue("");
		_edTransform.gotoLine(0);
	  }

	  _edResult.setValue("");
	  declUpdateResult();
	  _dontUpdate = false;

	  _edSource.getSession().on('change', function()
	  {
	  	if (!_dontUpdate)
	  	{
			if (_sourceTimeout)
				clearTimeout(_sourceTimeout);

		    _sourceTimeout = setTimeout(
		    	function() {
		    		modelUpdateNode(_selectedNode.id, {"source": _edSource.getValue(), "state": "updated"});
		    		_sourceTimeout = null;
				    declUpdateResult();
		    	},
		    	1000
		    );
	    }
	  });

	  _edTransform.getSession().on('change', function() {
	  	if (!_dontUpdate)
	  	{
		    //ValidateJson(_edTransform, "#transformmsg");
			if (_transformTimeout)
				clearTimeout(_transformTimeout);

		    _transformTimeout = setTimeout(
		    	function() {
					modelUpdateNode(_selectedNode.id, {"transform": _edTransform.getValue(), "state": "updated"});
					_transformTimeout = null;
				    declUpdateResult();
		    	},
		    	500
		    );
	    }
	  });

	  $('#sbDeclPublished').switchbutton({
	      checked: _selectedNode.published,
	      onChange: function(checked){
	        modelUpdateNode(_selectedNode.id, {"published": checked, "state": "updated"});
	      }
	  });

	  var IsValid = function(value)
	  {
	  	return value.length > 0;
	  };

	  $.extend(
	      $.fn.validatebox.defaults.rules, {
	      distname: {
	          validator: function(value, params){
	          	return IsValid(value);
	          },
	          message: 'Please provide a declaration name.'
	      }
	  });

	  $('#vbDeclName').textbox({
	      value: _selectedNode.name,
	  });

	  $('#vbDeclName').textbox({
	      onChange: function(value, params){
		    modelSetLib(_selectedNode.id, null);
		    var lvalue = $('#vbDeclName').textbox('getValue');
	      	if (IsValid(lvalue))
	      	{
		        modelUpdateNode(_selectedNode.id, {"name": lvalue, "state": "updated"});
	        }
	      }
	  });

	  var lrequires = _selectedNode.requires;
	  if (!lrequires)
	  	lrequires = null;
	  $('#vbDeclRequires').textbox({
	      value: lrequires,
	  });

	  $('#vbDeclRequires').textbox({
	      onChange: function(value, params){
		    modelSetLib(_selectedNode.id, null);
		    var lvalue = $('#vbDeclRequires').textbox('getValue');
		    modelUpdateNode(_selectedNode.id, {"requires": lvalue, "state": "updated"});
		    declUpdateResult();
	      }
	  });

	  $('#accBody').accordion("resize");

	  _dontUpdate = true;
	  declUpdateResult();
	  _dontUpdate = false;
  }
  else
  {
	  _selectedNode = aNode;
  }

  declUpdateDeclDetail(aNode);
};

var declSetUnselected = function(aNode)
{
  if (aNode && _selectedNode && aNode.id !== _selectedNode.id)
  {
  	if (_sourceTimeout)
  	{
		modelUpdateNode(_selectedNode.id, {"source": _edSource.getValue(), "state": "updated"});
		_sourceTimeout = null;
  	}

  	if (_transformTimeout)
  	{
		modelUpdateNode(_selectedNode.id, {"transform": _edTransform.getValue(), "state": "updated"});
		_transformTimeout = null;
  	}
  }
}

RegisterModelObserver("decldetail", function(aNotifyObj)
{
	if (aNotifyObj)
	{
		if (aNotifyObj.type === "treereplace")
		{
			_selectedNode = null;
			_edSource = null;
			_edTransform = null;
			_edResult = null;
			_dontUpdate = false;
		}
		else if (aNotifyObj.type === "nodeupdated")
		{
			if (aNotifyObj.node.type === "decl")
			{
				declUpdateDeclDetail(aNotifyObj.node);
			}
		}
		else if (aNotifyObj.type === "nodeselected")
		{
			if (aNotifyObj.node.type === "decl")
			{
				declSetSelected(aNotifyObj.node);
			}
			else
			{
				declSetSelected(null);
			}
		}
		else if (aNotifyObj.type === "nodeunselected")
		{
			if (aNotifyObj.node.type === "decl")
			{
				declSetUnselected(aNotifyObj.node);
			}
		}
		else if (aNotifyObj.type === "libupdated")
		{
			if (aNotifyObj.node.type === "decl" && aNotifyObj.node.id === _selectedNode.id)
			{
				declUpdateResult();
			}
		}
	}
});
<|endoftext|>


<commit_before>
// create the game
var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update });

// variables

var planet;
var player1;
var player2;
var cursors;

// loads before game starts
function preload() {

    game.load.image('planet', 'assets/sprites/shmup-ship2.png');
    game.load.image('player', 'assets/sprites/blue_ball.png');

} // preload()

// runs when game starts
function create() {

    // set background colour
    game.stage.backgroundColor = '#001255';

    // add the planet to the game and anchor it
    planet = game.add.sprite(game.world.centerX, game.world.centerY, 'planet');
    planet.anchor.setTo(0.5, 0.5);

    // add physics to the planet
    game.physics.arcade.enable(planet);

    // add player one to the game
    player1 = game.add.sprite(400, 300, 'player');
    player1.anchor.setTo(0.5);      // anchor player
    player1.pivot.x = 240;          // set the players pivot. (how far from it's position it is)

    // add player two to the game
    player2 = game.add.sprite(400, 300, 'player');
    player2.anchor.setTo(0.5);      // anchor player
    player2.pivot.x = -240;         // set the players pivot. (how far from it's position it is)

    // sets up game to read key presses
    //cursors = game.input.keyboard.createCursorKeys();

} // create()

// runs every frame
function update() {

    // keep player 1 locked to planet
    player1.x = planet.x;
    player1.y = planet.y;

    // keep player 2 locked to planet
    player2.x = planet.x;
    player2.y = planet.y;

    // planets x and y velocity to 0
    planet.body.velocity.x = 0;
    planet.body.velocity.y = 0;

    // rotate the players
    player1.rotation += 0.02;
    player2.rotation += 0.02;

} // update()
<commit_msg>Can now move player 2 closer and farther from planet<commit_after>
// create the game
var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update });

// variables

var planet;
var player1;
var player2;
var cursors;

// loads before game starts
function preload() {

    game.load.image('planet', 'assets/sprites/shmup-ship2.png');
    game.load.image('player', 'assets/sprites/blue_ball.png');

} // preload()

// runs when game starts
function create() {

    // set background colour
    game.stage.backgroundColor = '#001255';

    // add the planet to the game and anchor it
    planet = game.add.sprite(game.world.centerX, game.world.centerY, 'planet');
    planet.anchor.setTo(0.5, 0.5);

    // add physics to the planet
    game.physics.arcade.enable(planet);

    // add player one to the game
    player1 = game.add.sprite(400, 300, 'player');
    player1.anchor.setTo(0.5);      // anchor player
    player1.pivot.x = 240;          // set the players pivot. (how far from it's position it is)

    // add player two to the game
    player2 = game.add.sprite(400, 300, 'player');
    player2.anchor.setTo(0.5);      // anchor player
    player2.pivot.x = -240;         // set the players pivot. (how far from it's position it is)

    // sets up game to read key presses
    cursors = game.input.keyboard.createCursorKeys();

} // create()

// runs every frame
function update() {

    // check for key presses
    checkForKeyPress();

    // keep player 1 locked to planet
    player1.x = planet.x;
    player1.y = planet.y;

    // keep player 2 locked to planet
    player2.x = planet.x;
    player2.y = planet.y;

    // planets x and y velocity to 0
    planet.body.velocity.x = 0;
    planet.body.velocity.y = 0;

    // rotate the players
    player1.rotation += 0.002;
    player2.rotation += 0.002;

} // update()

function checkForKeyPress(){

    if (cursors.up.isDown)
    {
        // move the player away from the planet
        player2.pivot.x -= 0.5;
    }
    else if (cursors.down.isDown)
    {
        // move the player towards the planet
        player2.pivot.x += 0.5;
    }

} // checkForKeyPress()
<|endoftext|>


<commit_before>
/**
 * Module dependencies.
 */

var express = require('express')
  , routes = require('./routes')
  , http = require('http')
  , path = require('path')
  , projectMetainfo = require('./routes/input/projectMetainfo')
  , paths = require('./custom_modules/paths')
  , projectStatus = require('./routes/projectStatus')
  , datastoreModule = require('./custom_modules/datastoreModule')
  //, swagger = require('swagger-node-express')
  , envInformationModule = require('./custom_modules/envInformationModule')
  , models = require('./custom_modules/models');
 // , validator = require("validator")
  //, mongodb = require('mongodb');

var app = express();

// all environments
app.set('port', process.env.PORT || paths.getApplicationPort());
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.set('input', __dirname + '/public/input');
console.log("dirname : " + __dirname);
//app.use(validator);
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(paths.locationOfFolderWithProjects()));
GLOBAL.PROGRESS_STATUS = [];

app.configure(function(){
  envInformationModule.setHostname(GLOBAL);
  console.log('set for all environments');
  app.use(express.errorHandler());
});

/*
app.configure('development', function(){
  GLOBAL.serverPath = 'localhost';
  console.log('set for development');
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.configure('production', function(){
  envInformationModule.setHostname(GLOBAL);
 //console.log('sp : ' + GLOBAL.serverPath);
  console.log('set for production');
  app.use(express.errorHandler());
});*/

//app.get('/', routes.index);
app.get('/projectStatus/:id', projectStatus.status );
app.get('/projectStatus', projectStatus.allStatuses);
app.get('/', projectMetainfo.form );
app.post('/', projectMetainfo.submit(app.get('/')));

var server = http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

var io = require ('socket.io').listen(server);
io.set('log level', 1);

io.sockets.on('connection', function(socket){
	socket.on('getStatus', function(data){
		var record = datastoreModule.getRecordForProjectName(data.nameOfGitRepo);
		socket.emit('statusChanged', record );
	});
});

//swagger.addModels(models);

<commit_msg>models module not needed<commit_after>
/**
 * Module dependencies.
 */

var express = require('express')
  , routes = require('./routes')
  , http = require('http')
  , path = require('path')
  , projectMetainfo = require('./routes/input/projectMetainfo')
  , paths = require('./custom_modules/paths')
  , projectStatus = require('./routes/projectStatus')
  , datastoreModule = require('./custom_modules/datastoreModule')
  //, swagger = require('swagger-node-express')
  , envInformationModule = require('./custom_modules/envInformationModule')
  //, models = require('./custom_modules/models');
 // , validator = require("validator")
  //, mongodb = require('mongodb');

var app = express();

// all environments
app.set('port', process.env.PORT || paths.getApplicationPort());
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.set('input', __dirname + '/public/input');
console.log("dirname : " + __dirname);
//app.use(validator);
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(paths.locationOfFolderWithProjects()));
GLOBAL.PROGRESS_STATUS = [];

app.configure(function(){
  envInformationModule.setHostname(GLOBAL);
  console.log('set for all environments');
  app.use(express.errorHandler());
});

/*
app.configure('development', function(){
  GLOBAL.serverPath = 'localhost';
  console.log('set for development');
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.configure('production', function(){
  envInformationModule.setHostname(GLOBAL);
 //console.log('sp : ' + GLOBAL.serverPath);
  console.log('set for production');
  app.use(express.errorHandler());
});*/

//app.get('/', routes.index);
app.get('/projectStatus/:id', projectStatus.status );
app.get('/projectStatus', projectStatus.allStatuses);
app.get('/', projectMetainfo.form );
app.post('/', projectMetainfo.submit(app.get('/')));

var server = http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

var io = require ('socket.io').listen(server);
io.set('log level', 1);

io.sockets.on('connection', function(socket){
	socket.on('getStatus', function(data){
		var record = datastoreModule.getRecordForProjectName(data.nameOfGitRepo);
		socket.emit('statusChanged', record );
	});
});

//swagger.addModels(models);

<|endoftext|>


<commit_before>"use strict";

/**
 * @constructor
 *
 * @param {BusConnector} bus
 */
function MouseAdapter(bus, screen_container)
{
    /** @const */
    var SPEED_FACTOR = 0.15;

    var left_down = false,
        right_down = false,
        middle_down = false,

        last_x = 0,
        last_y = 0,

        mouse = this;

    // set by controller
    this.enabled = false;

    // set by emulator
    this.emu_enabled = true;

    this.bus = bus;

    this.bus.register("mouse-enable", function(enabled)
    {
        this.enabled = enabled;
    }, this);

    this.destroy = function()
    {
        if(typeof window === "undefined")
        {
            return;
        }
        window.removeEventListener("touchstart", touch_start_handler, false);
        window.removeEventListener("touchend", touch_end_handler, false);
        window.removeEventListener("touchmove", mousemove_handler, false);
        window.removeEventListener("mousemove", mousemove_handler, false);
        window.removeEventListener("mousedown", mousedown_handler, false);
        window.removeEventListener("mouseup", mouseup_handler, false);
        window.removeEventListener("DOMMouseScroll", mousewheel_handler, false);
        window.removeEventListener("mousewheel", mousewheel_handler, { passive: false });
    };

    this.init = function()
    {
        if(typeof window === "undefined")
        {
            return;
        }
        this.destroy();

        window.addEventListener("touchstart", touch_start_handler, false);
        window.addEventListener("touchend", touch_end_handler, false);
        window.addEventListener("touchmove", mousemove_handler, false);
        window.addEventListener("mousemove", mousemove_handler, false);
        window.addEventListener("mousedown", mousedown_handler, false);
        window.addEventListener("mouseup", mouseup_handler, false);
        window.addEventListener("DOMMouseScroll", mousewheel_handler, false);
        window.addEventListener("mousewheel", mousewheel_handler, { passive: false });
    };
    this.init();

    function is_child(child, parent)
    {
        while(child.parentNode)
        {
            if(child === parent)
            {
                return true;
            }
            child = child.parentNode;
        }

        return false;
    }

    function may_handle(e)
    {
        if(!mouse.enabled || !mouse.emu_enabled)
        {
            return false;
        }

        const MOVE_MOUSE_WHEN_OVER_SCREEN_ONLY = true;

        if(MOVE_MOUSE_WHEN_OVER_SCREEN_ONLY)
        {
            var parent = screen_container || document.body;
            return document.pointerLockElement || is_child(e.target, parent);
        }
        else
        {
            if(e.type === "mousemove" || e.type === "touchmove")
            {
                return true;
            }

            if(e.type === "mousewheel" || e.type === "DOMMouseScroll")
            {
                return is_child(e.target, parent);
            }

            return !e.target || e.target.nodeName !== "INPUT" && e.target.nodeName !== "TEXTAREA";
        }
    }

    function touch_start_handler(e)
    {
        if(may_handle(e))
        {
            var touches = e["changedTouches"];

            if(touches && touches.length)
            {
                var touch = touches[touches.length - 1];
                last_x = touch.clientX;
                last_y = touch.clientY;
            }
        }
    }

    function touch_end_handler(e)
    {
        if(left_down || middle_down || right_down)
        {
            mouse.bus.send("mouse-click", [false, false, false]);
            left_down = middle_down = right_down = false;
        }
    }

    function mousemove_handler(e)
    {
        if(!mouse.bus)
        {
            return;
        }

        if(!may_handle(e))
        {
            return;
        }

        var delta_x = 0;
        var delta_y = 0;

        var touches = e["changedTouches"];

        if(touches)
        {
            if(touches.length)
            {
                var touch = touches[touches.length - 1];
                delta_x = touch.clientX - last_x;
                delta_y = touch.clientY - last_y;

                last_x = touch.clientX;
                last_y = touch.clientY;

                e.preventDefault();
            }
        }
        else
        {
            if(typeof e["movementX"] === "number")
            {
                delta_x = e["movementX"];
                delta_y = e["movementY"];
            }
            else if(typeof e["webkitMovementX"] === "number")
            {
                delta_x = e["webkitMovementX"];
                delta_y = e["webkitMovementY"];
            }
            else if(typeof e["mozMovementX"] === "number")
            {
                delta_x = e["mozMovementX"];
                delta_y = e["mozMovementY"];
            }
            else
            {
                // Fallback for other browsers?
                delta_x = e.clientX - last_x;
                delta_y = e.clientY - last_y;

                last_x = e.clientX;
                last_y = e.clientY;
            }
        }

        if(SPEED_FACTOR !== 1)
        {
            delta_x = delta_x * SPEED_FACTOR;
            delta_y = delta_y * SPEED_FACTOR;
        }

        //if(Math.abs(delta_x) > 100 || Math.abs(delta_y) > 100)
        //{
        //    // Large mouse delta, drop?
        //}

        delta_y = -delta_y;

        mouse.bus.send("mouse-delta", [delta_x, delta_y]);

        let absolute_x = e.pageX - screen_container.offsetLeft;
        let absolute_y = e.pageY - screen_container.offsetTop;
        mouse.bus.send("mouse-absolute", [
            absolute_x, absolute_y, screen_container.offsetWidth, screen_container.offsetHeight]);
    }

    function mousedown_handler(e)
    {
        if(may_handle(e))
        {
            click_event(e, true);
        }
    }

    function mouseup_handler(e)
    {
        if(may_handle(e))
        {
            click_event(e, false);
        }
    }

    function click_event(e, down)
    {
        if(!mouse.bus)
        {
            return;
        }

        if(e.which === 1)
        {
            left_down = down;
        }
        else if(e.which === 2)
        {
            middle_down = down;
        }
        else if(e.which === 3)
        {
            right_down = down;
        }
        else
        {
            dbg_log("Unknown event.which: " + e.which);
        }
        mouse.bus.send("mouse-click", [left_down, middle_down, right_down]);
    }

    function mousewheel_handler(e)
    {
        if(!may_handle(e))
        {
            return;
        }

        var delta_x = e.wheelDelta || -e.detail;
        var delta_y = 0;

        if(delta_x < 0)
        {
            delta_x = -1;
        }
        else if(delta_x > 0)
        {
            delta_x = 1;
        }

        mouse.bus.send("mouse-wheel", [delta_x, delta_y]);
        e.preventDefault();
    }
}
<commit_msg>Mouse: Fix case when no screen container is given<commit_after>"use strict";

/**
 * @constructor
 *
 * @param {BusConnector} bus
 */
function MouseAdapter(bus, screen_container)
{
    /** @const */
    var SPEED_FACTOR = 0.15;

    var left_down = false,
        right_down = false,
        middle_down = false,

        last_x = 0,
        last_y = 0,

        mouse = this;

    // set by controller
    this.enabled = false;

    // set by emulator
    this.emu_enabled = true;

    this.bus = bus;

    this.bus.register("mouse-enable", function(enabled)
    {
        this.enabled = enabled;
    }, this);

    this.destroy = function()
    {
        if(typeof window === "undefined")
        {
            return;
        }
        window.removeEventListener("touchstart", touch_start_handler, false);
        window.removeEventListener("touchend", touch_end_handler, false);
        window.removeEventListener("touchmove", mousemove_handler, false);
        window.removeEventListener("mousemove", mousemove_handler, false);
        window.removeEventListener("mousedown", mousedown_handler, false);
        window.removeEventListener("mouseup", mouseup_handler, false);
        window.removeEventListener("DOMMouseScroll", mousewheel_handler, false);
        window.removeEventListener("mousewheel", mousewheel_handler, { passive: false });
    };

    this.init = function()
    {
        if(typeof window === "undefined")
        {
            return;
        }
        this.destroy();

        window.addEventListener("touchstart", touch_start_handler, false);
        window.addEventListener("touchend", touch_end_handler, false);
        window.addEventListener("touchmove", mousemove_handler, false);
        window.addEventListener("mousemove", mousemove_handler, false);
        window.addEventListener("mousedown", mousedown_handler, false);
        window.addEventListener("mouseup", mouseup_handler, false);
        window.addEventListener("DOMMouseScroll", mousewheel_handler, false);
        window.addEventListener("mousewheel", mousewheel_handler, { passive: false });
    };
    this.init();

    function is_child(child, parent)
    {
        while(child.parentNode)
        {
            if(child === parent)
            {
                return true;
            }
            child = child.parentNode;
        }

        return false;
    }

    function may_handle(e)
    {
        if(!mouse.enabled || !mouse.emu_enabled)
        {
            return false;
        }

        const MOVE_MOUSE_WHEN_OVER_SCREEN_ONLY = true;

        if(MOVE_MOUSE_WHEN_OVER_SCREEN_ONLY)
        {
            var parent = screen_container || document.body;
            return document.pointerLockElement || is_child(e.target, parent);
        }
        else
        {
            if(e.type === "mousemove" || e.type === "touchmove")
            {
                return true;
            }

            if(e.type === "mousewheel" || e.type === "DOMMouseScroll")
            {
                return is_child(e.target, parent);
            }

            return !e.target || e.target.nodeName !== "INPUT" && e.target.nodeName !== "TEXTAREA";
        }
    }

    function touch_start_handler(e)
    {
        if(may_handle(e))
        {
            var touches = e["changedTouches"];

            if(touches && touches.length)
            {
                var touch = touches[touches.length - 1];
                last_x = touch.clientX;
                last_y = touch.clientY;
            }
        }
    }

    function touch_end_handler(e)
    {
        if(left_down || middle_down || right_down)
        {
            mouse.bus.send("mouse-click", [false, false, false]);
            left_down = middle_down = right_down = false;
        }
    }

    function mousemove_handler(e)
    {
        if(!mouse.bus)
        {
            return;
        }

        if(!may_handle(e))
        {
            return;
        }

        var delta_x = 0;
        var delta_y = 0;

        var touches = e["changedTouches"];

        if(touches)
        {
            if(touches.length)
            {
                var touch = touches[touches.length - 1];
                delta_x = touch.clientX - last_x;
                delta_y = touch.clientY - last_y;

                last_x = touch.clientX;
                last_y = touch.clientY;

                e.preventDefault();
            }
        }
        else
        {
            if(typeof e["movementX"] === "number")
            {
                delta_x = e["movementX"];
                delta_y = e["movementY"];
            }
            else if(typeof e["webkitMovementX"] === "number")
            {
                delta_x = e["webkitMovementX"];
                delta_y = e["webkitMovementY"];
            }
            else if(typeof e["mozMovementX"] === "number")
            {
                delta_x = e["mozMovementX"];
                delta_y = e["mozMovementY"];
            }
            else
            {
                // Fallback for other browsers?
                delta_x = e.clientX - last_x;
                delta_y = e.clientY - last_y;

                last_x = e.clientX;
                last_y = e.clientY;
            }
        }

        if(SPEED_FACTOR !== 1)
        {
            delta_x = delta_x * SPEED_FACTOR;
            delta_y = delta_y * SPEED_FACTOR;
        }

        //if(Math.abs(delta_x) > 100 || Math.abs(delta_y) > 100)
        //{
        //    // Large mouse delta, drop?
        //}

        delta_y = -delta_y;

        mouse.bus.send("mouse-delta", [delta_x, delta_y]);

        if(screen_container)
        {
            let absolute_x = e.pageX - screen_container.offsetLeft;
            let absolute_y = e.pageY - screen_container.offsetTop;
            mouse.bus.send("mouse-absolute", [
                absolute_x, absolute_y, screen_container.offsetWidth, screen_container.offsetHeight]);
        }
    }

    function mousedown_handler(e)
    {
        if(may_handle(e))
        {
            click_event(e, true);
        }
    }

    function mouseup_handler(e)
    {
        if(may_handle(e))
        {
            click_event(e, false);
        }
    }

    function click_event(e, down)
    {
        if(!mouse.bus)
        {
            return;
        }

        if(e.which === 1)
        {
            left_down = down;
        }
        else if(e.which === 2)
        {
            middle_down = down;
        }
        else if(e.which === 3)
        {
            right_down = down;
        }
        else
        {
            dbg_log("Unknown event.which: " + e.which);
        }
        mouse.bus.send("mouse-click", [left_down, middle_down, right_down]);
    }

    function mousewheel_handler(e)
    {
        if(!may_handle(e))
        {
            return;
        }

        var delta_x = e.wheelDelta || -e.detail;
        var delta_y = 0;

        if(delta_x < 0)
        {
            delta_x = -1;
        }
        else if(delta_x > 0)
        {
            delta_x = 1;
        }

        mouse.bus.send("mouse-wheel", [delta_x, delta_y]);
        e.preventDefault();
    }
}
<|endoftext|>