<commit_before>const Discord = require("discord.js");
const bot = new Discord.Client();
const token = "MzI3MTIyNTk3OTAyODExMTM3.DCwwQQ.BIxxQQEfezftpzywZLtawDeMoKU";

var fortunes = ["It is certain", "It is decidedly so", "Without a doubt", "Yes definitely", "You may rely of it", "As I see it, yes", "Most likely", "Outlook good", "Yes", "Signs point to yes", "Reply hazy try again", "Ask again later", "Better not tell you now", "Cannot predict now", "Conentrate and ask again", "Dont count on it", "My reply is no", "My sources say no", "Outlook not so good", "Very doubtful"];

var commands = {
    "help": {
        usage: "<command>",
        description: "Gives you a list of commands you can use",
        process: function(message, args){
            if(args.length === 0){
                var commandKeys = Object.keys(commands);
                var commandList = "";
                for(var i = 0; i < commandKeys.length - 1; i++){
                    commandList += commandKeys[i] + ", ";
                }
                commandList += commandKeys[commandKeys.length - 1];
                message.reply("My current commands are: " + commandList);
                message.channel.send("You can use `!help <command>` to learn more about a command");
            } else{
                for(var i = 0; i < args.length; i++){
                    try{
                        message.channel.send(`\`!${args[i]} ${commands[args[i]].usage}\`: ${commands[args[i]].description}`);
                    } catch(e){
                        message.channel.send(`\`!${args[i]}\`: Not a command`);
                    }
                }
            }
        }
    },
    "bot": {
        usage: "",
        description: "Tells you information about the bot",
        process: function(message, args){
            message.reply("I am a discord bot for didney worl who has an appetite for non-nutritive substances");
        }
    },
    "ping": {
        usage: "",
        description: "Pings the bot",
        process: function(message, args){
            message.reply("Pong :ping_pong:");
        }
    },
    "roll": {
        usage: "<amount>d<sides>",
        description: "Rolls a die",
        process: function(message, args){
            var rolls = [];
            var die = "";
            if(args.length === 0){
                die = "1d6";
                rolls.push(Math.floor(Math.random() * 6 + 1));
            } else{
                var amount = parseInt(args[0].split("d")[0]);
                var sides = parseInt(args[0].split("d")[1]);
                if(!Number.isInteger(amount) || !Number.isInteger(sides)){
                    message.reply("That is not a valid die");
                    return;
                }
                if(amount > 10){
                    message.reply("You cannot roll more than 10 dice at a time");
                    return;
                }
                die = args[0];
                for(var i = 0; i < amount; i++){
                    rolls.push(Math.floor(Math.random() * sides + 1));
                }
            }
            var rollList = "";
            for(var i = 0; i < rolls.length - 1; i++){
                rollList += rolls[i] + ", ";
            }
            rollList += rolls[rolls.length - 1];
            message.reply(`You rolled ${die} and got: ${rollList}`);
        }
    },
    "8ball": {
        usage: "",
        description: "Asks a magic 8ball",
        process: function(message, args){
            message.reply(fortunes[Math.floor(Math.random() * fortunes.length)]);
        }
    },
    "insult": {
        usage: "",
        description: "Call the bot to your voice channel to deliver a special insult",
        process: function(message, args){
            message.reply("There are currently no insults :sob:");
        }
    }
};

var checkForCommand = function(message){
    if(!message.author.bot && message.content.startsWith("!")){
        var args = message.content.substring(1).split(" ");
        var command = args.splice(0, 1);
        try{
            commands[command].process(message, args);
        } catch(e){
            message.reply("Sorry that isn't a command yet :sob:");
            message.channel.send("You can type `!help` to see a list of my commands");
        }
    }
}

bot.on("ready", () => console.log("Bot ready!"));
bot.on("disconnect", () => {
    console.log("Disconnected!");
    process.exit(1);
});
bot.on("guildMemberAdd", member => {
    member.guild.defaultChannel.send(`Welcome to the server, ${member}!`);
    member.guild.defaultChannel.send("You can type `!help` at anytime to see my commands");
});
bot.on("message", message => checkForCommand(message));
bot.on("messageUpdate", (oldMessage, newMessage) => checkForCommand(newMessage));

bot.login(token);<commit_msg>Add insult test and save/recall skeletons<commit_after>const Discord = require("discord.js");
const bot = new Discord.Client();
const token = "MzI3MTIyNTk3OTAyODExMTM3.DCwwQQ.BIxxQQEfezftpzywZLtawDeMoKU";

var fortunes = ["It is certain", "It is decidedly so", "Without a doubt", "Yes definitely", "You may rely of it", "As I see it, yes", "Most likely", "Outlook good", "Yes", "Signs point to yes", "Reply hazy try again", "Ask again later", "Better not tell you now", "Cannot predict now", "Conentrate and ask again", "Dont count on it", "My reply is no", "My sources say no", "Outlook not so good", "Very doubtful"];

var commands = {
    "help": {
        usage: "<command>",
        description: "Gives you a list of commands you can use",
        process: function(message, args){
            if(args.length === 0){
                var commandKeys = Object.keys(commands);
                var commandList = "";
                for(var i = 0; i < commandKeys.length - 1; i++){
                    commandList += commandKeys[i] + ", ";
                }
                commandList += commandKeys[commandKeys.length - 1];
                message.reply("My current commands are: " + commandList);
                message.channel.send("You can use `!help <command>` to learn more about a command");
            } else{
                for(var i = 0; i < args.length; i++){
                    try{
                        message.channel.send(`\`!${args[i]} ${commands[args[i]].usage}\`: ${commands[args[i]].description}`);
                    } catch(e){
                        message.channel.send(`\`!${args[i]}\`: Not a command`);
                    }
                }
            }
        }
    },
    "bot": {
        usage: "",
        description: "Tells you information about the bot",
        process: function(message, args){
            message.reply("I am a discord bot for didney worl who has an appetite for non-nutritive substances");
        }
    },
    "ping": {
        usage: "",
        description: "Pings the bot",
        process: function(message, args){
            message.reply("Pong :ping_pong:");
        }
    },
    "roll": {
        usage: "<amount>d<sides>",
        description: "Rolls a die",
        process: function(message, args){
            var rolls = [];
            var die = "";
            if(args.length === 0){
                die = "1d6";
                rolls.push(Math.floor(Math.random() * 6 + 1));
            } else{
                var amount = parseInt(args[0].split("d")[0]);
                var sides = parseInt(args[0].split("d")[1]);
                if(!Number.isInteger(amount) || !Number.isInteger(sides)){
                    message.reply("That is not a valid die");
                    return;
                }
                if(amount > 10){
                    message.reply("You cannot roll more than 10 dice at a time");
                    return;
                }
                die = args[0];
                for(var i = 0; i < amount; i++){
                    rolls.push(Math.floor(Math.random() * sides + 1));
                }
            }
            var rollList = "";
            for(var i = 0; i < rolls.length - 1; i++){
                rollList += rolls[i] + ", ";
            }
            rollList += rolls[rolls.length - 1];
            message.reply(`You rolled ${die} and got: ${rollList}`);
        }
    },
    "8ball": {
        usage: "",
        description: "Asks a magic 8ball",
        process: function(message, args){
            message.reply(fortunes[Math.floor(Math.random() * fortunes.length)]);
        }
    },
    "insult": {
        usage: "",
        description: "Call the bot to your voice channel to deliver a special insult",
        process: function(message, args){
            message.reply("There are currently no insults :sob:");
            if(!message.guild) return;
            if(message.member.voiceChannel){
                message.member.voiceChannel.join().then(connection =>{
                    message.reply("Connected to the channel");
                }).catch(console.log);
            } else{
                message.reply("You need to join a voice channel first");
            }
        }
    },
    "save": {
        usage: "",
        description: "",
        process: function(message, args){

        }
    },
    "recall": {
        usage: "",
        description: "",
        process: function(message, args){

        }
    }
};

var checkForCommand = function(message){
    if(!message.author.bot && message.content.startsWith("!")){
        var args = message.content.substring(1).split(" ");
        var command = args.splice(0, 1);
        try{
            commands[command].process(message, args);
        } catch(e){
            message.reply("Sorry that isn't a command yet :sob:");
            message.channel.send("You can type `!help` to see a list of my commands");
        }
    }
}

bot.on("ready", () => console.log("Bot ready!"));
bot.on("disconnect", () => {
    console.log("Disconnected!");
    process.exit(1);
});
bot.on("guildMemberAdd", member => {
    member.guild.defaultChannel.send(`Welcome to the server, ${member}!`);
    member.guild.defaultChannel.send("You can type `!help` at anytime to see my commands");
});
bot.on("message", message => checkForCommand(message));
bot.on("messageUpdate", (oldMessage, newMessage) => checkForCommand(newMessage));

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


