<commit_before>(function($) {

function present( value, array, message ) {
	QUnit.push( jQuery.inArray( value, array ) !== -1 , value, array, message );
}

function notPresent( value, array, message ) {
	QUnit.push( jQuery.inArray( value, array ) === -1 , value, array, message );
}

var animateTime = 15;

module( "effects.core" );

$.each( $.effects.effect, function( effect ) {
	if ( effect === "transfer" ) {
		return;
	}
	module( "effect."+effect );
	asyncTest( "show/hide", function() {
		var hidden = $( "div.hidden" );
		expect( 8 );

		var count = 0,
			test = 0;

		function queueTest( fn ) {
			count++;
			var point = count;
			return function( next ) {
				test++;
				equal( point, test, "Queue function fired in order" );
				if ( fn ) {
					fn ();
				} else {
					setTimeout( next, animateTime );
				}
			};
		}

		hidden.queue( queueTest() ).show( effect, animateTime, queueTest(function() {
			equal( hidden.css("display"), "block", "Hidden is shown after .show(\"" +effect+ "\", time)" );
		})).queue( queueTest() ).hide( effect, animateTime, queueTest(function() {
			equal( hidden.css("display"), "none", "Back to hidden after .hide(\"" +effect+ "\", time)" );
		})).queue( queueTest(function(next) {
			deepEqual( hidden.queue(), ["inprogress"], "Only the inprogress sentinel remains");
			start();
		}));
	});
});

module("animateClass");

asyncTest( "animateClass works with borderStyle", function() {
	var test = $("div.animateClass"),
		count = 0;
	expect(3);
	test.toggleClass("testAddBorder", 20, function() {
		test.toggleClass("testAddBorder", 20, function() {
			equal( test.css("borderLeftStyle"), "none", "None border set" );
			start();
		});
		equal( test.css("borderLeftStyle"), "solid", "None border not immedately set" );
	});
	equal( test.css("borderLeftStyle"), "solid", "Solid border immedately set" );
});

asyncTest( "animateClass works with colors", function() {
	var test = $("div.animateClass"),
		count = 0;
	expect(2);
	test.toggleClass("testChangeBackground", 100, function() {
		present( test.css("backgroundColor"), [ "#ffffff", "rgb(255, 255, 255)" ], "Color is final" );
		start();
	});
	setTimeout(function() {
		var color = test.css("backgroundColor");
		notPresent( color, [ "#000000", "#ffffff", "rgb(0, 0, 0)", "rgb(255,255,255)" ],
			"Color is not endpoints in middle." );
	}, 50);
});

asyncTest( "animateClass works with children", function() {
	var test = $("div.animateClass"),
		h2 = test.find("h2");

	expect(4);
	test.toggleClass("testChildren", { children: true, duration: 100, complete: function() {
		equal( h2.css("fontSize"), "20px", "Text size is final during complete");
		test.toggleClass("testChildren", 100, function() {
			equal( h2.css("fontSize"), "10px", "Text size revertted after class removed");
			start();
		});
		setTimeout(function() {
			equal( h2.css("fontSize"), "20px", "Text size unchanged with children: undefined" );
		}, 50);
	}});
	setTimeout(function() {
		notPresent( h2.css("fontSize"), ["10px","20px"], "Font size is neither endpoint when in middle.");
	}, 50);
});

})(jQuery);
<commit_msg>Unit Tests: Cleaning up some code in effects unit tests, removing magic numbers used for animation durations<commit_after>(function($) {

function present( value, array, message ) {
	QUnit.push( jQuery.inArray( value, array ) !== -1 , value, array, message );
}

function notPresent( value, array, message ) {
	QUnit.push( jQuery.inArray( value, array ) === -1 , value, array, message );
}

// minDuration is used for "short" animate tests where we are only concerned about the final
var minDuration = 15,

	// duration is used for "long" animates where we plan on testing properties during animation
	duration = 200,

	// mid is used for testing in the "middle" of the "duration" animations
	mid = duration / 2;

module( "effects.core" );

$.each( $.effects.effect, function( effect ) {
	if ( effect === "transfer" ) {
		return;
	}
	module( "effect."+effect );
	asyncTest( "show/hide", function() {
		var hidden = $( "div.hidden" );
		expect( 8 );

		var count = 0,
			test = 0;

		function queueTest( fn ) {
			count++;
			var point = count;
			return function( next ) {
				test++;
				equal( point, test, "Queue function fired in order" );
				if ( fn ) {
					fn();
				} else {
					setTimeout( next, minDuration );
				}
			};
		}

		hidden.queue( queueTest() ).show( effect, minDuration, queueTest(function() {
			equal( hidden.css("display"), "block", "Hidden is shown after .show(\"" +effect+ "\", time)" );
		})).queue( queueTest() ).hide( effect, minDuration, queueTest(function() {
			equal( hidden.css("display"), "none", "Back to hidden after .hide(\"" +effect+ "\", time)" );
		})).queue( queueTest(function(next) {
			deepEqual( hidden.queue(), ["inprogress"], "Only the inprogress sentinel remains");
			start();
		}));
	});
});

module("animateClass");

asyncTest( "animateClass works with borderStyle", function() {
	var test = $("div.animateClass"),
		count = 0;
	expect(3);
	test.toggleClass("testAddBorder", minDuration, function() {
		test.toggleClass("testAddBorder", minDuration, function() {
			equal( test.css("borderLeftStyle"), "none", "None border set" );
			start();
		});
		equal( test.css("borderLeftStyle"), "solid", "None border not immedately set" );
	});
	equal( test.css("borderLeftStyle"), "solid", "Solid border immedately set" );
});

asyncTest( "animateClass works with colors", function() {
	var test = $("div.animateClass"),
		count = 0;
	expect(2);
	test.toggleClass("testChangeBackground", duration, function() {
		present( test.css("backgroundColor"), [ "#ffffff", "rgb(255, 255, 255)" ], "Color is final" );
		start();
	});
	setTimeout(function() {
		var color = test.css("backgroundColor");
		notPresent( color, [ "#000000", "#ffffff", "rgb(0, 0, 0)", "rgb(255,255,255)" ],
			"Color is not endpoints in middle." );
	}, mid);
});

asyncTest( "animateClass works with children", function() {
	var test = $("div.animateClass"),
		h2 = test.find("h2");

	expect(4);
	test.toggleClass("testChildren", { children: true, duration: duration, complete: function() {
		equal( h2.css("fontSize"), "20px", "Text size is final during complete");
		test.toggleClass("testChildren", duration, function() {
			equal( h2.css("fontSize"), "10px", "Text size revertted after class removed");
			start();
		});
		setTimeout(function() {
			equal( h2.css("fontSize"), "20px", "Text size unchanged with children: undefined" );
		}, mid);
	}});
	setTimeout(function() {
		notPresent( h2.css("fontSize"), ["10px","20px"], "Font size is neither endpoint when in middle.");
	}, mid);
});

})(jQuery);
<|endoftext|>


<commit_before>var irc = require('irc');
var fs = require('fs');
var EventEmitter = require('events');
var reload = require('require-reload')(require);
var utils;

if(!global.is_reloading) {
    var console_log = console.log;
    var console_err = console.error;
    console.log = function(text) {
        console_log(new Date().toUTCString() + ' - ' + text);
    }
    console.error = function(text) {
        console_err(new Date().toUTCString() + ' - ERROR: ' + text);
    }
    global.is_reloading = true;
}

var actions;
var modules = {};
var configs = {};
var globals = {};

function reset_actions() {
    for(var module in modules) {
        if(modules[module].destroy) {
            try {
                modules[module].destroy();
            } catch(e) {
                console.error('while destroying ' + module + ': ' + e);
            }
        }
    }

    actions = new EventEmitter();
    modules = {};
    globals = {};
}

function load_actions() {
    reset_actions();

    utils = reload('./utils.js');

    function help_on_empty(func) {
        return function(bot, from, to, text) {
            if(!text.trim()) {
                return true;
            } else {
                return func.apply(this, arguments);
            }
        }
    }

    function op_only(func) {
        return function(bot, from, to) {
            if(!bot.chans || !bot.chans[bot.channel.toLowerCase()] || bot.chans[bot.channel.toLowerCase()].users[from] !== '@') {
                bot.sayDirect(from, to, 'Only ops may use this command.');
                return;
            }

            return func.apply(this, arguments);
        }
    }

    function no_pm(func) {
        return function(bot, from, to) {
            if(to === bot.nick && bot.chans[bot.channel] && bot.chans[bot.channel].users[from] !== '@') {
                bot.sayDirect(from, to, 'This command is not allowed in pm.');
            } else {
                return func.apply(this, arguments);
            }
        }
    }

    var help_msgs = {};

    actions.on('reload', op_only(function(bot, from, to, text, message) {
        try {
            console.log('Reloading FancyBot');

            for(var config in configs) {
                save_config(config, configs[config], true);
            }

            try {
                load_actions();

                bot.disconnect('Reloading...', function() {
                    global.is_reloading = true;
                    reload(process.argv[1]);
                });
            } catch(e) {
                bot.sayDirect(from, to, 'Reloading attempt failed, could not reload actions: ' + e);
                console.error('Failed to reload actions: ' + e);
                console.error(e.stack);
            }
        } catch(e) {
            console.log('Failed to reload the actions ' + e + '\n' + e.stack);
            bot.sayDirect(from, to, 'Failed to reload the actions ' + e.message);
        }
    }));
    help_msgs['reload'] = 'Usage: !reload. Reloads all actions, op only use.';

    actions.on('help', function(bot, from, to, text, message) {
        if(text) {
            if(help_msgs[text]) {
                bot.sayDirect(from, to, help_msgs[text]);
            } else {
                bot.sayDirect(from, to, 'No help message found for command \'' + text + '\'.');
            }
        } else {
            var commands = '';
            for(var command in actions._events) {
                if(command[0] !== '_') {
                    commands += ' ' + command;
                }
            }
            bot.sayDirect(from, to, 'Available commands:' + commands);
        }
    });
    help_msgs['help'] = 'Usage: !help [command]. Displays a help message for the command, or if ommitted lists all available commands.'

    fs.readdirSync('actions/').forEach(function(file) {
        if(!file.endsWith('.js')) return;

        var name = file.substring(0, file.length - 3);

        if(name === 'bot') {
            throw 'Cannot use reserved name \'bot\'.';
        }

        modules[name] = reload('./actions/' + file);

        var action_utils = {
            save_config: function() {
                save_config(name, configs[name]);
            },
            globals: globals,
        };
        Object.assign(action_utils, utils);

        if(!configs[name]) {
            configs[name] = load_config(name);
        }
        var action_config = configs[name];

        function action(options, func) {
            if(options.name[0] !== '_') {
                if(actions.listenerCount(options.name) > 0) {
                    throw 'Cannot have two user actions registered to the same name.';
                }

                if(options.help_on_empty) {
                    func = help_on_empty(func);
                }
                if(options.op_only) {
                    func = op_only(func);
                }
                if(options.no_pm) {
                    func = no_pm(func);
                }

                help_msgs[options.name] = options.help;
            }

            var f = function(bot, from, to) {
                var args = Array.from(arguments).concat([action_utils, action_config]);
                if(func.apply(this, args) && options.name[0] !== '_' && options.help) {
                    bot.sayDirect(from, to, options.help);
                }
            };

            actions.on(options.name, f);
        }

        if(modules[name].init) {
            modules[name].init(action, action_utils, action_config);
            console.log('Loaded ' + name);
        }
    });
}

function load_config(name) {
    try {
        var config = JSON.parse(fs.readFileSync('configs/' + name + '.json'));
        console.log('Loaded config');
        return config;
    } catch(e) {
        console.error('COULD NOT LOAD CONFIG: ' + e + '\n' + e.stack);
        return {};
    }
}

var configs_timeout = {};
function save_config(name, config, immediately) {
    if(!configs_timeout[name]) {
        configs_timeout[name] = {
            save_config_count: 0,
            last_config_timeout: null,
        };
    }

    if(configs_timeout[name].save_config_count < 10 || immediately) {
        if(configs_timeout[name].last_config_timeout) {
            clearTimeout(configs_timeout[name].last_config_timeout);
            configs_timeout[name].save_config_count++;
        }

        if(immediately) {
            fs.writeFileSync('configs/' + name + '.json', JSON.stringify(config, null, 4));
            configs_timeout[name].save_config_count = 0;
            configs_timeout[name].last_config_timeout = null;
        } else {
            configs_timeout[name].last_config_timeout = setTimeout(function() {
                configs_timeout[name].save_config_count = 0;
                configs_timeout[name].last_config_timeout = null;
                fs.writeFile('configs/' + name + '.json', JSON.stringify(config, null, 4), function(err) {
                    if(err)
                        console.error('COULD NOT WRITE CONFIG!');
                });
            }, 1000);
        }
    }
}

var bot_config = JSON.parse(fs.readFileSync('config.json'));

load_actions();

var name = bot_config.name;
var server = bot_config.server;
var chan = bot_config.channel;

var bot = new irc.Client(server, name, {
    userName: name,
    realName: name,
    channels: [chan],
    autoRejoin: true
});
bot.channel = chan;

bot.sayDirect = function(from, to, message) {
    if(to === bot.nick) {
        bot.say(from, message);
    } else {
        bot.say(to, from + ': ' + message);
    }
}

bot.on('registered', function(message) {
    console.log('Successfully joined ' + server + '!');

    if(bot_config.password) {
        console.log('Identifying...');
        bot.say('NickServ', 'identify ' + bot_config.password);
    }

    actions.emit('_init', bot, message);
});

bot.on('join', function(channel, nick, message) {
    if(nick === bot.nick) {
        if(global.is_reloading) {
            console.log('Successfully reloaded ' + name + '.');
            bot.say(channel, 'Successfully reloaded ' + name + '.');
        }

        console.log('Joined ' + channel);
        actions.emit('_joined', bot, channel, message);
    } else {
        actions.emit('_join', bot, channel, nick, message);
    }
});

bot.on('part', function(channel, nick, reason, message) {
    actions.emit('_part', bot, channel, nick, reason, message);
});

bot.on('quit', function(nick, reason, channels, message) {
    actions.emit('_quit', bot, bot.channel, nick, reason, message);
});

bot.on('kick', function(channel, nick, by, reason ,message) {
    actions.emit('_kick', bot, channel, nick, by, reason, message);
});

bot.on('nick', function(oldnick, newnick, channels, message) {
    if(bot.nick != name) {
        bot.send('NICK', name);
    }

    if(newnick === name) {
        actions.emit('_init', bot, message);
    }

    actions.emit('_nick', bot, oldnick, newnick, channels, message);
});

bot.on('message', function(nick, to, text, message) {
    actions.emit('_msg', bot, nick, to, text, message);

    if(text[0] === '!') {
        var index = text.indexOf(' ');
        var command = text.substring(1, index == -1 ? undefined : index).trim();

        console.log('Detected command from ' + nick + ': ' + command);

        if(command[0] != '_' && actions.emit(command, bot, nick, to, index == -1 ? '' : text.substring(index).trim(), message)) {
            return;
        }

        console.log('Command \'' + command + '\' not found.');
    }

    actions.emit('_', bot, nick, to, text, message);
});

bot.on('notice', function(nick, to, text, message) {
    if(to === bot.nick) {
        console.log('NOTICE: -' + (nick === null ? 'Server' : nick) + '- ' + text);
    }

    actions.emit('_notice', bot, nick, to, text, message);
});

bot.on('selfMessage', function(to, text) {
    actions.emit('_self', bot, to, text);
});

bot.on('action', function(nick, to, text, message) {
    actions.emit('_action', bot, nick, to, text, message);
});

bot.on('+mode', function(channel, by, mode, argument, message) {
    actions.emit('_mode', bot, channel, by, '+' + mode, argument, message);
});

bot.on('-mode', function(channel, by, mode, argument, message) {
    actions.emit('_mode', bot, channel, by, '-' + mode, argument, message);
});

bot.on('error', function(message) {
    console.error(require('util').inspect(message));
});

process.on('exit', function() {
    console.log("Goodbye!");
});

console.log('Joining ' + server + '...');
<commit_msg>Aded reloadbot command that reloads entire bot, keeping reload command to only actions.<commit_after>var irc = require('irc');
var fs = require('fs');
var EventEmitter = require('events');
var reload = require('require-reload')(require);
var utils;

if(!global.is_reloading) {
    var console_log = console.log;
    var console_err = console.error;
    console.log = function(text) {
        console_log(new Date().toUTCString() + ' - ' + text);
    }
    console.error = function(text) {
        console_err(new Date().toUTCString() + ' - ERROR: ' + text);
    }
    global.is_reloading = true;
}

var actions;
var modules = {};
var configs = {};
var globals = {};

function reset_actions() {
    for(var module in modules) {
        if(modules[module].destroy) {
            try {
                modules[module].destroy();
            } catch(e) {
                console.error('while destroying ' + module + ': ' + e);
            }
        }
    }

    actions = new EventEmitter();
    modules = {};
    globals = {};
}