<commit_before>/*
 Copyright [2016] [Relevance Lab]

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

const logger = require('_pr/logger')(module);
const dateUtil = require('_pr/lib/utils/dateUtil');
const monitorsModel = require('_pr/model/monitors');
const appConfig = require('_pr/config');

var monitorsService = module.exports = {};

monitorsService.checkIfMonitorExists = function (monitorId, callback) {
    monitorsModel.getById(monitorId, function (err, monitor) {
        if (err) {
            var err = new Error('Internal server error');
            err.status = 500;
            return callback(err);
        } else if (!monitor) {
            var err = new Error('Monitor not found');
            err.status = 404;
            return callback(err);
        } else {
            return callback(null, monitor);
        }
    });
};

monitorsService.responseFormatter = function (monitor) {
    var formatted = {};
    switch (monitor.type) {
        case 'sensu':
        case 'Sensu':
            formatted._id = monitor._id;
            formatted.type = monitor.type;
            if (monitor.organization.length) {
                formatted.organization = {
                    id: monitor.organization[0].rowid,
                    name: monitor.organization[0].orgname
                };
            }
            formatted.parameters = monitor.parameters;
            if (formatted.parameters.transportProtocolParameters['password']) {
                delete formatted.parameters.transportProtocolParameters['password'];
            }
            break;
    }
    return formatted;
};

monitorsService.createMonitor = function (monitor, callback) {

    switch (monitor.type) {
        case 'sensu':
        case 'Sensu':
            monitorsModel.createNew(monitor, function (err, monitor) {
                //@TODO To be generalized
                if (err && err.name === 'ValidationError') {
                    var err = new Error('Bad Request');
                    err.status = 400;
                    callback(err);
                } else if (err) {
                    var err = new Error('Internal Server Error');
                    err.status = 500;
                    callback(err);
                } else {
                    callback(null, monitor);
                }
            });
            break;
        default:
            var err = new Error('Bad request');
            err.status = 400;
            return callback(err);
            break;
    }

};

monitorsService.updateMonitor = function updateMonitor(monitorId, updateFields, callback) {
    switch (updateFields.type) {
        case 'sensu':
        case 'Sensu':
            monitorsModel.updateMonitors(monitorId, updateFields, function (err, monitor) {
                //@TODO To be generalized
                if (err && err.name === 'ValidationError') {
                    var err = new Error('Bad Request');
                    err.status = 400;
                    callback(err);
                } else if (err) {
                    var err = new Error('Internal Server Error');
                    err.status = 500;
                    callback(err);
                } else {
                    callback(null, monitor);
                }
            });
            break;
        default:
            var err = new Error('Bad request');
            err.status = 400;
            return callback(err);
            break;
    }
};

monitorsService.deleteMonitors = function (monitorId, callback) {
    monitorsModel.deleteMonitors(monitorId, function (err, monitor) {
        if (err) {
            var err = new Error('Internal server error');
            err.status = 500;
            return callback(err);
        } else if (!monitor) {
            var err = new Error('Monitor not found');
            err.status = 404;
            return callback(err);
        } else {
            // @TODO response to be decided
            return callback(null, {});
        }
    });
};

monitorsService.getMonitors = function (query, callback) {
    var params = {};
    logger.debug('get monitors');
    if ('filterBy' in query) {
        params = monitorsService.parseFilterBy(query.filterBy);
    }
    monitorsModel.getMonitors(params, function (err, monitors) {
        if (err) {
            logger.error(err);
            var err = new Error('Internal Server Error');
            err.status = 500;
            callback(err);
        } else {
            var res = [];
            if (monitors.length > 0) {
                for (i = 0; i < monitors.length; i++) {
                    res[i] = monitorsService.responseFormatter(monitors[i]);
                }
            }
            callback(null, res);
        }
    });
};

monitorsService.getMonitor = function (monitorId, callback) {
    monitorsModel.getMonitor(monitorId, function (err, monitor) {
        if (err) {
            var err = new Error('Internal Server Error');
            err.status = 500;
            return callback(err);
        } else if (!monitor) {
            var err = new Error('Monitor not found');
            err.status = 404;
            return callback(err);
        } else if (monitor) {
            monitor = monitorsService.responseFormatter(monitor);
            callback(null, monitor);
        }
    });
};

// @TODO Query builder to be made generic
monitorsService.parseFilterBy = function (filterByString) {
    var filterQuery = {};

    var filters = filterByString.split('+');
    for (var i = 0; i < filters.length; i++) {
        var filter = filters[i].split(':');
        var filterQueryValues = filter[1].split(",");

        filterQuery[filter[0]] = {'$in': filterQueryValues};
    }

    return filterQuery;
};
<commit_msg>changed function name<commit_after>/*
 Copyright [2016] [Relevance Lab]

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

const logger = require('_pr/logger')(module);
const dateUtil = require('_pr/lib/utils/dateUtil');
const monitorsModel = require('_pr/model/monitors');
const appConfig = require('_pr/config');

var monitorsService = module.exports = {};

monitorsService.checkIfMonitorExists = function (monitorId, callback) {
    monitorsModel.getById(monitorId, function (err, monitor) {
        if (err) {
            var err = new Error('Internal server error');
            err.status = 500;
            return callback(err);
        } else if (!monitor) {
            var err = new Error('Monitor not found');
            err.status = 404;
            return callback(err);
        } else {
            return callback(null, monitor);
        }
    });
};

monitorsService.formatResponse = function (monitor) {
    var formatted = {};
    switch (monitor.type) {
        case 'sensu':
        case 'Sensu':
            formatted._id = monitor._id;
            formatted.type = monitor.type;
            if (monitor.organization.length) {
                formatted.organization = {
                    id: monitor.organization[0].rowid,
                    name: monitor.organization[0].orgname
                };
            }
            formatted.parameters = monitor.parameters;
            if (formatted.parameters.transportProtocolParameters['password']) {
                delete formatted.parameters.transportProtocolParameters['password'];
            }
            break;
    }
    return formatted;
};

monitorsService.createMonitor = function (monitor, callback) {

    switch (monitor.type) {
        case 'sensu':
        case 'Sensu':
            monitorsModel.createNew(monitor, function (err, monitor) {
                //@TODO To be generalized
                if (err && err.name === 'ValidationError') {
                    var err = new Error('Bad Request');
                    err.status = 400;
                    callback(err);
                } else if (err) {
                    var err = new Error('Internal Server Error');
                    err.status = 500;
                    callback(err);
                } else {
                    callback(null, monitor);
                }
            });
            break;
        default:
            var err = new Error('Bad request');
            err.status = 400;
            return callback(err);
            break;
    }

};

monitorsService.updateMonitor = function updateMonitor(monitorId, updateFields, callback) {
    switch (updateFields.type) {
        case 'sensu':
        case 'Sensu':
            monitorsModel.updateMonitors(monitorId, updateFields, function (err, monitor) {
                //@TODO To be generalized
                if (err && err.name === 'ValidationError') {
                    var err = new Error('Bad Request');
                    err.status = 400;
                    callback(err);
                } else if (err) {
                    var err = new Error('Internal Server Error');
                    err.status = 500;
                    callback(err);
                } else {
                    callback(null, monitor);
                }
            });
            break;
        default:
            var err = new Error('Bad request');
            err.status = 400;
            return callback(err);
            break;
    }
};

monitorsService.deleteMonitors = function (monitorId, callback) {
    monitorsModel.deleteMonitors(monitorId, function (err, monitor) {
        if (err) {
            var err = new Error('Internal server error');
            err.status = 500;
            return callback(err);
        } else if (!monitor) {
            var err = new Error('Monitor not found');
            err.status = 404;
            return callback(err);
        } else {
            // @TODO response to be decided
            return callback(null, {});
        }
    });
};

monitorsService.getMonitors = function (query, callback) {
    var params = {};
    logger.debug('get monitors');
    if ('filterBy' in query) {
        params = monitorsService.parseFilterBy(query.filterBy);
    }
    monitorsModel.getMonitors(params, function (err, monitors) {
        if (err) {
            logger.error(err);
            var err = new Error('Internal Server Error');
            err.status = 500;
            callback(err);
        } else {
            var res = [];
            if (monitors.length > 0) {
                for (i = 0; i < monitors.length; i++) {
                    res[i] = monitorsService.formatResponse(monitors[i]);
                }
            }
            callback(null, res);
        }
    });
};

monitorsService.getMonitor = function (monitorId, callback) {
    monitorsModel.getMonitor(monitorId, function (err, monitor) {
        if (err) {
            var err = new Error('Internal Server Error');
            err.status = 500;
            return callback(err);
        } else if (!monitor) {
            var err = new Error('Monitor not found');
            err.status = 404;
            return callback(err);
        } else if (monitor) {
            monitor = monitorsService.formatResponse(monitor);
            callback(null, monitor);
        }
    });
};

// @TODO Query builder to be made generic
monitorsService.parseFilterBy = function (filterByString) {
    var filterQuery = {};

    var filters = filterByString.split('+');
    for (var i = 0; i < filters.length; i++) {
        var filter = filters[i].split(':');
        var filterQueryValues = filter[1].split(",");

        filterQuery[filter[0]] = {'$in': filterQueryValues};
    }

    return filterQuery;
};
<|endoftext|>


<commit_before>$(document).ready(function() {
	var upButton = '';
	var downButton = '';

	var trashButton = '';
	var addButton = '';

	var controlGroup = '
 \

 \
		<input type="text" class="url" placeholder="www.google.com"> \
		<input type="text" class="input-mini abbreviation" placeholder="Gl"> \

 \

';

	chrome.storage.sync.get('sites', function(items) {
		sites = items['sites'];

		if (sites.length == 0) {
			$("#sites").prepend(controlGroup);
		}

		sites = sites.reverse();

		for (var i = 0; i < sites.length; i++) {
			var newControlGroup = controlGroup;
			var site = sites[i];

			newControlGroup = $(newControlGroup);
			newControlGroup.find('input.url').val(site.url);
			newControlGroup.find('input.abbreviation').val(site.abbreviation);

			$("#sites").prepend(newControlGroup);
		}

		updateAllButtons();

		$(".container").removeClass("hidden");
	});

	function getButtons(up, down) {
		var result = '

';

		if (up) {
			result += upButton;
		}

		if (down) {
			result += downButton;
		}

		result += '

';

		return result;
	}

	updateAllButtons();

	function updateAllButtons() {
		updateControlGroupAddRemoveButtons();
		updateControlGroupSortingButtons();
	}

	function updateControlGroupAddRemoveButtons() {
		var controlsCount = $('.controls').size();

		$('.controls').each(function(index) {
			$(this).children('.btn.add').remove();
			$(this).children('.btn.remove').remove();

			if (index != controlsCount - 1 && controlsCount != 2) {
				$(this).append(trashButton);
			}

			if (index == controlsCount - 2) {
				$(this).append(addButton);
			}
		});

		$('.btn.remove').off().on('click', removeControlGroup);
		$('.btn.add').off().on('click', addControlGroup);
	}

	function removeControlGroup() {
		parent = $(this).parents('.control-group');
		parent.remove();

		updateAllButtons();
	}

	function addControlGroup() {
		parent = $(this).parents('.control-group');

		parent.after(controlGroup);

		updateAllButtons();
	}

	function updateControlGroupSortingButtons() {
		var controlsCount = $('.controls').size();

		$('.controls').each(function(index) {
			$(this).children('.btn-toolbar').remove();

			if (index == controlsCount - 1 || controlsCount == 2) {
				return;
			}

			if (index == 0) {
				$(this).append(getButtons(false, true));
			} else if (index == controlsCount - 2) {
				$(this).append(getButtons(true, false));
			} else {
				$(this).append(getButtons(true, true));
			}
		});

		$('.btn.up').off().on('click', moveControlGroupUp);
		$('.btn.down').off().on('click', moveControlGroupDown);
	}

	function moveControlGroupUp() {
		parent = $(this).parents('.control-group');

		var previous = parent.prev();

		parent.remove();
		previous.before(parent);

		updateAllButtons();
	}

	function moveControlGroupDown() {
		parent = $(this).parents('.control-group');

		var next = parent.next();

		parent.remove();
		next.after(parent);

		updateAllButtons();
	}

	function getFaviconColor(url, callback) {
		var image = new Image();
		image.onload = function() {
			var context = $("canvas")[0].getContext('2d');
			context.drawImage(image, 0, 0);

			var average = [0, 0, 0, 0];

			for (var x = 0; x < image.width; x++) {
				for (var y = 0; y < image.height; y++) {
					data = context.getImageData(x, y, 1, 1).data;

					for (var i = 0; i < data.length; i++) {
						average[i] += data[i];
					}
				}
			}

			for (var i = 0; i < average.length; i++) {
				average[i] /= image.width * image.height;

				if (i != average.length - 1) {
					average[i] = Math.round(average[i]);
				} else {
					average[i] /= 255;
				}
			}

			callback(average);
		}
		image.src = url + '/favicon.ico';
		console.log(image.src);
		// image.src = 'http://www.google.com/s2/favicons?domain=' + url;
	}

	$('#sites').submit(function(event) {
		event.preventDefault();
		event.stopPropagation();

		var fields = [];

		$('input:text.url').each(function(index, element) {
			var controlsCount = $('.controls').size();
			var value = $(this).val();

			if (!value || value.length == 0) {
				if (controlsCount > 2) {
					$(this).parents('.control-group').remove();

					updateAllButtons();
					return;
				}
			}
		});

		$('input:text.url').each(function(index, element) {
			var value = $(this).val();

			if (!value.match(/^(http|https):\/\//)) {
				value = "http://" + value;
				$(this).val(value);
			}

			fields[index] = {};
			fields[index].url = value;
		});

		$('input:text.abbreviation').each(function(index, element) {
			var value = $(this).val();

			fields[index].abbreviation = value;
		});

		var sitesWithColors = 0;

		for (var i = 0; i < fields.length; i++) {
			(function() {
				var site = fields[i];

				getFaviconColor(site.url, function(color) {
					console.log(site, color);

					site.color = {
						'red': color[0],
						'green': color[1],
						'blue': color[2],
						'alpha': color[3]
					};

					sitesWithColors++;

					if (sitesWithColors == fields.length) {
						chrome.storage.sync.set({"sites": fields}, function() {
							$("#success").addClass("show");

							window.setTimeout(function() {
								$("#success").removeClass("show");
							}, 2000);
						});
					}
				});
			})();
		}

		return false;
	});
});<commit_msg>Get the title of a page.<commit_after>$(document).ready(function() {
	var upButton = '';
	var downButton = '';

	var trashButton = '';
	var addButton = '';

	var controlGroup = '
 \

 \
		<input type="text" class="url" placeholder="www.google.com"> \
		<input type="text" class="input-mini abbreviation" placeholder="Gl"> \

 \

';

	chrome.storage.sync.get('sites', function(items) {
		sites = items['sites'];

		if (sites.length == 0) {
			$("#sites").prepend(controlGroup);
		}

		sites = sites.reverse();

		for (var i = 0; i < sites.length; i++) {
			var newControlGroup = controlGroup;
			var site = sites[i];

			newControlGroup = $(newControlGroup);
			newControlGroup.find('input.url').val(site.url);
			newControlGroup.find('input.abbreviation').val(site.abbreviation);

			$("#sites").prepend(newControlGroup);
		}

		updateAllButtons();

		$(".container").removeClass("hidden");
	});

	function getButtons(up, down) {
		var result = '

';

		if (up) {
			result += upButton;
		}

		if (down) {
			result += downButton;
		}

		result += '

';

		return result;
	}

	updateAllButtons();

	function updateAllButtons() {
		updateControlGroupAddRemoveButtons();
		updateControlGroupSortingButtons();
	}

	function updateControlGroupAddRemoveButtons() {
		var controlsCount = $('.controls').size();

		$('.controls').each(function(index) {
			$(this).children('.btn.add').remove();
			$(this).children('.btn.remove').remove();

			if (index != controlsCount - 1 && controlsCount != 2) {
				$(this).append(trashButton);
			}

			if (index == controlsCount - 2) {
				$(this).append(addButton);
			}
		});

		$('.btn.remove').off().on('click', removeControlGroup);
		$('.btn.add').off().on('click', addControlGroup);
	}

	function removeControlGroup() {
		parent = $(this).parents('.control-group');
		parent.remove();

		updateAllButtons();
	}

	function addControlGroup() {
		parent = $(this).parents('.control-group');

		parent.after(controlGroup);

		updateAllButtons();
	}

	function updateControlGroupSortingButtons() {
		var controlsCount = $('.controls').size();

		$('.controls').each(function(index) {
			$(this).children('.btn-toolbar').remove();

			if (index == controlsCount - 1 || controlsCount == 2) {
				return;
			}

			if (index == 0) {
				$(this).append(getButtons(false, true));
			} else if (index == controlsCount - 2) {
				$(this).append(getButtons(true, false));
			} else {
				$(this).append(getButtons(true, true));
			}
		});

		$('.btn.up').off().on('click', moveControlGroupUp);
		$('.btn.down').off().on('click', moveControlGroupDown);
	}

	function moveControlGroupUp() {
		parent = $(this).parents('.control-group');

		var previous = parent.prev();

		parent.remove();
		previous.before(parent);

		updateAllButtons();
	}

	function moveControlGroupDown() {
		parent = $(this).parents('.control-group');

		var next = parent.next();

		parent.remove();
		next.after(parent);

		updateAllButtons();
	}

	function getFaviconColor(url, callback) {
		var image = new Image();
		image.onload = function() {
			var context = $("canvas")[0].getContext('2d');
			context.drawImage(image, 0, 0);

			var average = [0, 0, 0, 0];

			for (var x = 0; x < image.width; x++) {
				for (var y = 0; y < image.height; y++) {
					data = context.getImageData(x, y, 1, 1).data;

					for (var i = 0; i < data.length; i++) {
						average[i] += data[i];
					}
				}
			}

			for (var i = 0; i < average.length; i++) {
				average[i] /= image.width * image.height;

				if (i != average.length - 1) {
					average[i] = Math.round(average[i]);
				} else {
					average[i] /= 255;
				}
			}

			callback(average);
		}
		image.src = url + '/favicon.ico';
		console.log(image.src);
		// image.src = 'http://www.google.com/s2/favicons?domain=' + url;
	}

	$('#sites').submit(function(event) {
		event.preventDefault();
		event.stopPropagation();

		var fields = [];

		$('input:text.url').each(function(index, element) {
			var controlsCount = $('.controls').size();
			var value = $(this).val();

			if (!value || value.length == 0) {
				if (controlsCount > 2) {
					$(this).parents('.control-group').remove();

					updateAllButtons();
					return;
				}
			}
		});

		$('input:text.url').each(function(index, element) {
			var value = $(this).val();

			if (!value.match(/^(http|https):\/\//)) {
				value = "http://" + value;
				$(this).val(value);
			}

			fields[index] = {};
			fields[index].url = value;
		});

		for (var i = 0; i < fields.length; i++) {
			(function() {
				var url = fields[i].url;
				$.get(url, function(response) {
					var title = (/<title>(.*?)<\/title>/m).exec(response);
					if (title) {
						console.log(url, title);
					}
				});
			})();
		}

		$('input:text.abbreviation').each(function(index, element) {
			var value = $(this).val();

			fields[index].abbreviation = value;
		});

		var sitesWithColors = 0;

		for (var i = 0; i < fields.length; i++) {
			(function() {
				var site = fields[i];

				getFaviconColor(site.url, function(color) {
					console.log(site, color);

					site.color = {
						'red': color[0],
						'green': color[1],
						'blue': color[2],
						'alpha': color[3]
					};

					sitesWithColors++;

					if (sitesWithColors == fields.length) {
						chrome.storage.sync.set({"sites": fields}, function() {
							$("#success").addClass("show");

							window.setTimeout(function() {
								$("#success").removeClass("show");
							}, 2000);
						});
					}
				});
			})();
		}

		return false;
	});
});<|endoftext|>


<commit_before>import Three from 'three';
import MTLLoader from './mtl-loader';
import OBJLoader from './obj-loader';

// export function loadObj(objPath, objFile, isSelected) {
//   let objLoader = new OBJLoader();
//   objLoader.setPath(objPath);
//   return new Promise((resolve, reject) => {
//     objLoader.load(objFile, object => {
//
//       if (isSelected) {
//         let box = new Three.BoxHelper(object, 0x99c3fb);
//         box.material.linewidth = 2;
//         box.material.depthTest = false;
//         object.add(box);
//       }
//       resolve(object);
//     });
//   });
// }

export function loadObjWithMaterial(mtlFile, objFile, imgPath) {
  let mtlLoader = new MTLLoader();
  mtlLoader.setTexturePath(imgPath);
  let url = mtlFile;
  return new Promise((resolve, reject) => {

    mtlLoader.load(url, materials => {
      materials.preload();
      let objLoader = new OBJLoader();
      objLoader.setMaterials(materials);
      objLoader.load(objFile, object => resolve(object));

    });
  });
}

<commit_msg>Code cleaning<commit_after>import MTLLoader from './mtl-loader';
import OBJLoader from './obj-loader';

export function loadObjWithMaterial(mtlFile, objFile, imgPath) {
  let mtlLoader = new MTLLoader();
  mtlLoader.setTexturePath(imgPath);
  let url = mtlFile;
  return new Promise((resolve, reject) => {

    mtlLoader.load(url, materials => {
      materials.preload();
      let objLoader = new OBJLoader();
      objLoader.setMaterials(materials);
      objLoader.load(objFile, object => resolve(object));

    });
  });
}

<|endoftext|>


<commit_before>/**
 * admin.babel.js
 *
 * Description:
 *   Admin page to controll questions
 *
 * Author:
 *  sota1235
 */