function load_actions() {
    reset_actions();

    utils = reload('./utils.js');

    function help_on_empty(func) {
        return function(bot, from, to, text) {
            if(!text.trim()) {
                return true;
            } else {
                return func.apply(this, arguments);
            }
        }
    }

    function op_only(func) {
        return function(bot, from, to) {
            if(!bot.chans || !bot.chans[bot.channel.toLowerCase()] || bot.chans[bot.channel.toLowerCase()].users[from] !== '@') {
                bot.sayDirect(from, to, 'Only ops may use this command.');
                return;
            }

            return func.apply(this, arguments);
        }
    }

    function no_pm(func) {
        return function(bot, from, to) {
            if(to === bot.nick && bot.chans[bot.channel] && bot.chans[bot.channel].users[from] !== '@') {
                bot.sayDirect(from, to, 'This command is not allowed in pm.');
            } else {
                return func.apply(this, arguments);
            }
        }
    }

    var help_msgs = {};

    actions.on('reload', op_only(function(bot, from, to, text, message) {
        console.log('Reloading actions.');

        var old_actions = actions;
        var old_globals = globals;

        try {
            load_actions();
            bot.sayDirect(from, to, 'Successfully reloaded actions.');
            console.log('Successfully reloaded actions.');
        } catch(e) {
            bot.sayDirect(from, to, 'Reloading attempt failed, could not reload actions: ' + e);
            console.error('Failed to reload actions: ' + e);
            console.error(e.stack);

            actions = old_actions;
            globals = old_globals;
        }
    }));
    help_msgs['reload'] = 'Usage: !reload. Reloads all actions, op only use.';

    actions.on('reloadbot', op_only(function(bot, from, to, text, message) {
        try {
            console.log('Reloading FancyBot');

            for(var config in configs) {
                save_config(config, configs[config], true);
            }

            try {
                load_actions();

                bot.disconnect('Reloading...', function() {
                    global.is_reloading = true;
                    reload(process.argv[1]);
                });
            } catch(e) {
                bot.sayDirect(from, to, 'Reloading attempt failed, could not reload actions: ' + e);
                console.error('Failed to reload actions: ' + e);
                console.error(e.stack);
            }
        } catch(e) {
            console.log('Failed to reload the actions ' + e + '\n' + e.stack);
            bot.sayDirect(from, to, 'Failed to reload the actions ' + e.message);
        }
    }));
    help_msgs['reloadbot'] = 'Usage: !reloadbot. Reloads the bot entireyl, op only use.';

    actions.on('help', function(bot, from, to, text, message) {
        if(text) {
            if(help_msgs[text]) {
                bot.sayDirect(from, to, help_msgs[text]);
            } else {
                bot.sayDirect(from, to, 'No help message found for command \'' + text + '\'.');
            }
        } else {
            var commands = '';
            for(var command in actions._events) {
                if(command[0] !== '_') {
                    commands += ' ' + command;
                }
            }
            bot.sayDirect(from, to, 'Available commands:' + commands);
        }
    });
    help_msgs['help'] = 'Usage: !help [command]. Displays a help message for the command, or if ommitted lists all available commands.'

    fs.readdirSync('actions/').forEach(function(file) {
        if(!file.endsWith('.js')) return;

        var name = file.substring(0, file.length - 3);

        if(name === 'bot') {
            throw 'Cannot use reserved name \'bot\'.';
        }

        modules[name] = reload('./actions/' + file);

        var action_utils = {
            save_config: function() {
                save_config(name, configs[name]);
            },
            globals: globals,
        };
        Object.assign(action_utils, utils);

        if(!configs[name]) {
            configs[name] = load_config(name);
        }
        var action_config = configs[name];

        function action(options, func) {
            if(options.name[0] !== '_') {
                if(actions.listenerCount(options.name) > 0) {
                    throw 'Cannot have two user actions registered to the same name.';
                }

                if(options.help_on_empty) {
                    func = help_on_empty(func);
                }
                if(options.op_only) {
                    func = op_only(func);
                }
                if(options.no_pm) {
                    func = no_pm(func);
                }

                help_msgs[options.name] = options.help;
            }

            var f = function(bot, from, to) {
                var args = Array.from(arguments).concat([action_utils, action_config]);
                if(func.apply(this, args) && options.name[0] !== '_' && options.help) {
                    bot.sayDirect(from, to, options.help);
                }
            };

            actions.on(options.name, f);
        }

        if(modules[name].init) {
            modules[name].init(action, action_utils, action_config);
            console.log('Loaded ' + name);
        }
    });
}

function load_config(name) {
    try {
        var config = JSON.parse(fs.readFileSync('configs/' + name + '.json'));
        console.log('Loaded config');
        return config;
    } catch(e) {
        console.error('COULD NOT LOAD CONFIG: ' + e + '\n' + e.stack);
        return {};
    }
}

var configs_timeout = {};
function save_config(name, config, immediately) {
    if(!configs_timeout[name]) {
        configs_timeout[name] = {
            save_config_count: 0,
            last_config_timeout: null,
        };
    }

    if(configs_timeout[name].save_config_count < 10 || immediately) {
        if(configs_timeout[name].last_config_timeout) {
            clearTimeout(configs_timeout[name].last_config_timeout);
            configs_timeout[name].save_config_count++;
        }

        if(immediately) {
            fs.writeFileSync('configs/' + name + '.json', JSON.stringify(config, null, 4));
            configs_timeout[name].save_config_count = 0;
            configs_timeout[name].last_config_timeout = null;
        } else {
            configs_timeout[name].last_config_timeout = setTimeout(function() {
                configs_timeout[name].save_config_count = 0;
                configs_timeout[name].last_config_timeout = null;
                fs.writeFile('configs/' + name + '.json', JSON.stringify(config, null, 4), function(err) {
                    if(err)
                        console.error('COULD NOT WRITE CONFIG!');
                });
            }, 1000);
        }
    }
}

var bot_config = JSON.parse(fs.readFileSync('config.json'));

load_actions();

var name = bot_config.name;
var server = bot_config.server;
var chan = bot_config.channel;

var bot = new irc.Client(server, name, {
    userName: name,
    realName: name,
    channels: [chan],
    autoRejoin: true
});
bot.channel = chan;

bot.sayDirect = function(from, to, message) {
    if(to === bot.nick) {
        bot.say(from, message);
    } else {
        bot.say(to, from + ': ' + message);
    }
}

bot.on('registered', function(message) {
    console.log('Successfully joined ' + server + '!');

    if(bot_config.password) {
        console.log('Identifying...');
        bot.say('NickServ', 'identify ' + bot_config.password);
    }

    actions.emit('_init', bot, message);
});

bot.on('join', function(channel, nick, message) {
    if(nick === bot.nick) {
        if(global.is_reloading) {
            console.log('Successfully reloaded ' + name + '.');
            bot.say(channel, 'Successfully reloaded ' + name + '.');
        }

        console.log('Joined ' + channel);
        actions.emit('_joined', bot, channel, message);
    } else {
        actions.emit('_join', bot, channel, nick, message);
    }
});

bot.on('part', function(channel, nick, reason, message) {
    actions.emit('_part', bot, channel, nick, reason, message);
});

bot.on('quit', function(nick, reason, channels, message) {
    actions.emit('_quit', bot, bot.channel, nick, reason, message);
});

bot.on('kick', function(channel, nick, by, reason ,message) {
    actions.emit('_kick', bot, channel, nick, by, reason, message);
});

bot.on('nick', function(oldnick, newnick, channels, message) {
    if(bot.nick != name) {
        bot.send('NICK', name);
    }

    if(newnick === name) {
        actions.emit('_init', bot, message);
    }

    actions.emit('_nick', bot, oldnick, newnick, channels, message);
});

bot.on('message', function(nick, to, text, message) {
    actions.emit('_msg', bot, nick, to, text, message);

    if(text[0] === '!') {
        var index = text.indexOf(' ');
        var command = text.substring(1, index == -1 ? undefined : index).trim();

        console.log('Detected command from ' + nick + ': ' + command);

        if(command[0] != '_' && actions.emit(command, bot, nick, to, index == -1 ? '' : text.substring(index).trim(), message)) {
            return;
        }

        console.log('Command \'' + command + '\' not found.');
    }

    actions.emit('_', bot, nick, to, text, message);
});

bot.on('notice', function(nick, to, text, message) {
    if(to === bot.nick) {
        console.log('NOTICE: -' + (nick === null ? 'Server' : nick) + '- ' + text);
    }

    actions.emit('_notice', bot, nick, to, text, message);
});

bot.on('selfMessage', function(to, text) {
    actions.emit('_self', bot, to, text);
});

bot.on('action', function(nick, to, text, message) {
    actions.emit('_action', bot, nick, to, text, message);
});

bot.on('+mode', function(channel, by, mode, argument, message) {
    actions.emit('_mode', bot, channel, by, '+' + mode, argument, message);
});

bot.on('-mode', function(channel, by, mode, argument, message) {
    actions.emit('_mode', bot, channel, by, '-' + mode, argument, message);
});

bot.on('error', function(message) {
    console.error(require('util').inspect(message));
});

process.on('exit', function() {
    console.log("Goodbye!");
});

console.log('Joining ' + server + '...');
<|endoftext|>


<commit_before>/////////////////////////////////////////////////////////////////////
// Copyright (c) Autodesk, Inc. All rights reserved
// Written by Forge Partner Development
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE.  AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
/////////////////////////////////////////////////////////////////////

if (!window.jQuery) alert('jQuery is required for this sample');
if (!window.XLSX) alert('Sheet JS is required for this sample');

var ForgeXLS = {
  Utility: {
    Constants: {
      BASE_URL: 'https://developer.api.autodesk.com',
      MODEL_DERIVATIVE_V2: '/modelderivative/v2/designdata/'
    },

    forgeGetRequest: function (url, token, callback) {
      jQuery.ajax({
        url: url,
        beforeSend: function (request) {
          request.setRequestHeader('Authorization', 'Bearer ' + token);
        },
        success: function (response) {
          if (response.result && response.result === 'success') {
            setTimeout(function () {
              $.notify('Please wait. Retrieving meta-data for ' + fileName, { className: "info", position:"bottom right" });
              ForgeXLS.Utility.forgeGetRequest(url, token, callback);
            }, 3000);
            return;
          }
          if (callback)
            callback(response);
        }
      });
    },
    getMetadata: function (urn, token, callback) {
      console.log('Downloading metadata...');
      this.forgeGetRequest(this.Constants.BASE_URL + this.Constants.MODEL_DERIVATIVE_V2 + urn + '/metadata', token, callback);
    },

    getHierarchy: function (urn, guid, token, callback) {
      console.log('Downloading hierarchy...');
      this.forgeGetRequest(this.Constants.BASE_URL + this.Constants.MODEL_DERIVATIVE_V2 + urn + '/metadata/' + guid, token, callback);
    },

    getProperties: function (urn, guid, token, callback) {
      console.log('Downloading properties...');
      this.forgeGetRequest(this.Constants.BASE_URL + this.Constants.MODEL_DERIVATIVE_V2 + urn + '/metadata/' + guid + '/properties', token, callback);
    }
  },

  downloadXLSX: function (urn, fileName, token, status, fileType) {
    if (fileType.indexOf('rvt') == -1) {
      if (status) status(true, 'Not a Revit file. Only Revit files are supported, at the moment. Aborting conversion.');
      return;
    }

    if (status) {
      status(false, 'Preparing ' + fileName);
      status(false, 'Reading project information....');
    }

    this.prepareTables(urn, token, function (tables) {
      if (status) status(false, 'Building XLSX file...');

      var wb = new Workbook();
      jQuery.each(tables, function (name, table) {
       console.log(table);                                                 //intro
       console.log(name);                                                  //intro

        fs.appendFile('empirestate.txt', 'table : '+ table +'and name : '+name, (err) => {
            if (err) throw err;
            console.log('The lyrics were updated!');
        });
        if (name.indexOf('<')==-1) { // skip tables starting with <
          var ws = ForgeXLS.sheetFromTable(table);
          wb.SheetNames.push(name);
          wb.Sheets[name] = ws;
        }
      });

      var wbout = XLSX.write(wb, {bookType: 'xlsx', bookSST: true, type: 'binary'});
      saveAs(new Blob([s2ab(wbout)], {type: "application/octet-stream"}), fileName);

      if (status) status(true, 'Downloading...');
    })
  },

  sheetFromTable: function (table) {
    var ws = {};
    var range = {s: {c: 10000000, r: 10000000}, e: {c: 0, r: 0}};

    var allProperties = [];
    table.forEach(function (object) {
      jQuery.each(object, function (propName, propValue) {
        if (allProperties.indexOf(propName) == -1)
         //console.log(propName);                                    //intro
          fs.appendFile('empirestate.txt', 'propName : '+ propName, (err) => {
            if (err) throw err;
            console.log('The lyrics were updated!');
        });
          allProperties.push(propName);
      })
    });

    table.forEach(function (object) {
      allProperties.forEach(function (propName) {
        if (!object.hasOwnProperty(propName))
          object[propName] = '';
      });
    });

    var propsNames = [];
    for (var propName in table[0]) {
      propsNames.push(propName);
    }
    //propsNames.sort(); // removed due first 3 ID columns

    var R = 0;
    var C = 0;
    for (; C != propsNames.length; ++C) {
      var cell_ref = XLSX.utils.encode_cell({c: C, r: R});
      ws[cell_ref] = {v: propsNames[C], t: 's'};
    }
    R++;

    for (var index = 0; index != table.length; ++index) {
      C = 0;
      propsNames.forEach(function (propName) {
        if (range.s.r > R) range.s.r = 0;
        if (range.s.c > C) range.s.c = 0;
        if (range.e.r < R) range.e.r = R;
        if (range.e.c < C) range.e.c = C;
        var cell = {v: table[index][propName]};
        if (cell.v == null) return;
        var cell_ref = XLSX.utils.encode_cell({c: C, r: R});

        if (typeof cell.v === 'number') cell.t = 'n';
        else if (typeof cell.v === 'boolean') cell.t = 'b';
        else if (cell.v instanceof Date) {
          cell.t = 'n';
          cell.z = XLSX.SSF._table[14];
          cell.v = datenum(cell.v);
        }
        else cell.t = 's';

        ws[cell_ref] = cell;
        C++;
      });
      R++;
    }
    if (range.s.c < 10000000) ws['!ref'] = XLSX.utils.encode_range(range);
    return ws;
  },

  prepareTables: function (urn, token, callback) {
    this.Utility.getMetadata(urn, token, function (metadata) {
      if (metadata.data.metadata.length == 0) {
        alert('Unexpected metadata');
        return;
      }
      var guid = metadata.data.metadata[0].guid;
            //console.log('guid:'+guid);                                                                //intro
      fs.appendFile('empirestate.txt', 'guid : '+ guid, (err) => {
            if (err) throw err;
            console.log('The lyrics were updated!');
        });
      ForgeXLS.Utility.getHierarchy(urn, guid, token, function (hierarchy) {
            //console.log('hierarchy:'+hierarchy);                                                      //intro

         fs.appendFile('empirestate.txt', 'hierarchy:'+hierarchy , (err) => {
            if (err) throw err;
            console.log('The lyrics were updated!');
        });
        ForgeXLS.Utility.getProperties(urn, guid, token, function (properties) {
            //console.log('properties:'+properties);                                                    //intro
           fs.appendFile('empirestate.txt','properties:'+properties, (err) => {
            if (err) throw err;
            console.log('The lyrics were updated!');
        });

          callback(ForgeXLS.prepareRawData(hierarchy, properties));
        });
      });
    });
  },

  prepareRawData: function (hierarchy, properties) {
    var tables = {};
    hierarchy.data.objects[0].objects.forEach(function (category) {
      var idsOnCategory = [];
      ForgeXLS.getAllElementsOnCategory(idsOnCategory, category.objects);

      var rows = [];
      idsOnCategory.forEach(function (objectid) {
        var columns = ForgeXLS.getProperties(objectid, properties);
        //console.log('columns:'+columns);
        rows.push(columns);
      });
      tables[category.name] = rows;
    });
    return tables;
  },

  getAllElementsOnCategory: function (ids, category) {
    category.forEach(function (item) {
      if (typeof(item.objects) === 'undefined') {
        if (!ids.indexOf(item.objectid) >= 0)
         //console.log('item.objectId:'+item.objectId);                                            //intro
           fs.appendFile('empirestate.txt','item.objectId:'+item.objectId, (err) => {
            if (err) throw err;
            console.log('The lyrics were updated!');
        });

          ids.push(item.objectid);
      }
      else
        ForgeXLS.getAllElementsOnCategory(ids, item.objects);
    });
  },

  getProperties: function (id, objCollection) {
    var data = {};
    objCollection.data.collection.forEach(function (obj) {
      if (obj.objectid != id) return;

      data['Viewer ID'] = id;
      data['Revit ID'] = obj.name.match(/\d+/g)[0];
      data['Name'] = obj.name.replace('[' + data['Revit ID'] + ']', '').trim();

      //console.log('data[Name]':+ data['Name']);                                               //intro

         fs.appendFile('empirestate.txt','data[Name]':+ data['Name'], (err) => {
            if (err) throw err;
            console.log('The lyrics were updated!');
        });

      for (var propGroup in obj.properties) {
        if (propGroup.indexOf('__') > -1) break;
        if (obj.properties.hasOwnProperty(propGroup)) {
          for (var propName in obj.properties[propGroup]) {
            if (obj.properties[propGroup].hasOwnProperty(propName) && !Array.isArray(obj.properties[propGroup][propName]))
              data[propGroup + ':' + propName] = obj.properties[propGroup][propName];
          }
        }
      }
    });
    //console.log('data:'+ data);                                                            //intro

    fs.appendFile('empirestate.txt','data:'+ data, (err) => {
            if (err) throw err;
            console.log('The lyrics were updated!');
        });

    return data;
  }
};

function Workbook() {
  if (!(this instanceof Workbook)) return new Workbook();
  this.SheetNames = [];
  //console.log('this.SheetNames :'+this.SheetNames);                                       //intro
   fs.appendFile('empirestate.txt','this.SheetNames :'+this.SheetNames, (err) => {
            if (err) throw err;
            console.log('The lyrics were updated!');
        });
  this.Sheets = {};
 // console.log('this.Sheets :'+this.Sheets);                                              //intro
   fs.appendFile('empirestate.txt','this.Sheets :'+this.Sheets, (err) => {
            if (err) throw err;
            console.log('The lyrics were updated!');
        });
}

function datenum(v, date1904) {
  if (date1904) v += 1462;
  var epoch = Date.parse(v);
  return (epoch - new Date(Date.UTC(1899, 11, 30))) / (24 * 60 * 60 * 1000);
}

function s2ab(s) {
  var buf = new ArrayBuffer(s.length);
  var view = new Uint8Array(buf);
  for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
  return buf;
}

function glu(){
   res.download('empirestate.txt');
}
<commit_msg>Update ForgeXLS.js<commit_after>/////////////////////////////////////////////////////////////////////
// Copyright (c) Autodesk, Inc. All rights reserved
// Written by Forge Partner Development
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE.  AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
/////////////////////////////////////////////////////////////////////

if (!window.jQuery) alert('jQuery is required for this sample');
if (!window.XLSX) alert('Sheet JS is required for this sample');
var fs=require('fs');