'use strict';

import React      from 'react';
import { render } from 'react-dom';
import $          from 'jquery';
// react bootstrap
import {
  ListGroup, ListGroupItem, Panel,
  ButtonToolbar, Button, Input
} from 'react-bootstrap';
// own files
import { getQuestions, addQuestion } from './ajax.babel.js';

var socket    = io();
var Component = React.Component;

/* commponents */
// question
class Question extends Component {
  render() {
    return (

        <ListGroupItem>{this.props.children}</ListGroupItem>

    );
  }
}

// form to add question
class QuestionForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      value: ''
    };
    this.handleQuestionClick = this.handleQuestionClick.bind(this);
    this.handleChange        = this.handleChange.bind(this);
  }

  handleQuestionClick() {
    var choice = ['A1', 'A2', 'A3', 'A4'];
    var text   = this.refs.input.getValue();
    this.props.onQuestionClick(text, choice);
    this.refs.input.setValue('');
    return;
  }

  handleChange() {
    this.setState({
      value: this.refs.input.getValue()
    });
  }

  render() {
    return (

        <Input
          type='text'
          placeholder='クイズ本文を入力してください'
          hasFeedback
          value={this.state.value}
          ref='input'
          groupClassName='group-class'
          labelClassName='label-class'
          onChange={this.handleChange} />
        <ButtonToolbar>
          <Button
            bsStyle='primary'
            onClick={this.handleQuestionClick}>
            クイズを作成
          </Button>
        </ButtonToolbar>

    );
  }
}

// question list
class QuestionList extends Component {
  render() {
    var questionNodes = this.props.questions.map(function(question) {
      return (
        <Question id={question._id} key={question._id}>
          {question.text}
        </Question>
      )
    });
    return (

        <ListGroup>
          {questionNodes}
        </ListGroup>

    );
  }
}

// admin page
class QuestionAdmin extends Component {
  constructor(props) {
    super(props);
    this.state = {
      questions: []
    };
    this.handleQuestionClick = this.handleQuestionClick.bind(this);
  }

  handleQuestionClick(text, choice) {
    var that = this;
    addQuestion(text, choice)
      .then(function(result) {
        console.log(`Submit comment success : ${JSON.stringify(result)}`);
        that.loadQuestions();
      });
  }

  loadQuestions() {
    var that = this;
    getQuestions()
      .then(function(questions) {
        that.setState({questions: questions});
      });
  }

  componentDidMount() {
    this.loadQuestions();
  }

  render() {
    return (

Hello, question admin

        <QuestionForm onQuestionClick={this.handleQuestionClick} />
        <QuestionList questions={this.state.questions} />

    );
  }
}

/* rendering */
render(
  <QuestionAdmin />,
  document.getElementById('question-admin')
);
<commit_msg>modify: add delete button component<commit_after>/**
 * admin.babel.js
 *
 * Description:
 *   Admin page to controll questions
 *
 * Author:
 *  sota1235
 */
'use strict';

import React      from 'react';
import { render } from 'react-dom';
import $          from 'jquery';
// react bootstrap
import {
  ListGroup, ListGroupItem, Panel,
  ButtonToolbar, Button, Input
} from 'react-bootstrap';
// own files
import { getQuestions, addQuestion } from './ajax.babel.js';

var socket    = io();
var Component = React.Component;