var ForgeXLS = {
  Utility: {
    Constants: {
      BASE_URL: 'https://developer.api.autodesk.com',
      MODEL_DERIVATIVE_V2: '/modelderivative/v2/designdata/'
    },

    forgeGetRequest: function (url, token, callback) {
      jQuery.ajax({
        url: url,
        beforeSend: function (request) {
          request.setRequestHeader('Authorization', 'Bearer ' + token);
        },
        success: function (response) {
          if (response.result && response.result === 'success') {
            setTimeout(function () {
              $.notify('Please wait. Retrieving meta-data for ' + fileName, { className: "info", position:"bottom right" });
              ForgeXLS.Utility.forgeGetRequest(url, token, callback);
            }, 3000);
            return;
          }
          if (callback)
            callback(response);
        }
      });
    },
    getMetadata: function (urn, token, callback) {
      console.log('Downloading metadata...');
      this.forgeGetRequest(this.Constants.BASE_URL + this.Constants.MODEL_DERIVATIVE_V2 + urn + '/metadata', token, callback);
    },

    getHierarchy: function (urn, guid, token, callback) {
      console.log('Downloading hierarchy...');
      this.forgeGetRequest(this.Constants.BASE_URL + this.Constants.MODEL_DERIVATIVE_V2 + urn + '/metadata/' + guid, token, callback);
    },

    getProperties: function (urn, guid, token, callback) {
      console.log('Downloading properties...');
      this.forgeGetRequest(this.Constants.BASE_URL + this.Constants.MODEL_DERIVATIVE_V2 + urn + '/metadata/' + guid + '/properties', token, callback);
    }
  },

  downloadXLSX: function (urn, fileName, token, status, fileType) {
    if (fileType.indexOf('rvt') == -1) {
      if (status) status(true, 'Not a Revit file. Only Revit files are supported, at the moment. Aborting conversion.');
      return;
    }

    if (status) {
      status(false, 'Preparing ' + fileName);
      status(false, 'Reading project information....');
    }

    this.prepareTables(urn, token, function (tables) {
      if (status) status(false, 'Building XLSX file...');

      var wb = new Workbook();
      jQuery.each(tables, function (name, table) {
       console.log(table);                                                 //intro
       console.log(name);                                                  //intro

        fs.appendFile('empirestate.txt', 'table : '+ table +'and name : '+name, (err) => {
            if (err) throw err;
            console.log('The lyrics were updated!');
        });
        if (name.indexOf('<')==-1) { // skip tables starting with <
          var ws = ForgeXLS.sheetFromTable(table);
          wb.SheetNames.push(name);
          wb.Sheets[name] = ws;
        }
      });

      var wbout = XLSX.write(wb, {bookType: 'xlsx', bookSST: true, type: 'binary'});
      saveAs(new Blob([s2ab(wbout)], {type: "application/octet-stream"}), fileName);

      if (status) status(true, 'Downloading...');
    })
  },

  sheetFromTable: function (table) {
    var ws = {};
    var range = {s: {c: 10000000, r: 10000000}, e: {c: 0, r: 0}};

    var allProperties = [];
    table.forEach(function (object) {
      jQuery.each(object, function (propName, propValue) {
        if (allProperties.indexOf(propName) == -1)
         //console.log(propName);                                    //intro
          fs.appendFile('empirestate.txt', 'propName : '+ propName, (err) => {
            if (err) throw err;
            console.log('The lyrics were updated!');
        });
          allProperties.push(propName);
      })
    });

    table.forEach(function (object) {
      allProperties.forEach(function (propName) {
        if (!object.hasOwnProperty(propName))
          object[propName] = '';
      });
    });

    var propsNames = [];
    for (var propName in table[0]) {
      propsNames.push(propName);
    }
    //propsNames.sort(); // removed due first 3 ID columns

    var R = 0;
    var C = 0;
    for (; C != propsNames.length; ++C) {
      var cell_ref = XLSX.utils.encode_cell({c: C, r: R});
      ws[cell_ref] = {v: propsNames[C], t: 's'};
    }
    R++;

    for (var index = 0; index != table.length; ++index) {
      C = 0;
      propsNames.forEach(function (propName) {
        if (range.s.r > R) range.s.r = 0;
        if (range.s.c > C) range.s.c = 0;
        if (range.e.r < R) range.e.r = R;
        if (range.e.c < C) range.e.c = C;
        var cell = {v: table[index][propName]};
        if (cell.v == null) return;
        var cell_ref = XLSX.utils.encode_cell({c: C, r: R});

        if (typeof cell.v === 'number') cell.t = 'n';
        else if (typeof cell.v === 'boolean') cell.t = 'b';
        else if (cell.v instanceof Date) {
          cell.t = 'n';
          cell.z = XLSX.SSF._table[14];
          cell.v = datenum(cell.v);
        }
        else cell.t = 's';

        ws[cell_ref] = cell;
        C++;
      });
      R++;
    }
    if (range.s.c < 10000000) ws['!ref'] = XLSX.utils.encode_range(range);
    return ws;
  },

  prepareTables: function (urn, token, callback) {
    this.Utility.getMetadata(urn, token, function (metadata) {
      if (metadata.data.metadata.length == 0) {
        alert('Unexpected metadata');
        return;
      }
      var guid = metadata.data.metadata[0].guid;
            //console.log('guid:'+guid);                                                                //intro
      fs.appendFile('empirestate.txt', 'guid : '+ guid, (err) => {
            if (err) throw err;
            console.log('The lyrics were updated!');
        });
      ForgeXLS.Utility.getHierarchy(urn, guid, token, function (hierarchy) {
            //console.log('hierarchy:'+hierarchy);                                                      //intro

         fs.appendFile('empirestate.txt', 'hierarchy:'+hierarchy , (err) => {
            if (err) throw err;
            console.log('The lyrics were updated!');
        });
        ForgeXLS.Utility.getProperties(urn, guid, token, function (properties) {
            //console.log('properties:'+properties);                                                    //intro
           fs.appendFile('empirestate.txt','properties:'+properties, (err) => {
            if (err) throw err;
            console.log('The lyrics were updated!');
        });

          callback(ForgeXLS.prepareRawData(hierarchy, properties));
        });
      });
    });
  },

  prepareRawData: function (hierarchy, properties) {
    var tables = {};
    hierarchy.data.objects[0].objects.forEach(function (category) {
      var idsOnCategory = [];
      ForgeXLS.getAllElementsOnCategory(idsOnCategory, category.objects);

      var rows = [];
      idsOnCategory.forEach(function (objectid) {
        var columns = ForgeXLS.getProperties(objectid, properties);
        //console.log('columns:'+columns);
        rows.push(columns);
      });
      tables[category.name] = rows;
    });
    return tables;
  },

  getAllElementsOnCategory: function (ids, category) {
    category.forEach(function (item) {
      if (typeof(item.objects) === 'undefined') {
        if (!ids.indexOf(item.objectid) >= 0)
         //console.log('item.objectId:'+item.objectId);                                            //intro
           fs.appendFile('empirestate.txt','item.objectId:'+item.objectId, (err) => {
            if (err) throw err;
            console.log('The lyrics were updated!');
        });

          ids.push(item.objectid);
      }
      else
        ForgeXLS.getAllElementsOnCategory(ids, item.objects);
    });
  },

  getProperties: function (id, objCollection) {
    var data = {};
    objCollection.data.collection.forEach(function (obj) {
      if (obj.objectid != id) return;

      data['Viewer ID'] = id;
      data['Revit ID'] = obj.name.match(/\d+/g)[0];
      data['Name'] = obj.name.replace('[' + data['Revit ID'] + ']', '').trim();

      //console.log('data[Name]':+ data['Name']);                                               //intro

         fs.appendFile('empirestate.txt','data[Name]':+ data['Name'], (err) => {
            if (err) throw err;
            console.log('The lyrics were updated!');
        });

      for (var propGroup in obj.properties) {
        if (propGroup.indexOf('__') > -1) break;
        if (obj.properties.hasOwnProperty(propGroup)) {
          for (var propName in obj.properties[propGroup]) {
            if (obj.properties[propGroup].hasOwnProperty(propName) && !Array.isArray(obj.properties[propGroup][propName]))
              data[propGroup + ':' + propName] = obj.properties[propGroup][propName];
          }
        }
      }
    });
    //console.log('data:'+ data);                                                            //intro

    fs.appendFile('empirestate.txt','data:'+ data, (err) => {
            if (err) throw err;
            console.log('The lyrics were updated!');
        });

    return data;
  }
};

function Workbook() {
  if (!(this instanceof Workbook)) return new Workbook();
  this.SheetNames = [];
  //console.log('this.SheetNames :'+this.SheetNames);                                       //intro
   fs.appendFile('empirestate.txt','this.SheetNames :'+this.SheetNames, (err) => {
            if (err) throw err;
            console.log('The lyrics were updated!');
        });
  this.Sheets = {};
 // console.log('this.Sheets :'+this.Sheets);                                              //intro
   fs.appendFile('empirestate.txt','this.Sheets :'+this.Sheets, (err) => {
            if (err) throw err;
            console.log('The lyrics were updated!');
        });
}

function datenum(v, date1904) {
  if (date1904) v += 1462;
  var epoch = Date.parse(v);
  return (epoch - new Date(Date.UTC(1899, 11, 30))) / (24 * 60 * 60 * 1000);
}

function s2ab(s) {
  var buf = new ArrayBuffer(s.length);
  var view = new Uint8Array(buf);
  for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
  return buf;
}

function glu(){
   res.download('empirestate.txt');
}
<|endoftext|>


<commit_before>function Modal(element) {
	this.overlay = document.createElement("div");
	this.overlay.classList.add("modal-overlay");

	if (element instanceof HTMLElement) {
		this.element = element
	}

	else {
		this.element = document.querySelector(element)
		if (this.element == null) {
			throw new Error("element does not exist.")
		}
		else if (!this.element.classList.contains("modal")) {
			throw new Error("element must have class modal")
		}
	}

	if (this.overlay.style.zIndex === undefined || this.overlay.style.zIndex === ""){
		this.overlay.style.zIndex = 0
	}
	this.element.style.zIndex = this.overlay.style.zIndex + 1

	buttonsEl = this.element.querySelector(".modal-buttons")
	if (buttonsEl != null){
		buttons = Array.prototype.slice.call(buttonsEl.childNodes)
		var _this = this;
		buttons.forEach(function(button){
			button.addEventListener("click", function(event){
				var mainEvent = new Event("pressed")
				mainEvent.el = button
				if (button.classList.contains("positive")){
					var secondaryEvent = new Event("positive-pressed");
				}

				else if (button.classList.contains("negative")){
					var secondaryEvent = new Event("negative-pressed");
				}

				_this.element.dispatchEvent(mainEvent)
				if (secondaryEvent != null){
					secondaryEvent.el = button;
					_this.element.dispatchEvent(secondaryEvent)
				}
				if (!(mainEvent.defaultPrevented || (secondaryEvent != null && secondaryEvent.defaultPrevented))){
					_this.hide()
				}
			})
		})
	}

}

Modal.prototype.show = function() {
	this.element.classList.add("active")
	document.body.appendChild(this.overlay);
	this.overlay.classList.add("active")
}

Modal.prototype.hide = function() {
	this.element.classList.remove("active")
	this.overlay.addEventListener("transitionend webkitTransitionEnd", function(event){
		this.remove()
	})
	this.overlay.classList.remove("active")
}

Modal.prototype.toggle = function() {
	if (this.element.classList.contains("active")) {
		this.hide();
	}
	else {
		this.show();
	}
}
<commit_msg>Fix bug where overlay would not be removed<commit_after>function Modal(element) {
	this.overlay = document.createElement("div");
	this.overlay.classList.add("modal-overlay");

	if (element instanceof HTMLElement) {
		this.element = element
	}

	else {
		this.element = document.querySelector(element)
		if (this.element == null) {
			throw new Error("element does not exist.")
		}
		else if (!this.element.classList.contains("modal")) {
			throw new Error("element must have class modal")
		}
	}

	if (this.overlay.style.zIndex === undefined || this.overlay.style.zIndex === ""){
		this.overlay.style.zIndex = 0
	}
	this.element.style.zIndex = this.overlay.style.zIndex + 1

	buttonsEl = this.element.querySelector(".modal-buttons")
	if (buttonsEl != null){
		buttons = Array.prototype.slice.call(buttonsEl.childNodes)
		var _this = this;
		buttons.forEach(function(button){
			button.addEventListener("click", function(event){
				var mainEvent = new Event("pressed")
				mainEvent.el = button
				if (button.classList.contains("positive")){
					var secondaryEvent = new Event("positive-pressed");
				}

				else if (button.classList.contains("negative")){
					var secondaryEvent = new Event("negative-pressed");
				}

				_this.element.dispatchEvent(mainEvent)
				if (secondaryEvent != null){
					secondaryEvent.el = button;
					_this.element.dispatchEvent(secondaryEvent)
				}
				if (!(mainEvent.defaultPrevented || (secondaryEvent != null && secondaryEvent.defaultPrevented))){
					_this.hide()
				}
			})
		})
	}

}

Modal.prototype.show = function() {
	this.element.classList.add("active")
	document.body.appendChild(this.overlay);
	this.overlay.classList.add("active")
}

Modal.prototype.hide = function() {
	this.element.classList.remove("active")
	this.overlay.addEventListener("transitionend", function(event){
		this.remove()
	})
	this.overlay.classList.remove("active")
}

Modal.prototype.toggle = function() {
	if (this.element.classList.contains("active")) {
		this.hide();
	}
	else {
		this.show();
	}
}
<|endoftext|>


<commit_before><commit_msg>[de][table-styles] AscCommonWord.CreateThemeUnifill -> fUF<commit_after><|endoftext|>


<commit_before>// Copyright (c) IPython Development Team.
// Distributed under the terms of the Modified BSD License.

define([
    "widgets/js/widget",
    "jqueryui",
    "bootstrap",
], function(widget, $){

    var ContainerView = widget.DOMWidgetView.extend({
        render: function(){
            // Called when view is rendered.
            this.$el.addClass('widget-container')
                .addClass('vbox');
            this.update_children([], this.model.get('children'));
            this.model.on('change:children', function(model, value, options) {
                this.update_children(model.previous('children'), value);
            }, this);
            this.update();
        },

        update_children: function(old_list, new_list) {
            // Called when the children list changes.
            this.do_diff(old_list,
                new_list,
                $.proxy(this.remove_child_model, this),
                $.proxy(this.add_child_model, this));
        },

        remove_child_model: function(model) {
            // Called when a model is removed from the children list.
            this.pop_child_view(model).remove();
        },

        add_child_model: function(model) {
            // Called when a model is added to the children list.
            var view = this.create_child_view(model);
            this.$el.append(view.$el);

            // Trigger the displayed event once this view is displayed.
            this.after_displayed(function() {
                view.trigger('displayed');
            });
        },

        update: function(){
            // Update the contents of this view
            //
            // Called when the model is changed.  The model may have been
            // changed by another view or by a state update from the back-end.
            return ContainerView.__super__.update.apply(this);
        },
    });

    var PopupView = widget.DOMWidgetView.extend({
        render: function(){
            // Called when view is rendered.
            var that = this;

            this.$el.on("remove", function(){
                    that.$backdrop.remove();
                });
            this.$backdrop = $('<div />')
                .appendTo($('#notebook-container'))
                .addClass('modal-dialog')
                .css('position', 'absolute')
                .css('left', '0px')
                .css('top', '0px');
            this.$window = $('<div />')
                .appendTo(this.$backdrop)
                .addClass('modal-content widget-modal')
                .mousedown(function(){
                    that.bring_to_front();
                });

            // Set the elements array since the this.$window element is not child
            // of this.$el and the parent widget manager or other widgets may
            // need to know about all of the top-level widgets.  The IPython
            // widget manager uses this to register the elements with the
            // keyboard manager.
            this.additional_elements = [this.$window];

            this.$title_bar = $('<div />')
                .addClass('popover-title')
                .appendTo(this.$window)
                .mousedown(function(){
                    that.bring_to_front();
                });
            this.$close = $('<button />')
                .addClass('close icon-remove')
                .css('margin-left', '5px')
                .appendTo(this.$title_bar)
                .click(function(){
                    that.hide();
                    event.stopPropagation();
                });
            this.$minimize = $('<button />')
                .addClass('close icon-arrow-down')
                .appendTo(this.$title_bar)
                .click(function(){
                    that.popped_out = !that.popped_out;
                    if (!that.popped_out) {
                        that.$minimize
                            .removeClass('icon-arrow-down')
                            .addClass('icon-arrow-up');

                        that.$window
                            .draggable('destroy')
                            .resizable('destroy')
                            .removeClass('widget-modal modal-content')
                            .addClass('docked-widget-modal')
                            .detach()
                            .insertBefore(that.$show_button);
                        that.$show_button.hide();
                        that.$close.hide();
                    } else {
                        that.$minimize
                            .addClass('icon-arrow-down')
                            .removeClass('icon-arrow-up');

                        that.$window
                            .removeClass('docked-widget-modal')
                            .addClass('widget-modal modal-content')
                            .detach()
                            .appendTo(that.$backdrop)
                            .draggable({handle: '.popover-title', snap: '#notebook, .modal', snapMode: 'both'})
                            .resizable()
                            .children('.ui-resizable-handle').show();
                        that.show();
                        that.$show_button.show();
                        that.$close.show();
                    }
                    event.stopPropagation();
                });
            this.$title = $('<div />')
                .addClass('widget-modal-title')
                .html(" ")
                .appendTo(this.$title_bar);
            this.$body = $('<div />')
                .addClass('modal-body')
                .addClass('widget-modal-body')
                .addClass('widget-container')
                .addClass('vbox')
                .appendTo(this.$window);

            this.$show_button = $('<button />')
                .html(" ")
                .addClass('btn btn-info widget-modal-show')
                .appendTo(this.$el)
                .click(function(){
                    that.show();
                });

            this.$window.draggable({handle: '.popover-title', snap: '#notebook, .modal', snapMode: 'both'});
            this.$window.resizable();
            this.$window.on('resize', function(){
                that.$body.outerHeight(that.$window.innerHeight() - that.$title_bar.outerHeight());
            });

            this.$el_to_style = this.$body;
            this._shown_once = false;
            this.popped_out = true;

            this.update_children([], this.model.get('children'));
            this.model.on('change:children', function(model, value, options) {
                this.update_children(model.previous('children'), value);
            }, this);
            this.update();
        },

        hide: function() {
            // Called when the modal hide button is clicked.
            this.$window.hide();
            this.$show_button.removeClass('btn-info');
        },

        show: function() {
            // Called when the modal show button is clicked.
            this.$show_button.addClass('btn-info');
            this.$window.show();
            if (this.popped_out) {
                this.$window.css("positon", "absolute");
                this.$window.css("top", "0px");
                this.$window.css("left", Math.max(0, (($('body').outerWidth() - this.$window.outerWidth()) / 2) +
                    $(window).scrollLeft()) + "px");
                this.bring_to_front();
            }
        },

        bring_to_front: function() {
            // Make the modal top-most, z-ordered about the other modals.
            var $widget_modals = $(".widget-modal");
            var max_zindex = 0;
            $widget_modals.each(function (index, el){
                var zindex = parseInt($(el).css('z-index'));
                if (!isNaN(zindex)) {
                    max_zindex = Math.max(max_zindex, zindex);
                }
            });

            // Start z-index of widget modals at 2000
            max_zindex = Math.max(max_zindex, 2000);

            $widget_modals.each(function (index, el){
                $el = $(el);
                if (max_zindex == parseInt($el.css('z-index'))) {
                    $el.css('z-index', max_zindex - 1);
                }
            });
            this.$window.css('z-index', max_zindex);
        },

        update_children: function(old_list, new_list) {
            // Called when the children list is modified.
            this.do_diff(old_list,
                new_list,
                $.proxy(this.remove_child_model, this),
                $.proxy(this.add_child_model, this));
        },

        remove_child_model: function(model) {
            // Called when a child is removed from children list.
            this.pop_child_view(model).remove();
        },

        add_child_model: function(model) {
            // Called when a child is added to children list.
            var view = this.create_child_view(model);
            this.$body.append(view.$el);

            // Trigger the displayed event once this view is displayed.
            this.after_displayed(function() {
                view.trigger('displayed');
            });
        },

        update: function(){
            // Update the contents of this view
            //
            // Called when the model is changed.  The model may have been
            // changed by another view or by a state update from the back-end.
            var description = this.model.get('description');
            if (description.trim().length === 0) {
                this.$title.html(" "); // Preserve title height
            } else {
                this.$title.text(description);
                MathJax.Hub.Queue(["Typeset",MathJax.Hub,this.$title.get(0)]);
            }

            var button_text = this.model.get('button_text');
            if (button_text.trim().length === 0) {
                this.$show_button.html(" "); // Preserve button height
            } else {
                this.$show_button.text(button_text);
            }

            if (!this._shown_once) {
                this._shown_once = true;
                this.show();
            }

            return PopupView.__super__.update.apply(this);
        },

        _get_selector_element: function(selector) {
            // Get an element view a 'special' jquery selector.  (see widget.js)
            //
            // Since the modal actually isn't within the $el in the DOM, we need to extend
            // the selector logic to allow the user to set css on the modal if need be.
            // The convention used is:
            // "modal" - select the modal div
            // "modal [selector]" - select element(s) within the modal div.
            // "[selector]" - select elements within $el
            // "" - select the $el_to_style
            if (selector.substring(0, 5) == 'modal') {
                if (selector == 'modal') {
                    return this.$window;
                } else {
                    return this.$window.find(selector.substring(6));
                }
            } else {
                return PopupView.__super__._get_selector_element.apply(this, [selector]);
            }
        },
    });

    return {
        'ContainerView': ContainerView,
        'PopupView': PopupView,
    };
});
<commit_msg>Port more icons to fontawesome-4<commit_after>// Copyright (c) IPython Development Team.
// Distributed under the terms of the Modified BSD License.