/* commponents */
// question
class Question extends Component {
  constructor(props) {
    super(props);
    this.state = {
      buttonStyle: {
        float: 'right'
      }
    }
  }

  render() {
    return (

        <ListGroupItem>

            {this.props.children}
            <Button bsStyle='danger' pullRight style={this.state.buttonStyle}>削除</Button>

        </ListGroupItem>

    );
  }
}

// form to add question
class QuestionForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      value: ''
    };
    this.handleQuestionClick = this.handleQuestionClick.bind(this);
    this.handleChange        = this.handleChange.bind(this);
  }

  handleQuestionClick() {
    var choice = ['A1', 'A2', 'A3', 'A4'];
    var text   = this.refs.input.getValue();
    this.props.onQuestionClick(text, choice);
    this.refs.input.setValue('');
    return;
  }

  handleChange() {
    this.setState({
      value: this.refs.input.getValue()
    });
  }

  render() {
    return (

        <Input
          type='text'
          placeholder='クイズ本文を入力してください'
          hasFeedback
          value={this.state.value}
          ref='input'
          groupClassName='group-class'
          labelClassName='label-class'
          onChange={this.handleChange} />
        <ButtonToolbar>
          <Button
            bsStyle='primary'
            onClick={this.handleQuestionClick}>
            クイズを作成
          </Button>
        </ButtonToolbar>

    );
  }
}

// question list
class QuestionList extends Component {
  render() {
    var questionNodes = this.props.questions.map(function(question) {
      return (
        <Question id={question._id} key={question._id}>
          {question.text}
        </Question>
      )
    });
    return (

        <ListGroup>
          {questionNodes}
        </ListGroup>

    );
  }
}

// admin page
class QuestionAdmin extends Component {
  constructor(props) {
    super(props);
    this.state = {
      questions: []
    };
    this.handleQuestionClick = this.handleQuestionClick.bind(this);
  }

  handleQuestionClick(text, choice) {
    var that = this;
    addQuestion(text, choice)
      .then(function(result) {
        console.log(`Submit comment success : ${JSON.stringify(result)}`);
        that.loadQuestions();
      });
  }

  loadQuestions() {
    var that = this;
    getQuestions()
      .then(function(questions) {
        that.setState({questions: questions});
      });
  }

  componentDidMount() {
    this.loadQuestions();
  }

  render() {
    return (

Hello, question admin

        <QuestionForm onQuestionClick={this.handleQuestionClick} />
        <QuestionList questions={this.state.questions} />

    );
  }
}

/* rendering */
render(
  <QuestionAdmin />,
  document.getElementById('question-admin')
);
<|endoftext|>


<commit_before>module.exports = {
  "bundles": {
    "dist/app-build": {
      "includes": [
        "[**/*.js]",
        "**/*.json!json",
        "**/*.html!text",
        "**/*.css!text"
      ],
      "options": {
        "inject": true,
        "minify": true,
        // "depCache": true,
        "rev": true
      }
    },
    "dist/aurelia": {
      "includes": [
        "aurelia-framework",
        "aurelia-bootstrapper",
        "aurelia-fetch-client",
        "aurelia-router",
        "aurelia-animator-css",
        "aurelia-templating-binding",
        "aurelia-polyfills",
        "aurelia-templating-resources",
        "aurelia-templating-router",
        "aurelia-loader-default",
        "aurelia-history-browser",
        "aurelia-validatejs",
        "aurelia-dialog",
        "aurelia-dialog/*.js",
        "aurelia-logging-console",
        "[bootstrap]",
        "[bootstrap/js/bootstrap.js]",
        "bootstrap/css/bootstrap.css!text",
        "aurelia-v-grid",
        "aurelia-v-grid/**/*.js",
        "aurelia-v-grid/**/*.html!text",
        "aurelia-v-grid/**/*.css!text",
        "fetch",
        "moment",
        "showdown",
        "semver",
        "json",
        "text"
      ],
      "options": {
        "inject": true,
        "minify": true,
        // "depCache": false,
        "rev": true
      }
    }
  }
};
<commit_msg>chore(deployment): don't bundle app files yet to allow for easier debugging<commit_after>module.exports = {
  "bundles": {
    // "dist/app-build": {
    //   "includes": [
    //     "[**/*.js]",
    //     "**/*.json!json",
    //     "**/*.html!text",
    //     "**/*.css!text"
    //   ],
    //   "options": {
    //     "inject": true,
    //     "minify": true,
    //     // "depCache": true,
    //     "rev": true
    //   }
    // },
    "dist/aurelia": {
      "includes": [
        "aurelia-framework",
        "aurelia-bootstrapper",
        "aurelia-fetch-client",
        "aurelia-router",
        "aurelia-animator-css",
        "aurelia-templating-binding",
        "aurelia-polyfills",
        "aurelia-templating-resources",
        "aurelia-templating-router",
        "aurelia-loader-default",
        "aurelia-history-browser",
        "aurelia-validatejs",
        "aurelia-dialog",
        "aurelia-dialog/*.js",
        "aurelia-logging-console",
        "[bootstrap]",
        "[bootstrap/js/bootstrap.js]",
        "bootstrap/css/bootstrap.css!text",
        "aurelia-v-grid",
        "aurelia-v-grid/**/*.js",
        "aurelia-v-grid/**/*.html!text",
        "aurelia-v-grid/**/*.css!text",
        "fetch",
        "moment",
        "showdown",
        "semver",
        "json",
        "text"
      ],
      "options": {
        "inject": true,
        "minify": true,
        // "depCache": false,
        "rev": true
      }
    }
  }
};
<|endoftext|>


<commit_before>/**
 * Expose the Adapter object.
 */
var Adapter = module.exports = {};

/**
 * Dependencies.
 */
var browser = require('bowser').browser;  // TODO: Fix when my PR accepted.
var debug = require('debug')('rtcninja:Adapter');

/**
 * Local variables.
 */
var getUserMedia = null;
var RTCPeerConnection = null;
var browserVersion = Number(browser.version) || 0;
var isDesktop = !!(! browser.mobile || ! browser.tablet);

debug('detected browser: %s %s [mobile:%s, tablet:%s, android:%s, ios:%s]', browser.name, browser.version, !!browser.mobile, !!browser.tablet, !!browser.android, !!browser.ios);

// Chrome desktop.
if (isDesktop && browser.chrome && browserVersion >= 23) {
	getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
	RTCPeerConnection = global.webkitRTCPeerConnection;
}

// Firefox desktop.
else if (isDesktop && browser.firefox && browserVersion >= 22) {
	getUserMedia = navigator.mozGetUserMedia.bind(navigator);
	RTCPeerConnection = function(pcConfig, pcConstraints) {
		// .urls is not supported in FF yet.
		setIceServersUrl(pcConfig);
		return new global.mozRTCPeerConnection(pcConfig, pcConstraints);
	};
}

// Opera desktop.
else if (isDesktop && browser.opera && browserVersion >= 27) {
	getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
	RTCPeerConnection = global.webkitRTCPeerConnection;
}

// Chrome Android.
else if (browser.android && browser.chrome && browserVersion >= 39) {
	getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
	RTCPeerConnection = global.webkitRTCPeerConnection;
}
// Firefox Android.
else if (browser.android && browser.firefox && browserVersion >= 33) {
	getUserMedia = navigator.mozGetUserMedia.bind(navigator);
	RTCPeerConnection = function(pcConfig, pcConstraints) {
		// .urls is not supported in FF yet.
		setIceServersUrl(pcConfig);
		return new global.mozRTCPeerConnection(pcConfig, pcConstraints);
	};
}

// Opera Android.
else if (browser.android && browser.opera && browserVersion >= 24) {
	getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
	RTCPeerConnection = global.webkitRTCPeerConnection;
}

// Android native browser.
else if (browser.android && browserVersion >= 37) {
	getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
	RTCPeerConnection = global.webkitRTCPeerConnection;
}

// Others.
else if (navigator.webkitGetUserMedia && global.webkitRTCPeerConnection) {
	getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
	RTCPeerConnection = global.webkitRTCPeerConnection;
}
else if (navigator.mozGetUserMedia && global.mozRTCPeerConnection) {
	getUserMedia = navigator.mozGetUserMedia.bind(navigator);
	RTCPeerConnection = function(pcConfig, pcConstraints) {
		// .urls is not supported in FF yet.
		setIceServersUrl(pcConfig);
		return new global.mozRTCPeerConnection(pcConfig, pcConstraints);
	};
}
else if (navigator.getUserMedia && global.RTCPeerConnection) {
	getUserMedia = navigator.getUserMedia.bind(navigator);
	RTCPeerConnection = global.RTCPeerConnection;
}

function setIceServersUrl(pcConfig) {
	if (! pcConfig || ! Array.isArray(pcConfig.iceServers)) {
		return;
	}

	for (var i=0, len=pcConfig.iceServers.length; i < len; i++) {
		if (pcConfig.iceServers[i].hasOwnProperty('urls')) {
			pcConfig.iceServers[i].url = pcConfig.iceServers[i].urls;
			delete pcConfig.iceServers[i].urls;
		}
	}
}

function throwNonSupported(item) {
	return function() {
		throw new Error('rtcninja: WebRTC not supported, missing ' +item+ ' [browser: ' +browser.name+ ' ' +browser.version + ']');
	};
}

// Expose getUserMedia.
Adapter.getUserMedia = getUserMedia || throwNonSupported('getUserMedia');

// Expose RTCPeerConnection.
Adapter.RTCPeerConnection = RTCPeerConnection || throwNonSupported('RTCPeerConnection');

// Expose a WebRTC checker.
Adapter.hasWebRTC = !!(getUserMedia && RTCPeerConnection);

// Expose browser.
Adapter.browser = browser;
<commit_msg>Filter STUN/TURN candidates in Firefox (fixes #1)<commit_after>/**
 * Expose the Adapter object.
 */
var Adapter = module.exports = {};

/**
 * Dependencies.
 */
var browser = require('bowser').browser;  // TODO: Fix when my PR accepted.
var debug = require('debug')('rtcninja:Adapter');

/**
 * Local variables.
 */
var getUserMedia = null;
var RTCPeerConnection = null;
var browserVersion = Number(browser.version) || 0;
var isDesktop = !!(! browser.mobile || ! browser.tablet);

debug('detected browser: %s %s [mobile:%s, tablet:%s, android:%s, ios:%s]', browser.name, browser.version, !!browser.mobile, !!browser.tablet, !!browser.android, !!browser.ios);

// Chrome desktop.
if (isDesktop && browser.chrome && browserVersion >= 23) {
	getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
	RTCPeerConnection = global.webkitRTCPeerConnection;
}

// Firefox desktop.
else if (isDesktop && browser.firefox && browserVersion >= 22) {
	getUserMedia = navigator.mozGetUserMedia.bind(navigator);
	RTCPeerConnection = function(pcConfig, pcConstraints) {
		setSingleIceServer(pcConfig);
		setIceServersUrl(pcConfig);
		return new global.mozRTCPeerConnection(pcConfig, pcConstraints);
	};
}

// Opera desktop.
else if (isDesktop && browser.opera && browserVersion >= 27) {
	getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
	RTCPeerConnection = global.webkitRTCPeerConnection;
}

// Chrome Android.
else if (browser.android && browser.chrome && browserVersion >= 39) {
	getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
	RTCPeerConnection = global.webkitRTCPeerConnection;
}
// Firefox Android.
else if (browser.android && browser.firefox && browserVersion >= 33) {
	getUserMedia = navigator.mozGetUserMedia.bind(navigator);
	RTCPeerConnection = function(pcConfig, pcConstraints) {
		setSingleIceServer(pcConfig);
		setIceServersUrl(pcConfig);
		return new global.mozRTCPeerConnection(pcConfig, pcConstraints);
	};
}

// Opera Android.
else if (browser.android && browser.opera && browserVersion >= 24) {
	getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
	RTCPeerConnection = global.webkitRTCPeerConnection;
}

// Android native browser.
else if (browser.android && browserVersion >= 37) {
	getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
	RTCPeerConnection = global.webkitRTCPeerConnection;
}

// Others.
else if (navigator.webkitGetUserMedia && global.webkitRTCPeerConnection) {
	getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
	RTCPeerConnection = global.webkitRTCPeerConnection;
}
else if (navigator.mozGetUserMedia && global.mozRTCPeerConnection) {
	getUserMedia = navigator.mozGetUserMedia.bind(navigator);
	RTCPeerConnection = function(pcConfig, pcConstraints) {
		setSingleIceServer(pcConfig);
		setIceServersUrl(pcConfig);
		return new global.mozRTCPeerConnection(pcConfig, pcConstraints);
	};
}
else if (navigator.getUserMedia && global.RTCPeerConnection) {
	getUserMedia = navigator.getUserMedia.bind(navigator);
	RTCPeerConnection = global.RTCPeerConnection;
}

function setSingleIceServer(pcConfig) {
	for (var i=0, len=pcConfig.iceServers.length; i < len; i++) {
		var server = pcConfig.iceServers[i];
		var urls = server.urls || server.url;

		if (! Array.isArray(urls)) {
			continue;
		}
		else {
			// Just let the first URL.
			urls.splice(1, urls.length);
		}
	}
}

function setIceServersUrl(pcConfig) {
	for (var i=0, len=pcConfig.iceServers.length; i < len; i++) {
		if (pcConfig.iceServers[i].hasOwnProperty('urls')) {
			pcConfig.iceServers[i].url = pcConfig.iceServers[i].urls;
			delete pcConfig.iceServers[i].urls;
		}
	}
}

function throwNonSupported(item) {
	return function() {
		throw new Error('rtcninja: WebRTC not supported, missing ' +item+ ' [browser: ' +browser.name+ ' ' +browser.version + ']');
	};
}

// Expose getUserMedia.
Adapter.getUserMedia = getUserMedia || throwNonSupported('getUserMedia');

// Expose RTCPeerConnection.
Adapter.RTCPeerConnection = RTCPeerConnection || throwNonSupported('RTCPeerConnection');

// Expose a WebRTC checker.
Adapter.hasWebRTC = !!(getUserMedia && RTCPeerConnection);

// Expose browser.
Adapter.browser = browser;
<|endoftext|>


<commit_before>'use strict';

var https = require('https');
var fs = require('fs');

var detectedVersion = null;
var baseDir = null;

if (fs.existsSync('/opt/sencha-brain')) {
  detectedVersion = 'Version 64';
  baseDir = '/opt';
} else {
  detectedVersion = 'Not version 64';
  baseDir = '/home/iva';
}

var deviceConfig = JSON.parse(fs.readFileSync(baseDir + '/sencha-brain/device_config.json'));

var ca = fs.readFileSync(deviceConfig.updater.caFile);
var cert = fs.readFileSync(deviceConfig.brain.certFile);
var key = fs.readFileSync(deviceConfig.brain.keyFile);

function report(err, res, cb) {
  console.log(res);
  var data = JSON.stringify({
    error: err ? err : null,
    result: res
  });

  var options = {
    host: 'updates.lamassu.is',
    port: 8000,
    path: '/report',
    method: 'POST',
    key: key,
    cert: cert,
    ca: ca,
    ciphers: 'AES128-GCM-SHA256:RC4:HIGH:!MD5:!aNULL:!EDH',
    secureProtocol: 'TLSv1_method',
    rejectUnauthorized: true,
    headers: {
      'Content-Type': 'application/json',
      'Content-Length': data.length
    }
  };
  options.agent = new https.Agent(options);

  // Set up the request
  var req = https.request(options, function(res) {
    res.setEncoding('utf8');
    res.resume();
    res.on('end', cb);
  });

  req.on('error', function(err) { console.log(err); cb(); });
  req.write(data);
  req.end();
}

report(null, 'started', function() {});

var async = require('./async');

process.on('SIGUSR2', function() {
  // USR1 is reserved by node
  // TODO: more graceful exit
  console.log('Got SIGUSR2. Immune.');
});

async.waterfall([
  async.apply(report, null, detectedVersion)
], function(err) {
  report(err, 'finished', function() {
    if (err) throw err;
    console.log('done updatescript');
    process.exit();
  });
});
<commit_msg>fixed certs paths in aaeon_version<commit_after>'use strict';

var https = require('https');
var fs = require('fs');

var detectedVersion = null;
var baseDir = null;

if (fs.existsSync('/opt/sencha-brain')) {
  detectedVersion = 'Version 64';
  baseDir = '/opt';
} else {
  detectedVersion = 'Not version 64';
  baseDir = '/home/iva';
}

var deviceConfig = JSON.parse(fs.readFileSync(baseDir + '/sencha-brain/device_config.json'));

var ca = fs.readFileSync(deviceConfig.updater.caFile);
var cert = fs.readFileSync(deviceConfig.brain.certs.certFile);
var key = fs.readFileSync(deviceConfig.brain.certs.keyFile);

function report(err, res, cb) {
  console.log(res);
  var data = JSON.stringify({
    error: err ? err : null,
    result: res
  });

  var options = {
    host: 'updates.lamassu.is',
    port: 8000,
    path: '/report',
    method: 'POST',
    key: key,
    cert: cert,
    ca: ca,
    ciphers: 'AES128-GCM-SHA256:RC4:HIGH:!MD5:!aNULL:!EDH',
    secureProtocol: 'TLSv1_method',
    rejectUnauthorized: true,
    headers: {
      'Content-Type': 'application/json',
      'Content-Length': data.length
    }
  };
  options.agent = new https.Agent(options);

  // Set up the request
  var req = https.request(options, function(res) {
    res.setEncoding('utf8');
    res.resume();
    res.on('end', cb);
  });

  req.on('error', function(err) { console.log(err); cb(); });
  req.write(data);
  req.end();
}

report(null, 'started', function() {});

var async = require('./async');

process.on('SIGUSR2', function() {
  // USR1 is reserved by node
  // TODO: more graceful exit
  console.log('Got SIGUSR2. Immune.');
});

async.waterfall([
  async.apply(report, null, detectedVersion)
], function(err) {
  report(err, 'finished', function() {
    if (err) throw err;
    console.log('done updatescript');
    process.exit();
  });
});
<|endoftext|>


<commit_before>#!/usr/bin/env node
/*
 * Pulley: Easy Github Pull Request Lander
 * Copyright 2011 John Resig
 * MIT Licensed
 */
(function() {
	"use strict";

	var child = require("child_process"),
		http = require("https"),
		fs = require("fs"),
		prompt = require("prompt"),
		request = require("request"),
		colors = require("colors"),

		// Process references
		exec = child.exec,
		spawn = child.spawn,

		// Process arguments
		id = process.argv[ 2 ],
		done = process.argv[ 3 ],

		// Localized application references
		user_repo = "",
		tracker = "",
		token = "",

		// Initialize config file
		config = JSON.parse( fs.readFileSync( __dirname + "/config.json" ) );

	// We don't want the default prompt message
	prompt.message = "";

	process.stdout.write( "Initializing... ".blue );

	exec( "git config --global --get pulley.token", function( error, stdout, stderr ) {
		token = stdout.trim();

		if ( token ) {
			init();
		} else {
			login();
		}
	});

	function login() {
		console.log("\nPlease login with your GitHub credentials.");
		console.log("Your credentials are only needed this one time to get a token from GitHub.");
		prompt.start();
		prompt.get([{
			name: "username",
			message: "Username",
			empty: false
		}, {
			name: "password",
			message: "Password",
			empty: false,
			hidden: true
		}], function( err, result ) {
			var auth = encodeURIComponent( result.username ) + ":" + encodeURIComponent( result.password );
			request.post("https://" + auth + "@api.github.com/authorizations", {
				json: true,
				body: {
					scopes: ["repo"],
					note: "Pulley",
					note_url: "https://github.com/jeresig/pulley"
				}
			}, function( err, res, body ) {
				token = body.token;
				if ( token ) {
					exec( "git config --global --add pulley.token " + token, function( error, stdout, stderr ) {
						console.log( "Success!".green );
						init();
					});
				} else {
					console.log( ( body.message + ". Try again." ).red );
					login();
				}
			});
		});
	}

	function init() {
		if ( !id ) {
			exit("No pull request ID specified, please provide one.");
		}
		exec( "git remote -v show " + config.remote, function( error, stdout, stderr ) {
			user_repo = ( /URL:.*?([\w\-]+\/[\w\-]+)/.exec( stdout ) || [] )[ 1 ];
			tracker = config.repos[ user_repo ];

			if ( user_repo ) {
				getStatus();
			} else {
				exit("External repository not found.");
			}
		});
	}

	function getStatus() {
		exec( "git status", function( error, stdout, stderr ) {
			if ( /Changes to be committed/i.test( stdout ) ) {
				if ( done ) {
					getPullData();
				} else {
					exit("Please commit changed files before attemping a pull/merge.");
				}
			} else if ( /Changes not staged for commit/i.test( stdout ) ) {
				if ( done ) {
					exit("Please add files that you wish to commit.");

				} else {
					exit("Please stash files before attempting a pull/merge.");
				}
			} else {
				if ( done ) {
					exit("It looks like you've broken your merge attempt.");
				} else {
					getPullData();
				}
			}
		});
	}

	function getPullData() {
		var path = "/repos/" + user_repo + "/pulls/" + id;

		console.log( "done.".green );
		process.stdout.write( "Getting pull request details... ".blue );

		callAPI( path, function( data ) {
			try {
				var pull = JSON.parse( data );

				console.log( "done.".green );

				if ( done ) {
					commit( pull );
				} else {
					mergePull( pull );
				}
			} catch( e ) {
				exit("Error retrieving pull request from Github.");
			}
		});
	}

	function mergePull( pull ) {
		var repo = pull.head.repo.ssh_url,
			head_branch = pull.head.ref,
			base_branch = pull.base.ref,
			branch = "pull-" + id,
			checkout_cmds = [
				"git checkout " + base_branch,
				"git pull " + config.remote + " " + base_branch,
				"git submodule update --init",
				"git checkout -b " + branch
			];

		process.stdout.write( "Pulling and merging results... ".blue );

		if ( pull.state === "closed" ) {
			exit("Can not merge closed Pull Requests.");
		}

		if ( pull.merged ) {
			exit("This Pull Request has already been merged.");
		}

		// TODO: give user the option to resolve the merge by themselves
		if ( !pull.mergeable ) {
			exit("This Pull Request is not automatically mergeable.");
		}

		exec( checkout_cmds.join( " && " ), function( error, stdout, stderr ) {
			if ( /toplevel/i.test( stderr ) ) {
				exit("Please call pulley from the toplevel directory of this repo.");
			} else if ( /fatal/i.test( stderr ) ) {
				exec( "git branch -D " + branch + " && " + checkout, doPull );
			} else {
				doPull();
			}
		});

		function doPull( error, stdout, stderr ) {
			var pull_cmds = [
				"git pull " + repo + " " + head_branch,
				"git checkout " + base_branch,
				"git merge --no-commit --squash " + branch
			];

			exec( pull_cmds.join( " && " ), function( error, stdout, stderr ) {
				if ( /Merge conflict/i.test( stdout ) ) {
					exit("Merge conflict. Please resolve then run: " +
						process.argv.join(" ") + " done");
				} else if ( /error/.test( stderr ) ) {
					exit("Unable to merge.  Please resolve then retry:\n" + stderr);
				} else {
					console.log( "done.".green );
					commit( pull );
				}
			});
		}
	}

	function commit( pull ) {
		var path = "/repos/" + user_repo + "/pulls/" + id + "/commits";

		process.stdout.write( "Getting author and committing changes... ".blue );

		callAPI( path, function( data ) {
			var match,
				msg = "Close GH-" + id + ": " + pull.title + ".",
				author = JSON.parse( data )[ 0 ].commit.author.name,
				base_branch = pull.base.ref,
				issues = [],
				urls = [],
				findBug = /#(\d+)/g;

			// Search title and body for issues for issues to link to
			if ( tracker ) {
				while ( ( match = findBug.exec( pull.title + pull.body ) ) ) {
					urls.push( tracker + match[ 1 ] );
				}
			}

			// Search just body for issues to add to the commit message
			while ( ( match = findBug.exec( pull.body ) ) ) {
				issues.push( " Fixes #" + match[ 1 ] );
			}

			// Add issues to the commit message
			msg += issues.join(",");

			if ( urls.length ) {
				msg += "\n\nMore Details:" + urls.map(function( url ) {
					return "\n - " + url;
				}).join("");
			}

			var commit = [ "commit", "-a", "--message=" + msg ];

			if ( config.interactive ) {
				commit.push("-e");
			}

			if ( author ) {
				commit.push( "--author=" + author );
			}

			getHEAD(function( oldCommit ) {
				// Thanks to: https://gist.github.com/927052
				spawn( "git", commit, {
					customFds: [ process.stdin, process.stdout, process.stderr ]
				}).on( "exit", function() {
					getHEAD(function( newCommit ) {
						if ( oldCommit === newCommit ) {
							reset("No commit, aborting push.");
						} else {
							exec( "git push " + config.remote + " " + base_branch, function( error, stdout, stderr ) {
								console.log( "done.".green );
								exit();
							});
						}
					});
				});
			});
		});
	}

	function callAPI( path, callback ) {
		request.get( "https://api.github.com" + path, {
			headers: {
				Authorization: "token " + token
			}
		}, function( err, res, body ) {
			var statusCode = res.socket._httpMessage.res.statusCode;

			if ( err ) {
				exit( err );
			}

			if ( statusCode === 404 ) {
				exit("Pull request doesn't exist");
			}

			if ( statusCode === 401 ) {
				login();
				return;
			}

			callback( body );
		});
	}

	function getHEAD( fn ) {
		exec( "git log | head -1", function( error, stdout, stderr ) {
			var commit = ( /commit (.*)/.exec( stdout ) || [] )[ 1 ];

			fn( commit );
		});
	}

	function reset( msg ) {
		console.error( ( "\n" + msg ).red );
		process.stderr.write( "Resetting files... ".red );

		exec( "git reset --hard ORIG_HEAD", function() {
			console.log( "done.".green );
			exit();
		});
	}

	function exit( msg ) {
		if ( msg ) {
			console.error( ( "\nError: " + msg ).red );
		}

		process.exit( 1 );
	}

})();<commit_msg>Finish retry feature when pulley branch exists (var checkout was undefined)<commit_after>#!/usr/bin/env node
/*
 * Pulley: Easy Github Pull Request Lander
 * Copyright 2011 John Resig
 * MIT Licensed
 */
(function() {
	"use strict";

	var child = require("child_process"),
		http = require("https"),
		fs = require("fs"),
		prompt = require("prompt"),
		request = require("request"),
		colors = require("colors"),

		// Process references
		exec = child.exec,
		spawn = child.spawn,

		// Process arguments
		id = process.argv[ 2 ],
		done = process.argv[ 3 ],

		// Localized application references
		user_repo = "",
		tracker = "",
		token = "",

		// Initialize config file
		config = JSON.parse( fs.readFileSync( __dirname + "/config.json" ) );

	// We don't want the default prompt message
	prompt.message = "";

	process.stdout.write( "Initializing... ".blue );

	exec( "git config --global --get pulley.token", function( error, stdout, stderr ) {
		token = stdout.trim();

		if ( token ) {
			init();
		} else {
			login();
		}
	});

	function login() {
		console.log("\nPlease login with your GitHub credentials.");
		console.log("Your credentials are only needed this one time to get a token from GitHub.");
		prompt.start();
		prompt.get([{
			name: "username",
			message: "Username",
			empty: false
		}, {
			name: "password",
			message: "Password",
			empty: false,
			hidden: true
		}], function( err, result ) {
			var auth = encodeURIComponent( result.username ) + ":" + encodeURIComponent( result.password );
			request.post("https://" + auth + "@api.github.com/authorizations", {
				json: true,
				body: {
					scopes: ["repo"],
					note: "Pulley",
					note_url: "https://github.com/jeresig/pulley"
				}
			}, function( err, res, body ) {
				token = body.token;
				if ( token ) {
					exec( "git config --global --add pulley.token " + token, function( error, stdout, stderr ) {
						console.log( "Success!".green );
						init();
					});
				} else {
					console.log( ( body.message + ". Try again." ).red );
					login();
				}
			});
		});
	}

	function init() {
		if ( !id ) {
			exit("No pull request ID specified, please provide one.");
		}
		exec( "git remote -v show " + config.remote, function( error, stdout, stderr ) {
			user_repo = ( /URL:.*?([\w\-]+\/[\w\-]+)/.exec( stdout ) || [] )[ 1 ];
			tracker = config.repos[ user_repo ];

			if ( user_repo ) {
				getStatus();
			} else {
				exit("External repository not found.");
			}
		});
	}

	function getStatus() {
		exec( "git status", function( error, stdout, stderr ) {
			if ( /Changes to be committed/i.test( stdout ) ) {
				if ( done ) {
					getPullData();
				} else {
					exit("Please commit changed files before attemping a pull/merge.");
				}
			} else if ( /Changes not staged for commit/i.test( stdout ) ) {
				if ( done ) {
					exit("Please add files that you wish to commit.");

				} else {
					exit("Please stash files before attempting a pull/merge.");
				}
			} else {
				if ( done ) {
					exit("It looks like you've broken your merge attempt.");
				} else {
					getPullData();
				}
			}
		});
	}

	function getPullData() {
		var path = "/repos/" + user_repo + "/pulls/" + id;

		console.log( "done.".green );
		process.stdout.write( "Getting pull request details... ".blue );

		callAPI( path, function( data ) {
			try {
				var pull = JSON.parse( data );

				console.log( "done.".green );

				if ( done ) {
					commit( pull );
				} else {
					mergePull( pull );
				}
			} catch( e ) {
				exit("Error retrieving pull request from Github.");
			}
		});
	}

	function mergePull( pull ) {
		var repo = pull.head.repo.ssh_url,
			head_branch = pull.head.ref,
			base_branch = pull.base.ref,
			branch = "pull-" + id,
			checkout = "git checkout " + base_branch,
			checkout_cmds = [
				checkout,
				"git pull " + config.remote + " " + base_branch,
				"git submodule update --init",
				"git checkout -b " + branch
			];

		process.stdout.write( "Pulling and merging results... ".blue );

		if ( pull.state === "closed" ) {
			exit("Can not merge closed Pull Requests.");
		}

		if ( pull.merged ) {
			exit("This Pull Request has already been merged.");
		}

		// TODO: give user the option to resolve the merge by themselves
		if ( !pull.mergeable ) {
			exit("This Pull Request is not automatically mergeable.");
		}

		exec( checkout_cmds.join( " && " ), function( error, stdout, stderr ) {
			if ( /toplevel/i.test( stderr ) ) {
				exit("Please call pulley from the toplevel directory of this repo.");
			} else if ( /fatal/i.test( stderr ) ) {
				exec( "git branch -D " + branch + " && " + checkout, doPull );
			} else {
				doPull();
			}
		});

		function doPull( error, stdout, stderr ) {
			var pull_cmds = [
				"git pull " + repo + " " + head_branch,
				checkout,
				"git merge --no-commit --squash " + branch
			];

			exec( pull_cmds.join( " && " ), function( error, stdout, stderr ) {
				if ( /Merge conflict/i.test( stdout ) ) {
					exit("Merge conflict. Please resolve then run: " +
						process.argv.join(" ") + " done");
				} else if ( /error/.test( stderr ) ) {
					exit("Unable to merge.  Please resolve then retry:\n" + stderr);
				} else {
					console.log( "done.".green );
					commit( pull );
				}
			});
		}
	}

	function commit( pull ) {
		var path = "/repos/" + user_repo + "/pulls/" + id + "/commits";

		process.stdout.write( "Getting author and committing changes... ".blue );

		callAPI( path, function( data ) {
			var match,
				msg = "Close GH-" + id + ": " + pull.title + ".",
				author = JSON.parse( data )[ 0 ].commit.author.name,
				base_branch = pull.base.ref,
				issues = [],
				urls = [],
				findBug = /#(\d+)/g;

			// Search title and body for issues for issues to link to
			if ( tracker ) {
				while ( ( match = findBug.exec( pull.title + pull.body ) ) ) {
					urls.push( tracker + match[ 1 ] );
				}
			}

			// Search just body for issues to add to the commit message
			while ( ( match = findBug.exec( pull.body ) ) ) {
				issues.push( " Fixes #" + match[ 1 ] );
			}

			// Add issues to the commit message
			msg += issues.join(",");

			if ( urls.length ) {
				msg += "\n\nMore Details:" + urls.map(function( url ) {
					return "\n - " + url;
				}).join("");
			}

			var commit = [ "commit", "-a", "--message=" + msg ];

			if ( config.interactive ) {
				commit.push("-e");
			}

			if ( author ) {
				commit.push( "--author=" + author );
			}

			getHEAD(function( oldCommit ) {
				// Thanks to: https://gist.github.com/927052
				spawn( "git", commit, {
					customFds: [ process.stdin, process.stdout, process.stderr ]
				}).on( "exit", function() {
					getHEAD(function( newCommit ) {
						if ( oldCommit === newCommit ) {
							reset("No commit, aborting push.");
						} else {
							exec( "git push " + config.remote + " " + base_branch, function( error, stdout, stderr ) {
								console.log( "done.".green );
								exit();
							});
						}
					});
				});
			});
		});
	}

	function callAPI( path, callback ) {
		request.get( "https://api.github.com" + path, {
			headers: {
				Authorization: "token " + token
			}
		}, function( err, res, body ) {
			var statusCode = res.socket._httpMessage.res.statusCode;

			if ( err ) {
				exit( err );
			}

			if ( statusCode === 404 ) {
				exit("Pull request doesn't exist");
			}

			if ( statusCode === 401 ) {
				login();
				return;
			}

			callback( body );
		});
	}

	function getHEAD( fn ) {
		exec( "git log | head -1", function( error, stdout, stderr ) {
			var commit = ( /commit (.*)/.exec( stdout ) || [] )[ 1 ];

			fn( commit );
		});
	}

	function reset( msg ) {
		console.error( ( "\n" + msg ).red );
		process.stderr.write( "Resetting files... ".red );

		exec( "git reset --hard ORIG_HEAD", function() {
			console.log( "done.".green );
			exit();
		});
	}

	function exit( msg ) {
		if ( msg ) {
			console.error( ( "\nError: " + msg ).red );
		}

		process.exit( 1 );
	}

})();<|endoftext|>


<commit_before><commit_msg>Update project EventEmitter to v4.3.0<commit_after><|endoftext|>


<commit_before>/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
export default function injectCustomCss(css) {
  const className = 'CssEditor-css';
  const head = document.head || document.getElementsByTagName('head')[0];
  let style = document.querySelector(`.${className}`);

  if (!style) {
    style = document.createElement('style');
    style.className = className;
    style.type = 'text/css';
    head.appendChild(style);
  }
  if (style.styleSheet) {
    style.styleSheet.cssText = css;
  } else {
    style.innerHTML = css;
  }
}
<commit_msg>Fix CSS injection order (#12265) (#12353)<commit_after>/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
export default function injectCustomCss(css) {
  const className = 'CssEditor-css';
  const head = document.head || document.getElementsByTagName('head')[0];
  let style = document.querySelector(`.${className}`);

  if (!style) {
    style = document.createElement('style');
    style.className = className;
    style.type = 'text/css';
  }

  if (style.styleSheet) {
    style.styleSheet.cssText = css;
  } else {
    style.innerHTML = css;
  }

  /**
   * Ensures that the style applied is always the last.
   *
   * from: https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild
   * The Node.appendChild() method adds a node to the end of the list of children
   * of a specified parent node. If the given child is a reference to an existing
   * node in the document, appendChild() moves it from its current position to the
   * new position (there is no requirement to remove the node from its parent node
   * before appending it to some other node).
   */

  head.appendChild(style);
}
<|endoftext|>


<commit_before>const HtmlWebpackPlugin = require('html-webpack-plugin')
const PreloadWebpackPlugin = require('preload-webpack-plugin')
const {ENV} = require('./paths')

const htmlSettings = {
  template: 'index.ejs',
  chunksSortMode: 'dependency',
  minify: (ENV === 'production') ? {
    removeComments: true,
    collapseWhitespace: true
  } : undefined
}

module.exports = {
  plugins: [
    new HtmlWebpackPlugin(htmlSettings),
    new PreloadWebpackPlugin({
      rel: 'prefetch' // Prefetch resources likely to be used for future navigations
    })
  ]
}
<commit_msg>Minify JS in index.html<commit_after>const HtmlWebpackPlugin = require('html-webpack-plugin')
const PreloadWebpackPlugin = require('preload-webpack-plugin')
const {transform} = require('babel-core')
const {ENV} = require('./paths')

const babelOpt = {
  babelrc: false,
  comments: false,
  filename: 'index.html',
  minified: true,
  presets: ['minify']
}

const htmlSettings = {
  template: 'index.ejs',
  chunksSortMode: 'dependency',
  minify: (ENV === 'production') ? {
    removeComments: true,
    collapseWhitespace: true,
    minifyJS(code) {
      return transform(code, babelOpt).code
    }
  } : undefined
}

module.exports = {
  plugins: [
    new HtmlWebpackPlugin(htmlSettings),
    new PreloadWebpackPlugin({
      rel: 'prefetch' // Prefetch resources likely to be used for future navigations
    })
  ]
}
<|endoftext|>


<commit_before>'use strict'

const debug = require('debug')('HeadlessChrome:browser')

/**
 * Created by: Luciano A. Ganga
 * Inspired by:
 *    - Doffy (https://github.com/qieguo2016/doffy)
 *    - Horseman (https://github.com/johntitus/node-horseman)
 * More Info:
 * https://developers.google.com/web/updates/2017/04/headless-chrome
 * https://chromedevtools.github.io/devtools-protocol
 * https://github.com/cyrus-and/chrome-remote-interface
 */

const EventEmitter = require('events')

const merge = require('deepmerge')

const chrome = require('./chrome')
const Tab = require('./Tab')

const defaultOptions = {
  headless: true,
  launchChrome: true, // If false, only connects CDP to the Chrome instance in host:port
  chrome: {
    host: 'localhost',
    port: 0, // Chrome instance port (defaults to 0 to generate a random port)
    remote: false,
    launchAttempts: 3,
    userDataDir: null,
    disableGPU: true,
    handleSIGINT: true,
    flags: ['--enable-logging'],
    noSandbox: false
  },
  tabs: {
    maxTabs: Infinity,
    startingUrl: 'about:blank' // Default starting URL for all the tabs
  },
  deviceMetrics: {
    width: 1024,
    height: 768,
    deviceScaleFactor: 1,
    mobile: false,
    fitWindow: false
  },
  browser: {
    loadPageTimeout: 60000,
    loadSelectorInterval: 500,
    loadSelectorTimeout: 60000,
    browserLog: false // {boolean|function}
  }
}

class Browser extends EventEmitter {
  constructor (options = {}) {
    super()
    // Deep merge in order to prevent total override of default params
    this.options = merge(defaultOptions, options)
    this.host = this.options.chrome.host
    this._tabs = [] // TODO: This array must be initialized with the list of tabs of the attached Chrome instance (if the chrome instance is not new but a remote one with existing tabs, this should be autocompleted from that instance)
    this._closedTabs = [] // This keeps track of closed tab ids
  }

  /**
   * Initializates a Chrome instance and opens a new tab
   * If it exceeds the maxTabs defined by user, returns undefined
   * @param {boolean} private Indicates a private tab (supported only in Headless mode)
   * @return - A browser tab instance, with all the actions
   */
  async init () {
    if (this.options.launchChrome) {
      // Launch a new Chrome instance and update the instance port
      const initializationOptions = this.options.chrome
      this.chromeInstance = await chrome.launch(this.options.headless, initializationOptions)
      this.port = this.chromeInstance.port
    }

    try {
      // Attach the Chrome Debugging Protocol to the chrome instance
      this.client = await chrome.attachCdpToBrowser(this.host, this.port, this.options.chrome.remote)

      return this
    } catch (err) {
      await this.chromeInstance.kill()
      throw err
    }
  }

  /**
   * Initializates a new Chrome tab and controls it.
   * If it exceeds the maxTabs defined by user, returns undefined
   * @param {boolean} privateTab Indicates a private tab (supported only in Headless mode)
   * @return - A browser tab instance, with all the actions
   */
  async newTab ({ privateTab = false } = {}) {
    debug(`:: newTab => Opening a new tab in browser. Private tab: ${privateTab}`)

    /**
     * Don't open tab if maxTabs reached, and not open private tab if not headless
     */
    if (Object.keys(this._tabs).length >= this.options.tabs.maxTabs) {
      const error = new Error(`Can't open new tab. Max tabs limit reached`)
      error.maxTabs = this.options.tabs.maxTabs
      error.openedTabs = Object.keys(this._tabs).length
      throw error
    }

    // Create and initialize the new tab
    const tab = new Tab(this.host, this.port, {
      privateTab,
      startingUrl: this.options.tabs.startingUrl
    }, this)

    await tab.init()

    this._tabs[tab.getId()] = tab

    return tab
  }

  getTab (tabId) {
    debug(`:: getTab => Getting tab ${tabId}`)
    return this._tabs[tabId]
  }

  /**
   * Lists all the open tabs ids
   */
  async listTabs () {
    debug(`:: listTabs => Listing all tabs`)
    let array = []
    for (let key in this._tabs) {
      array.push(this._tabs[key].id)
    }
    return array
  }

  /**
   * Lists all the private targets/tabs ids
   * only in headless mode
   */
  listPrivateTabs () {
    debug(`:: listPrivateTabs => Listing all private tabs...`)
    if (!this.options.headless) {
      debug(`:: listPrivateTabs => Can't list private tabs without headless mode!`)
      return
    }

    let array = []
    for (let key in this._tabs) {
      if (this._tabs[key].privateTab) array.push(this._tabs[key].id)
    }
    debug(`:: listPrivateTabs => "${array.length}" private tabs found.`)
    return array
  }

  /**
   * Exit the Chrome instance
   * @param {boolean} exit - Indicates if chromeInstance must be killed with SIGHUP
   * @return {boolean} - true if exited successfully
   */
  async close (exit = true) {
    debug(`:: close => Closing the browser.`)
    if (!this.client) {
      debug(`:: close => Can not close the browser. Browser instance doesn't exists.`)
      return
    }

    try {
      await this.client.close()
      this.client = null
      this._tabs = []
      this._closedTabs = []
      exit && await this.chromeInstance.kill('SIGHUP')
      debug(`:: close => Browser closed correctly!`)
      return true
    } catch (err) {
      throw err
    }
  }

  /**
   * PRIVATE METHOD - Erases all the information of a closed target/tab.
   * @param {string} the target/tab ID that was closed
   */
  async _closeTarget (tabId) {
    const target = this._tabs[tabId]

    // Save information about the closed tab
    this._closedTabs.push({
      id: tabId,
      closedAt: target.closedAt,
      instance: target
    })

    // Remove the tab from the active tabs list
    delete this._tabs[tabId]
  }

  /**
   * Tells if the browser is initialized
   */
  isInitialized () {
    return !!this.client
  }
}

module.exports = Browser
<commit_msg>Before trying to kill a chrome instance, check if it exists. It may not exists if the browser wasn't launched by this module<commit_after>'use strict'

const debug = require('debug')('HeadlessChrome:browser')

/**
 * Created by: Luciano A. Ganga
 * Inspired by:
 *    - Doffy (https://github.com/qieguo2016/doffy)
 *    - Horseman (https://github.com/johntitus/node-horseman)
 * More Info:
 * https://developers.google.com/web/updates/2017/04/headless-chrome
 * https://chromedevtools.github.io/devtools-protocol
 * https://github.com/cyrus-and/chrome-remote-interface
 */

const EventEmitter = require('events')

const merge = require('deepmerge')

const chrome = require('./chrome')
const Tab = require('./Tab')

const defaultOptions = {
  headless: true,
  launchChrome: true, // If false, only connects CDP to the Chrome instance in host:port
  chrome: {
    host: 'localhost',
    port: 0, // Chrome instance port (defaults to 0 to generate a random port)
    remote: false,
    launchAttempts: 3,
    userDataDir: null,
    disableGPU: true,
    handleSIGINT: true,
    flags: ['--enable-logging'],
    noSandbox: false
  },
  tabs: {
    maxTabs: Infinity,
    startingUrl: 'about:blank' // Default starting URL for all the tabs
  },
  deviceMetrics: {
    width: 1024,
    height: 768,
    deviceScaleFactor: 1,
    mobile: false,
    fitWindow: false
  },
  browser: {
    loadPageTimeout: 60000,
    loadSelectorInterval: 500,
    loadSelectorTimeout: 60000,
    browserLog: false // {boolean|function}
  }
}

class Browser extends EventEmitter {
  constructor (options = {}) {
    super()
    // Deep merge in order to prevent total override of default params
    this.options = merge(defaultOptions, options)
    this.host = this.options.chrome.host
    this._tabs = [] // TODO: This array must be initialized with the list of tabs of the attached Chrome instance (if the chrome instance is not new but a remote one with existing tabs, this should be autocompleted from that instance)
    this._closedTabs = [] // This keeps track of closed tab ids
  }

  /**
   * Initializates a Chrome instance and opens a new tab
   * If it exceeds the maxTabs defined by user, returns undefined
   * @param {boolean} private Indicates a private tab (supported only in Headless mode)
   * @return - A browser tab instance, with all the actions
   */
  async init () {
    if (this.options.launchChrome) {
      // Launch a new Chrome instance and update the instance port
      const initializationOptions = this.options.chrome
      this.chromeInstance = await chrome.launch(this.options.headless, initializationOptions)
      this.port = this.chromeInstance.port
    }

    try {
      // Attach the Chrome Debugging Protocol to the chrome instance
      this.client = await chrome.attachCdpToBrowser(this.host, this.port, this.options.chrome.remote)

      return this
    } catch (err) {
      await this.chromeInstance && this.chromeInstance.kill()
      throw err
    }
  }

  /**
   * Initializates a new Chrome tab and controls it.
   * If it exceeds the maxTabs defined by user, returns undefined
   * @param {boolean} privateTab Indicates a private tab (supported only in Headless mode)
   * @return - A browser tab instance, with all the actions
   */
  async newTab ({ privateTab = false } = {}) {
    debug(`:: newTab => Opening a new tab in browser. Private tab: ${privateTab}`)

    /**
     * Don't open tab if maxTabs reached, and not open private tab if not headless
     */
    if (Object.keys(this._tabs).length >= this.options.tabs.maxTabs) {
      const error = new Error(`Can't open new tab. Max tabs limit reached`)
      error.maxTabs = this.options.tabs.maxTabs
      error.openedTabs = Object.keys(this._tabs).length
      throw error
    }

    // Create and initialize the new tab
    const tab = new Tab(this.host, this.port, {
      privateTab,
      startingUrl: this.options.tabs.startingUrl
    }, this)

    await tab.init()

    this._tabs[tab.getId()] = tab

    return tab
  }

  getTab (tabId) {
    debug(`:: getTab => Getting tab ${tabId}`)
    return this._tabs[tabId]
  }

  /**
   * Lists all the open tabs ids
   */
  async listTabs () {
    debug(`:: listTabs => Listing all tabs`)
    let array = []
    for (let key in this._tabs) {
      array.push(this._tabs[key].id)
    }
    return array
  }

  /**
   * Lists all the private targets/tabs ids
   * only in headless mode
   */
  listPrivateTabs () {
    debug(`:: listPrivateTabs => Listing all private tabs...`)
    if (!this.options.headless) {
      debug(`:: listPrivateTabs => Can't list private tabs without headless mode!`)
      return
    }

    let array = []
    for (let key in this._tabs) {
      if (this._tabs[key].privateTab) array.push(this._tabs[key].id)
    }
    debug(`:: listPrivateTabs => "${array.length}" private tabs found.`)
    return array
  }

  /**
   * Exit the Chrome instance
   * @param {boolean} exit - Indicates if chromeInstance must be killed with SIGHUP
   * @return {boolean} - true if exited successfully
   */
  async close (exit = true) {
    debug(`:: close => Closing the browser.`)
    if (!this.client) {
      debug(`:: close => Can not close the browser. Browser instance doesn't exists.`)
      return
    }

    try {
      await this.client.close()
      this.client = null
      this._tabs = []
      this._closedTabs = []
      exit && await this.chromeInstance.kill('SIGHUP')
      debug(`:: close => Browser closed correctly!`)
      return true
    } catch (err) {
      throw err
    }
  }

  /**
   * PRIVATE METHOD - Erases all the information of a closed target/tab.
   * @param {string} the target/tab ID that was closed
   */
  async _closeTarget (tabId) {
    const target = this._tabs[tabId]

    // Save information about the closed tab
    this._closedTabs.push({
      id: tabId,
      closedAt: target.closedAt,
      instance: target
    })

    // Remove the tab from the active tabs list
    delete this._tabs[tabId]
  }

  /**
   * Tells if the browser is initialized
   */
  isInitialized () {
    return !!this.client
  }
}

module.exports = Browser
<|endoftext|>


<commit_before>var isDyslexic = false;
function fontCookieCheck() {
  var infoInCookie = readCookie('178fontcookie');
  isDyslexic = eval(infoInCookie);
  if (!infoInCookie) {
    fontAlert1();
  } else {
      if (isDyslexic == true) {
        var font = "Open Dyslexic";
      } else {
        var font = "Open Sans";
      }
      setFont(font);
  }
}

function fontAlert1() {
  if (($(window).height() <= 565 && $(window).width() <= 675) || ($(window).height() <= 420) || ($(window).width() <= 420)) {
    isDyslexic = confirm("Would you like to use a Dyslexia friendly font on this website?");
    if (isDyslexic == true) {
      createFontCookie("true");
      alert("The font is now set to Open Dyslexic.\n\nTo change your settings, use the switch at the bottom of the page.")
    } else {
      createFontCookie("false")
      alert("The font is the same font it's always been.\n\nTo change your settings, use the switch at the bottom of the page.")
    }
  } else {
    $(".swal2-modal").css('fontFamily', 'Open Dyslexic');
    $("button").css('fontFamily', 'Open Dyslexic');
    swal({
      title: 'Dyslexia Font',
      text: 'To use the dyslexia friendly font Open Dyslexic on this site, select the button below.',
      type: 'info',
      showCancelButton: true,
      confirmButtonText: 'Open Dyslexic',
      allowOutsideClick: false,
      allowEscapeKey: false,
    }).then(function setFont4Cookie(isConfirm) {
      if (isConfirm) {
        createFontCookie("true");
        swal({
          title: 'You\'ve set the font!',
          text: 'To change your settings, toggle the switch at the bottom of the page.',
          showCloseButton: true,
          type: 'success',
        });
      } else if (isConfirm == false) {
        createFontCookie("false");
        swal({
          title: 'You\'ve kept the same font!',
          text: 'To change your settings, toggle the switch at the bottom of the page.',
          showCloseButton: true,
          type: 'success',
        });
      } else {
        swal(
          'Uhhhh...',
          'So... This shouldn\'t be possible. I\'m not sure why this happened... Email me: timtv25@gmail.com',
          'error'
        );
      }
    });
  }
}

function createFontCookie(font4Cookie) {
  createCookie('178fontcookie',font4Cookie,5475);
  isDyslexic = eval(font4Cookie);
  fontCookieCheck();
}

function toggleFont() {
  if (isDyslexic == true) {
    isDyslexic = false;
    setFont("Open Sans");
  } else {
    isDyslexic = true;
    setFont("Open Dyslexic");
  }
  createFontCookie(isDyslexic.toString());
}

function setFont(font) {
  if (font != null) {
    $("body").css('fontFamily', font);
    $(".swal2-modal").css('fontFamily', font);
    $("button").css('fontFamily', font);
    $("#font-stuff").css('display', 'block');
    // TODO: Make things look *more* correct by setting specific styles to be different.
    // This part makes everything zoom out to look like it's the right size:
    if (isDyslexic == true) {
      $('body').css('zoom', .95);
      $('#picshoembed').css('zoom', 1.25);
      $('.switch-input')[0].checked = true;
    } else {
      $('.switch-input')[0].checked = false;
      $('body').css('zoom', 1);
    }
  }
}

$(document).ready(fontCookieCheck); // Runs the function fontCookieCheck everytime the page loads.
$(window).load(function() {
  $("body").css("display", "block");
});
<commit_msg>Removed popup on page load. (it's annoying)<commit_after>var isDyslexic = false;
function fontCookieCheck() {
  var infoInCookie = readCookie('178fontcookie');
  isDyslexic = eval(infoInCookie);
    if (isDyslexic == true) {
      var font = "Open Dyslexic";
    } else {
      var font = "Open Sans";
    }
    setFont(font);
}

/*function fontAlert1() {
  if (($(window).height() <= 565 && $(window).width() <= 675) || ($(window).height() <= 420) || ($(window).width() <= 420)) {
    isDyslexic = confirm("Would you like to use a Dyslexia friendly font on this website?");
    if (isDyslexic == true) {
      createFontCookie("true");
      alert("The font is now set to Open Dyslexic.\n\nTo change your settings, use the switch at the bottom of the page.")
    } else {
      createFontCookie("false")
      alert("The font is the same font it's always been.\n\nTo change your settings, use the switch at the bottom of the page.")
    }
  } else {
    $(".swal2-modal").css('fontFamily', 'Open Dyslexic');
    $("button").css('fontFamily', 'Open Dyslexic');
    swal({
      title: 'Dyslexia Font',
      text: 'To use the dyslexia friendly font Open Dyslexic on this site, select the button below.',
      type: 'info',
      showCancelButton: true,
      confirmButtonText: 'Open Dyslexic',
      allowOutsideClick: false,
      allowEscapeKey: false,
    }).then(function setFont4Cookie(isConfirm) {
      if (isConfirm) {
        createFontCookie("true");
        swal({
          title: 'You\'ve set the font!',
          text: 'To change your settings, toggle the switch at the bottom of the page.',
          showCloseButton: true,
          type: 'success',
        });
      } else if (isConfirm == false) {
        createFontCookie("false");
        swal({
          title: 'You\'ve kept the same font!',
          text: 'To change your settings, toggle the switch at the bottom of the page.',
          showCloseButton: true,
          type: 'success',
        });
      } else {
        swal(
          'Uhhhh...',
          'So... This shouldn\'t be possible. I\'m not sure why this happened... Email me: timtv25@gmail.com',
          'error'
        );
      }
    });
  }
}*/

function createFontCookie(font4Cookie) {
  createCookie('178fontcookie',font4Cookie,5475);
  isDyslexic = eval(font4Cookie);
  fontCookieCheck();
}

function toggleFont() {
  if (isDyslexic == true) {
    isDyslexic = false;
    setFont("Open Sans");
  } else {
    isDyslexic = true;
    setFont("Open Dyslexic");
  }
  createFontCookie(isDyslexic.toString());
}

function setFont(font) {
  if (font != null) {
    $("body").css('fontFamily', font);
    $(".swal2-modal").css('fontFamily', font);
    $("button").css('fontFamily', font);
    $("#font-stuff").css('display', 'block');
    // TODO: Make things look *more* correct by setting specific styles to be different.
    // This part makes everything zoom out to look like it's the right size:
    if (isDyslexic == true) {
      $('body').css('zoom', .95);
      $('#picshoembed').css('zoom', 1.25);
      $('.switch-input')[0].checked = true;
    } else {
      $('.switch-input')[0].checked = false;
      $('body').css('zoom', 1);
    }
  }
}

$(document).ready(fontCookieCheck); // Runs the function fontCookieCheck everytime the page loads.
$(window).load(function() {
  $("body").css("display", "block");
});
<|endoftext|>