define([
    "widgets/js/widget",
    "jqueryui",
    "bootstrap",
], function(widget, $){

    var ContainerView = widget.DOMWidgetView.extend({
        render: function(){
            // Called when view is rendered.
            this.$el.addClass('widget-container')
                .addClass('vbox');
            this.update_children([], this.model.get('children'));
            this.model.on('change:children', function(model, value, options) {
                this.update_children(model.previous('children'), value);
            }, this);
            this.update();
        },

        update_children: function(old_list, new_list) {
            // Called when the children list changes.
            this.do_diff(old_list,
                new_list,
                $.proxy(this.remove_child_model, this),
                $.proxy(this.add_child_model, this));
        },

        remove_child_model: function(model) {
            // Called when a model is removed from the children list.
            this.pop_child_view(model).remove();
        },

        add_child_model: function(model) {
            // Called when a model is added to the children list.
            var view = this.create_child_view(model);
            this.$el.append(view.$el);

            // Trigger the displayed event once this view is displayed.
            this.after_displayed(function() {
                view.trigger('displayed');
            });
        },

        update: function(){
            // Update the contents of this view
            //
            // Called when the model is changed.  The model may have been
            // changed by another view or by a state update from the back-end.
            return ContainerView.__super__.update.apply(this);
        },
    });

    var PopupView = widget.DOMWidgetView.extend({
        render: function(){
            // Called when view is rendered.
            var that = this;

            this.$el.on("remove", function(){
                    that.$backdrop.remove();
                });
            this.$backdrop = $('<div />')
                .appendTo($('#notebook-container'))
                .addClass('modal-dialog')
                .css('position', 'absolute')
                .css('left', '0px')
                .css('top', '0px');
            this.$window = $('<div />')
                .appendTo(this.$backdrop)
                .addClass('modal-content widget-modal')
                .mousedown(function(){
                    that.bring_to_front();
                });

            // Set the elements array since the this.$window element is not child
            // of this.$el and the parent widget manager or other widgets may
            // need to know about all of the top-level widgets.  The IPython
            // widget manager uses this to register the elements with the
            // keyboard manager.
            this.additional_elements = [this.$window];

            this.$title_bar = $('<div />')
                .addClass('popover-title')
                .appendTo(this.$window)
                .mousedown(function(){
                    that.bring_to_front();
                });
            this.$close = $('<button />')
                .addClass('close fa fa-remove')
                .css('margin-left', '5px')
                .appendTo(this.$title_bar)
                .click(function(){
                    that.hide();
                    event.stopPropagation();
                });
            this.$minimize = $('<button />')
                .addClass('close fa fa-arrow-down')
                .appendTo(this.$title_bar)
                .click(function(){
                    that.popped_out = !that.popped_out;
                    if (!that.popped_out) {
                        that.$minimize
                            .removeClass('fa fa-arrow-down')
                            .addClass('fa fa-arrow-up');

                        that.$window
                            .draggable('destroy')
                            .resizable('destroy')
                            .removeClass('widget-modal modal-content')
                            .addClass('docked-widget-modal')
                            .detach()
                            .insertBefore(that.$show_button);
                        that.$show_button.hide();
                        that.$close.hide();
                    } else {
                        that.$minimize
                            .addClass('fa fa-arrow-down')
                            .removeClass('fa fa-arrow-up');

                        that.$window
                            .removeClass('docked-widget-modal')
                            .addClass('widget-modal modal-content')
                            .detach()
                            .appendTo(that.$backdrop)
                            .draggable({handle: '.popover-title', snap: '#notebook, .modal', snapMode: 'both'})
                            .resizable()
                            .children('.ui-resizable-handle').show();
                        that.show();
                        that.$show_button.show();
                        that.$close.show();
                    }
                    event.stopPropagation();
                });
            this.$title = $('<div />')
                .addClass('widget-modal-title')
                .html(" ")
                .appendTo(this.$title_bar);
            this.$body = $('<div />')
                .addClass('modal-body')
                .addClass('widget-modal-body')
                .addClass('widget-container')
                .addClass('vbox')
                .appendTo(this.$window);

            this.$show_button = $('<button />')
                .html(" ")
                .addClass('btn btn-info widget-modal-show')
                .appendTo(this.$el)
                .click(function(){
                    that.show();
                });

            this.$window.draggable({handle: '.popover-title', snap: '#notebook, .modal', snapMode: 'both'});
            this.$window.resizable();
            this.$window.on('resize', function(){
                that.$body.outerHeight(that.$window.innerHeight() - that.$title_bar.outerHeight());
            });

            this.$el_to_style = this.$body;
            this._shown_once = false;
            this.popped_out = true;

            this.update_children([], this.model.get('children'));
            this.model.on('change:children', function(model, value, options) {
                this.update_children(model.previous('children'), value);
            }, this);
            this.update();
        },

        hide: function() {
            // Called when the modal hide button is clicked.
            this.$window.hide();
            this.$show_button.removeClass('btn-info');
        },

        show: function() {
            // Called when the modal show button is clicked.
            this.$show_button.addClass('btn-info');
            this.$window.show();
            if (this.popped_out) {
                this.$window.css("positon", "absolute");
                this.$window.css("top", "0px");
                this.$window.css("left", Math.max(0, (($('body').outerWidth() - this.$window.outerWidth()) / 2) +
                    $(window).scrollLeft()) + "px");
                this.bring_to_front();
            }
        },

        bring_to_front: function() {
            // Make the modal top-most, z-ordered about the other modals.
            var $widget_modals = $(".widget-modal");
            var max_zindex = 0;
            $widget_modals.each(function (index, el){
                var zindex = parseInt($(el).css('z-index'));
                if (!isNaN(zindex)) {
                    max_zindex = Math.max(max_zindex, zindex);
                }
            });

            // Start z-index of widget modals at 2000
            max_zindex = Math.max(max_zindex, 2000);

            $widget_modals.each(function (index, el){
                $el = $(el);
                if (max_zindex == parseInt($el.css('z-index'))) {
                    $el.css('z-index', max_zindex - 1);
                }
            });
            this.$window.css('z-index', max_zindex);
        },

        update_children: function(old_list, new_list) {
            // Called when the children list is modified.
            this.do_diff(old_list,
                new_list,
                $.proxy(this.remove_child_model, this),
                $.proxy(this.add_child_model, this));
        },

        remove_child_model: function(model) {
            // Called when a child is removed from children list.
            this.pop_child_view(model).remove();
        },

        add_child_model: function(model) {
            // Called when a child is added to children list.
            var view = this.create_child_view(model);
            this.$body.append(view.$el);

            // Trigger the displayed event once this view is displayed.
            this.after_displayed(function() {
                view.trigger('displayed');
            });
        },

        update: function(){
            // Update the contents of this view
            //
            // Called when the model is changed.  The model may have been
            // changed by another view or by a state update from the back-end.
            var description = this.model.get('description');
            if (description.trim().length === 0) {
                this.$title.html(" "); // Preserve title height
            } else {
                this.$title.text(description);
                MathJax.Hub.Queue(["Typeset",MathJax.Hub,this.$title.get(0)]);
            }

            var button_text = this.model.get('button_text');
            if (button_text.trim().length === 0) {
                this.$show_button.html(" "); // Preserve button height
            } else {
                this.$show_button.text(button_text);
            }

            if (!this._shown_once) {
                this._shown_once = true;
                this.show();
            }

            return PopupView.__super__.update.apply(this);
        },

        _get_selector_element: function(selector) {
            // Get an element view a 'special' jquery selector.  (see widget.js)
            //
            // Since the modal actually isn't within the $el in the DOM, we need to extend
            // the selector logic to allow the user to set css on the modal if need be.
            // The convention used is:
            // "modal" - select the modal div
            // "modal [selector]" - select element(s) within the modal div.
            // "[selector]" - select elements within $el
            // "" - select the $el_to_style
            if (selector.substring(0, 5) == 'modal') {
                if (selector == 'modal') {
                    return this.$window;
                } else {
                    return this.$window.find(selector.substring(6));
                }
            } else {
                return PopupView.__super__._get_selector_element.apply(this, [selector]);
            }
        },
    });

    return {
        'ContainerView': ContainerView,
        'PopupView': PopupView,
    };
});
<|endoftext|>


<commit_before>// 56: Generator - Send function to a generator
// To do: make all tests pass, leave the assert lines unchanged!

var assert = require("assert");

describe('pass a function to a generator', () => {

  it('the generator can receive a function as a value', function() {
    let fn = function() {};

    function* generatorFunction() {
      assert.equal(yield null, fn);
    }

    let iterator = generatorFunction();
    iterator.next();
    iterator.next();
  });

  it('pass a function to the iterator, which calls it', function() {
    function* generatorFunction() {
      yield (yield 1)();
    }

    var iterator = generatorFunction();
    var iteratedOver = [iterator.next().value, iterator.next().value];

    assert.deepEqual([1, 2], iteratedOver);
  });

  it('nesting yielded function calls', function() {
    function* generatorFunction() {
      yield (yield (yield 1)());
    }

    var iteratedOver = [];

    assert.deepEqual([1, 2, 3], iteratedOver);
  });

});

<commit_msg>fix 53-generator-send-function.js<commit_after>// 56: Generator - Send function to a generator
// To do: make all tests pass, leave the assert lines unchanged!

var assert = require("assert");

describe('pass a function to a generator', () => {

  it('the generator can receive a function as a value', function() {
    let fn = function() {};

    function* generatorFunction() {
      assert.equal(yield null, fn);
    }

    let iterator = generatorFunction();
    iterator.next();
    iterator.next(fn);
  });

  it('pass a function to the iterator, which calls it', function() {
    function* generatorFunction() {
      yield (yield 1)();
    }

    var iterator = generatorFunction();
    var iteratedOver = [iterator.next().value, iterator.next(() => 2).value];

    assert.deepEqual([1, 2], iteratedOver);
  });

  it('nesting yielded function calls', function() {
    function* generatorFunction() {
      yield (yield (yield 1)())();
    }

    var iterator = generatorFunction();
    var iteratedOver = [
      iterator.next().value,
      iterator.next(() => 2).value,
      iterator.next(() => 3).value
    ];

    assert.deepEqual([1, 2, 3], iteratedOver);
  });

});

<|endoftext|>


<commit_before>/**
 *
 */
var system = require('system');
var args = system.args;
//console.log(JSON.stringify(args));
//phantom.exit(0);

if(args.length!=2){
	console.error("requires url argument")
	phantom.exit(1);
}

siteurl=args[1];

folder=siteurl.replace('://','.');

var page = require('webpage').create();
page.open(siteurl, function(status) {
	console.log("Status: " + status);
	if(status === "success") {

		page.zoomFactor = 0.25;

		var render=function(dim){
			var size={width:Math.round(dim.width*page.zoomFactor), height:Math.round(dim.height*page.zoomFactor)}

			page.viewportSize = size;
			page.render(folder+'/page'+size.width+'x'+size.height+'.png');

			page.viewportSize = {width:size.height, height:size.width};
			page.render(folder+'/page'+size.height+'x'+size.width+'.png');

		}

		setTimeout(function(){

			render({ width: 768, height: 1024 });
			render({ width: 640, height: 980 });

			phantom.exit();

		},5000);

	}else{
		phantom.exit();
	}

});
<commit_msg>add output directory as cmd line option<commit_after>/**
 *
 */
var system = require('system');
var args = system.args;
//console.log(JSON.stringify(args));
//phantom.exit(0);

if(args.length<2){
	console.error("requires url argument")
	phantom.exit(1);
}

var siteurl=args[1];

var folder=siteurl.replace('://','.').replace(/[/]/g,'-');
var out='';
if(args.length>2){
	out=args[2];
	if(out.slice(-1)!='/'){
		out=out+'/';
	}
}

//console.log('folder name: '+folder);
var page = require('webpage').create();
page.open(siteurl, function(status) {
	console.log("Status: " + status);
	if(status === "success") {

		page.zoomFactor = 0.25;

		var render=function(dim){
			var size={width:Math.round(dim.width*page.zoomFactor), height:Math.round(dim.height*page.zoomFactor)}

			page.viewportSize = size;
			page.render(out+folder+'/page'+size.width+'x'+size.height+'.png');

			page.viewportSize = {width:size.height, height:size.width};
			page.render(out+folder+'/page'+size.height+'x'+size.width+'.png');

		}

		setTimeout(function(){

			render({ width: 768, height: 1024 });
			render({ width: 640, height: 980 });

			phantom.exit();

		},5000);

	}else{
		phantom.exit();
	}

});

<|endoftext|>


<commit_before>

module.exports = class SolarPayloadHandler {

  constructor(socket, client) {
    this.msg_id = 999;
    this.client = client;

    socket.on('message', (buf, rinfo) => {
      if (buf.readUInt8(0) === 9 && buf.readUInt8(1) === 55) {
        if (this.msg_id !== buf.readUInt8(3)) {
          let payload = this.unserialize(buf);
          payload.timestamp = new Date().getTime();
          console.log(payload);

          this.client.index({
            index: 'solar_0', //@todo not hard coded index name
            type: '_doc',
            body: payload
          })
          .catch ((err) => {
            console.error('failed to index: ' + err);
          })
          ;

        }
      }
    });
  }

  unserialize(buf) {
    let payload = {};
    payload.msg_type = buf.readUInt8(1);
    payload.device_id = buf.readUInt8(2);
    payload.msg_id = buf.readUInt8(3);
    this.msg_id = payload.msg_id;
    payload.flags = buf.readUInt8(4);
    payload.vcc = buf.readInt16BE(5);
    payload.mv = buf.readInt16BE(7);
    payload.ma = buf.readInt16BE(9);
    payload.light = buf.readInt16BE(11);
    payload.cpu_temperature = buf.readInt16BE(13);
    payload.temperature = buf.readInt16BE(15) / 10;
    payload.rssi = buf.readInt16BE(17);
    payload.snr = buf.readInt16BE(19);
    payload.freg_error = buf.readInt16BE(21);

    return payload;
  }

}
<commit_msg>Keep a record in a file.<commit_after>const fs = require('fs');
const fsPromises = fs.promises;

module.exports = class SolarPayloadHandler {

  constructor(socket, client) {
    this.msg_id = 999;
    this.client = client;

    socket.on('message', (buf, rinfo) => {
      if (buf.readUInt8(0) === 9 && buf.readUInt8(1) === 55) {
        if (this.msg_id !== buf.readUInt8(3)) {
          let payload = this.unserialize(buf);
          payload.timestamp = new Date().getTime();
          console.log(payload);

          // Keep a record in a file.
          let now = new Date();
          let month = now.getUTCMonth() + 1;
          let dir = __dirname + '/log/' + now.getUTCFullYear();
          // {recursive: true} requires > 10.12.0
          fsPromises.mkdir(dir, {recursive: true})
          .then(() => {
            return fsPromises.appendFile(
              dir + '/' + month + '.json',
              JSON.stringify(payload) + "\n"
            );
          })
          .catch(console.error);

          // Index into Elasticsearch.
          this.client.index({
            index: 'solar_0', //@todo not hard coded index name
            type: '_doc',
            body: payload
          })
          .catch ((err) => {
            console.error('failed to index: ' + err);
          })
          ;

        }
      }
    });
  }

  unserialize(buf) {
    let payload = {};
    payload.msg_type = buf.readUInt8(1);
    payload.device_id = buf.readUInt8(2);
    payload.msg_id = buf.readUInt8(3);
    this.msg_id = payload.msg_id;
    payload.flags = buf.readUInt8(4);
    payload.vcc = buf.readInt16BE(5);
    payload.mv = buf.readInt16BE(7);
    payload.ma = buf.readInt16BE(9);
    payload.light = buf.readInt16BE(11);
    payload.cpu_temperature = buf.readInt16BE(13);
    payload.temperature = buf.readInt16BE(15) / 10;
    payload.rssi = buf.readInt16BE(17);
    payload.snr = buf.readInt16BE(19);
    payload.freg_error = buf.readInt16BE(21);

    return payload;
  }

}
<|endoftext|>


<commit_before>const { createRemoteFileNode } = require(`gatsby-source-filesystem`)

exports.onCreateNode = async (
  {
    actions: { createNode },
    node,
    createContentDigest,
    store,
    cache,
    reporter,
  },
  { filter, nodeName = `localFile` }
) => {
  if (filter(node)) {
    const fileNode = await createRemoteFileNode({
      url: node.url,
      cache,
      createNode,
      createNodeId: createContentDigest,
    })

    if (fileNode) {
      const fileNodeLink = `${nodeName}___NODE`
      node[fileNodeLink] = fileNode.id
    }
  }
}

exports.createSchemaCustomization = ({ actions }) => {
  const { createTypes } = actions

  createTypes(`
    type UnsplashImagesYaml implements Node {
      url: String
      title: String
      credit: String
      gallery: Boolean
      localFile: File @link(from: "localFile___NODE")
    }

  `)
}
<commit_msg>chore: update using-image-processing example (#36421)<commit_after>const { createRemoteFileNode } = require(`gatsby-source-filesystem`)

exports.onCreateNode = async (
  { actions: { createNode, createNodeField }, node, createNodeId, getCache },
  { filter }
) => {
  if (filter(node)) {
    const fileNode = await createRemoteFileNode({
      url: node.url,
      parentNodeId: node.id,
      getCache,
      createNode,
      createNodeId,
    })

    if (fileNode) {
      createNodeField({ node, name: "localFile", value: fileNode.id })
    }
  }
}

exports.createSchemaCustomization = ({ actions }) => {
  const { createTypes } = actions

  createTypes(`
    type UnsplashImagesYaml implements Node {
      url: String
      title: String
      credit: String
      gallery: Boolean
      localFile: File @link(from: "fields.localFile")
    }

  `)
}
<|endoftext|>