<commit_before>exports.commands = {
	addsymbols: 'symbols',
	symbols: function (target, room, user) {
		if (!this.can('warn')) {
			this.sendReply('You need to be a league member to be able to use this command.');
			return false;
		}
		if (user.name.indexOf('∆') === 0 && user.name.lastIndexOf('∆') === (user.name.length - 1)) return this.sendReply("You already have your league symbols on.");
		if (user.name.indexOf('∆') == 0) {
			user.forceRename(user.name + '∆', undefined, true);
		} else if (user.name.lastIndexOf('∆') == (user.name.length - 1)) {
			user.forceRename('∆' + user.name, undefined, true);
		} else {
			user.forceRename('∆' + user.name + '∆', undefined, true);
		}
		return this.sendReply('Your league symbols have been added.');
	},

	site: function (target, room, user) {
		if (!this.runBroadcast()) return;
		this.sendReplyBox('Here is The Sora League Website:
' +
			'- Sora League Site'
		);
	},

	priomon: 'priomons',
	priomons: function (target, room, user) {
		if (!this.runBroadcast()) return;
		this.sendReplyBox('Here is a detailed explanation of the format Priomons:
' +
			'- Priomons'
		);
	},

	incweather: function (target, room, user) {
		if (!this.runBroadcast()) return;
		this.sendReplyBox('Here is a detailed explanation of the format Inclement Weather:
' +
			'- Inclement Weather'
		);
	},

	pokemonsandbox: function (target, room, user) {
		if (!this.runBroadcast()) return;
		this.sendReplyBox('Here is a detailed explanation of the format Pokemon Sandbox:
' +
			'- Pokemon Sandbox'
		);
	},

	championschallenge: function (target, room, user) {
		if (!this.runBroadcast()) return;
		this.sendReplyBox('Here is a detailed explanation of the format Champion\'s Challenge:
' +
			'- Champion\'s Challenge'
		);
	},

	ipl: function (target, room, user) {
		if (!this.runBroadcast()) return;
		this.sendReplyBox('Here is a link to the International Pokemon League Tournament (IPL):
' +
			'- IPL Tournament Web Site
' +
			'
');
	},

	gymleaders: function (target, room, user) {
		if (!this.runBroadcast()) return;
		this.sendReplyBox('Here is a list of Sora League Gym Leaders:
' +
			'- Sora League Gym Leaders'
		);
	},

	frontier: 'battlefrontier',
	battlefrontier: function (target, room, user) {
		if (!this.runBroadcast()) return;
		this.sendReplyBox('Sora Battle Frontier
' +
			'"Welcome to the Sora Battle Frontier! Challenge us if you Dare."
' +
			'Requirements: 8 Badges
' +
			'Rules: The Battle Frontier must be challenged after collecting 8 gym badges and 2 normal Frontiers must be defeated to gain access to the Elite 4.
' +
			'- The Elite Frontiers can only be challenged once a challenger has 4 different symbols.
' +
			'- The Frontier Head can be challenged after deafeating all other Frontier members.
' +
			'- If a challenger loses to an Elite Frontier or the Frontier Head, they will randomly lose one Elite symbol and one normal symbol.
' +
			'<blink>Notes:</blink>
' +
			'- The same frontier may be challenged once every 24 hours.
' +
			'- Challenging Rules
' +
			'Here is a list of Sora League Frontier Brains:
' +
			'- Sora League Frontier Brains'
		);
	},

	elitefour: 'e4',
	e4: function (target, room, user) {
		if (!this.runBroadcast()) return;
		this.sendReplyBox('Here is a list of Sora League Elite Four:
' +
			'- Sora League Elite Four'
		);
	},

	champions: 'champions',
	champions: function (target, room, user) {
		if (!this.runBroadcast()) return;
		this.sendReplyBox('Here is a list of Sora League Champions:
' +
			'- Sora League Champions'
		);
	},

	quoteoftheday: 'qotd',
	qotd: function (target, room, user) {
		if (!this.runBroadcast()) return;
		this.sendReplyBox('Quote of the Day:
' +
			'This command will display genius quotes until another quote tops it!
' +
			'"I\'m better as an E4." - Matt 2014
' +
			'"you have been hour munted by demon lrod helix" - Artiste Jeratt 9/7/14
' +
			'"Oh boy, how I love women. Golly gosh, I really do love vajigglejaggle. If only I could express how much I loved melons. Gee whizz." -Gym Ldr Eska 19/7/14
' +
			'"there can only be one asch, but anyone can be an aschhole" -E4 Cocoa 17/8/14
 ' +
			'"Drizzle Damp Rock is broken, but apparently the flying Rabbit Hedgehog from Ubers is okay." -∆Champiön Nöah∆ 1/9/14
' +
			'"The thing about electric types is you always gotta wear a rubber"-∆E4 Vanilla∆ 6/9/14
' +
			'"Umbreon is dark?"-∆E4 Arjunb∆ 30/11/14
' +
			'"Isn\'t Color Change and protean the same thing?" -∆Frontier∆ Nova 15/12/14
' +
			'"Smogon pretty much did the Treaty of Versailles to Water" -∆Champiön Nöah∆ 12/1/15
' +
			'"Chief Akkie, head of the meme police, serving for 38 years; no meme slips through her cracks." -Eska and Desna 14/3/15
'
		);
	},

	hos: 'banlist',
	hallofshame: 'banlist',
	banlist: function (target, room, user) {
		if (this.broadcasting) return;
		this.sendReplyBox('The Sora League Server Hall of Shame (Banlist):
' +
			'The following users are to be banned on sight, no exceptions. Most of them have dynamic ips, but even so, the first 2 set of numbers should be the same
' +
			'117.193.61.37/115.250.65.134 - Adipravar/lingam/China Guy
' +
			'79.216.58.98 - MegaschoolGirl/Jessica albas ass/Gym Leader Beer
' +
			'110.143.22.35 - Whelplo/Lord Noxot
' +
			'81.204.176.142
' +
			'68.144.221.250 - modsdd911/cocksucker3000
' +
			'65.9.122.140 - XVid
' +
			'188.247.72.73 - elite four pkmn/chatot
' +
			'50.117.78.134
' +
			'109.123.112.118
' +
			'70.56.251.194 - PEEEENNNNUUUSSSS
' +
			'184.148.86.83 - POOOOP BRO/MrGaminganimation
' +
			'76.103.152.157 - Thafuckingnigga
' +
			'110.174.150.196 - Nigerian Nuts
' +
			'77.209.58.47 - Spammer 008/flood of water
' +
			'107.3.135.54 - ilikewings
' +
			'24.118.0.134 - Colgate SHIT
' +
			'89.148.36.189 - gym leader Zaga
' +
			'204.108.212.233 - gawkypath
' +
			'95.211.174.70
' +
			'112.207.89.115
' +
			'69.171.166.93 - Efficient
' +
			'64.21.211.34 - Psychic kid
' +
			'217.123.61.20 - Sjado
' +
			'96.255.1.236
' +
			'12.204.68.50 - Denver Broncos
' +
			'173.8.74.161 - SawkTooOp
' +
			'149.254.224.226
' +
			'23.17.238.53 -Zarif
' +
			'74.88.1.127 -Unicode spammer (Eldes)
' +
			'23.30.142.86 -Carl Jones
' +
			'94.79.237.137 -Champiön Greninja
' +
			'71.191.144.42 -Imp Dawnmidst
' +
			'104.157.62.151 -ZYGA
' +
			'37.58.52.99 -Snowking
' +
			'222.127.85.53 -Galactic Azir
' +
			'76.100.209.92 -OgreLordVagina
' +
			'31.7.62.170 -Dan
' +
			'71.41.165.94 -yDante
' +
			'62.140.132.13 -Aidan
' +
			'Shame on them!');
	},

	donate: function (target, room, user) {
		if (!this.runBroadcast()) return;
		this.sendReplyBox('If you wish to donate to the server, please click on the button below.
' +
			'
' +
			'Remember to mention your username when you leave a note with your donation, or we won\'t know who donated. To all of those who\'ve donated or plan on donating, thank you! We really appreciate it!

' +
			'Donation benefits:
' +
			'$1 or more:' +
			'
Earns you the Server Donator badge, which will be displayed on your trainer card.' +
			'
Allows you to set a custom username colour visible in chats, but not the userlist.

' +
			'$5 or more:' +
			'
All of the above^' +
			'
A red userlist highlight color, visible on the Lobby\'s userlist');
	}
};
<commit_msg>Added james to hos<commit_after>exports.commands = {
	addsymbols: 'symbols',
	symbols: function (target, room, user) {
		if (!this.can('warn')) {
			this.sendReply('You need to be a league member to be able to use this command.');
			return false;
		}
		if (user.name.indexOf('∆') === 0 && user.name.lastIndexOf('∆') === (user.name.length - 1)) return this.sendReply("You already have your league symbols on.");
		if (user.name.indexOf('∆') == 0) {
			user.forceRename(user.name + '∆', undefined, true);
		} else if (user.name.lastIndexOf('∆') == (user.name.length - 1)) {
			user.forceRename('∆' + user.name, undefined, true);
		} else {
			user.forceRename('∆' + user.name + '∆', undefined, true);
		}
		return this.sendReply('Your league symbols have been added.');
	},

	site: function (target, room, user) {
		if (!this.runBroadcast()) return;
		this.sendReplyBox('Here is The Sora League Website:
' +
			'- Sora League Site'
		);
	},

	priomon: 'priomons',
	priomons: function (target, room, user) {
		if (!this.runBroadcast()) return;
		this.sendReplyBox('Here is a detailed explanation of the format Priomons:
' +
			'- Priomons'
		);
	},

	incweather: function (target, room, user) {
		if (!this.runBroadcast()) return;
		this.sendReplyBox('Here is a detailed explanation of the format Inclement Weather:
' +
			'- Inclement Weather'
		);
	},

	pokemonsandbox: function (target, room, user) {
		if (!this.runBroadcast()) return;
		this.sendReplyBox('Here is a detailed explanation of the format Pokemon Sandbox:
' +
			'- Pokemon Sandbox'
		);
	},

	championschallenge: function (target, room, user) {
		if (!this.runBroadcast()) return;
		this.sendReplyBox('Here is a detailed explanation of the format Champion\'s Challenge:
' +
			'- Champion\'s Challenge'
		);
	},

	ipl: function (target, room, user) {
		if (!this.runBroadcast()) return;
		this.sendReplyBox('Here is a link to the International Pokemon League Tournament (IPL):
' +
			'- IPL Tournament Web Site
' +
			'
');
	},

	gymleaders: function (target, room, user) {
		if (!this.runBroadcast()) return;
		this.sendReplyBox('Here is a list of Sora League Gym Leaders:
' +
			'- Sora League Gym Leaders'
		);
	},

	frontier: 'battlefrontier',
	battlefrontier: function (target, room, user) {
		if (!this.runBroadcast()) return;
		this.sendReplyBox('Sora Battle Frontier
' +
			'"Welcome to the Sora Battle Frontier! Challenge us if you Dare."
' +
			'Requirements: 8 Badges
' +
			'Rules: The Battle Frontier must be challenged after collecting 8 gym badges and 2 normal Frontiers must be defeated to gain access to the Elite 4.
' +
			'- The Elite Frontiers can only be challenged once a challenger has 4 different symbols.
' +
			'- The Frontier Head can be challenged after deafeating all other Frontier members.
' +
			'- If a challenger loses to an Elite Frontier or the Frontier Head, they will randomly lose one Elite symbol and one normal symbol.
' +
			'<blink>Notes:</blink>
' +
			'- The same frontier may be challenged once every 24 hours.
' +
			'- Challenging Rules
' +
			'Here is a list of Sora League Frontier Brains:
' +
			'- Sora League Frontier Brains'
		);
	},

	elitefour: 'e4',
	e4: function (target, room, user) {
		if (!this.runBroadcast()) return;
		this.sendReplyBox('Here is a list of Sora League Elite Four:
' +
			'- Sora League Elite Four'
		);
	},

	champions: 'champions',
	champions: function (target, room, user) {
		if (!this.runBroadcast()) return;
		this.sendReplyBox('Here is a list of Sora League Champions:
' +
			'- Sora League Champions'
		);
	},

	quoteoftheday: 'qotd',
	qotd: function (target, room, user) {
		if (!this.runBroadcast()) return;
		this.sendReplyBox('Quote of the Day:
' +
			'This command will display genius quotes until another quote tops it!
' +
			'"I\'m better as an E4." - Matt 2014
' +
			'"you have been hour munted by demon lrod helix" - Artiste Jeratt 9/7/14
' +
			'"Oh boy, how I love women. Golly gosh, I really do love vajigglejaggle. If only I could express how much I loved melons. Gee whizz." -Gym Ldr Eska 19/7/14
' +
			'"there can only be one asch, but anyone can be an aschhole" -E4 Cocoa 17/8/14
 ' +
			'"Drizzle Damp Rock is broken, but apparently the flying Rabbit Hedgehog from Ubers is okay." -∆Champiön Nöah∆ 1/9/14
' +
			'"The thing about electric types is you always gotta wear a rubber"-∆E4 Vanilla∆ 6/9/14
' +
			'"Umbreon is dark?"-∆E4 Arjunb∆ 30/11/14
' +
			'"Isn\'t Color Change and protean the same thing?" -∆Frontier∆ Nova 15/12/14
' +
			'"Smogon pretty much did the Treaty of Versailles to Water" -∆Champiön Nöah∆ 12/1/15
' +
			'"Chief Akkie, head of the meme police, serving for 38 years; no meme slips through her cracks." -Eska and Desna 14/3/15
'
		);
	},

	hos: 'banlist',
	hallofshame: 'banlist',
	banlist: function (target, room, user) {
		if (this.broadcasting) return;
		this.sendReplyBox('The Sora League Server Hall of Shame (Banlist):
' +
			'The following users are to be banned on sight, no exceptions. Most of them have dynamic ips, but even so, the first 2 set of numbers should be the same
' +
			'117.193.61.37/115.250.65.134 - Adipravar/lingam/China Guy
' +
			'79.216.58.98 - MegaschoolGirl/Jessica albas ass/Gym Leader Beer
' +
			'110.143.22.35 - Whelplo/Lord Noxot
' +
			'81.204.176.142
' +
			'68.144.221.250 - modsdd911/cocksucker3000
' +
			'65.9.122.140 - XVid
' +
			'188.247.72.73 - elite four pkmn/chatot
' +
			'50.117.78.134
' +
			'109.123.112.118
' +
			'70.56.251.194 - PEEEENNNNUUUSSSS
' +
			'184.148.86.83 - POOOOP BRO/MrGaminganimation
' +
			'76.103.152.157 - Thafuckingnigga
' +
			'110.174.150.196 - Nigerian Nuts
' +
			'77.209.58.47 - Spammer 008/flood of water
' +
			'107.3.135.54 - ilikewings
' +
			'24.118.0.134 - Colgate SHIT
' +
			'89.148.36.189 - gym leader Zaga
' +
			'204.108.212.233 - gawkypath
' +
			'95.211.174.70
' +
			'112.207.89.115
' +
			'69.171.166.93 - Efficient
' +
			'64.21.211.34 - Psychic kid
' +
			'217.123.61.20 - Sjado
' +
			'96.255.1.236
' +
			'12.204.68.50 - Denver Broncos
' +
			'173.8.74.161 - SawkTooOp
' +
			'149.254.224.226
' +
			'23.17.238.53 -Zarif
' +
			'74.88.1.127 -Unicode spammer (Eldes)
' +
			'23.30.142.86 -Carl Jones
' +
			'94.79.237.137 -Champiön Greninja
' +
			'71.191.144.42 -Imp Dawnmidst
' +
			'104.157.62.151 -ZYGA
' +
			'37.58.52.99 -Snowking
' +
			'222.127.85.53 -Galactic Azir
' +
			'76.100.209.92 -OgreLordVagina
' +
			'31.7.62.170 -Dan
' +
			'71.41.165.94 -yDante
' +
			'62.140.132.13 -Aidan
' +
			'165.255.119.159 -James357
' +
			'Shame on them!');
	},

	donate: function (target, room, user) {
		if (!this.runBroadcast()) return;
		this.sendReplyBox('If you wish to donate to the server, please click on the button below.
' +
			'
' +
			'Remember to mention your username when you leave a note with your donation, or we won\'t know who donated. To all of those who\'ve donated or plan on donating, thank you! We really appreciate it!

' +
			'Donation benefits:
' +
			'$1 or more:' +
			'
Earns you the Server Donator badge, which will be displayed on your trainer card.' +
			'
Allows you to set a custom username colour visible in chats, but not the userlist.

' +
			'$5 or more:' +
			'
All of the above^' +
			'
A red userlist highlight color, visible on the Lobby\'s userlist');
	}
};
<|endoftext|>


<commit_before>var logger = require('../logger')
  , doc = require('../doc.json')
  , session require('../app');

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

module.exports = (args) => {
    switch (args[0]) {

        case 'w':       return switchChatWrapper(args);

        case 'scrollb': return chatwin.scrollBack();
        case 'scrollf': return chatwin.scrollForward();
        case 'quit':    return process.exit(0);

        default:
            logger.log('warn', "Invalid command: %s", args[0]);
    }
};

function switchChatWrapper(args) {
    if (helpers.checkArgsLength(args, 2)) return;
    if (helpers.typeNumber(args[1])) return;
    if (session.chats[parseInt(args[1]) - 1] === undefined) {
        logger.log('verbose', doc.cmd.chatNotExist, args[0], args[1]);
        return;
    } else chatwin.switchChat(
        session.chats[parseInt(args[1]) - 1]
    );
}

var helpers = {
    checkArgsLength: (args, len) => {
        if (args.length > len) {
            logger.log('warn', doc.cmd.tooManyArguments, args[0]);
            return 1;
        } else if (args.length < len) {
            logger.log('warn', doc.cmd.notEnoughArguments, args[0]);
            return 1;
        } else return 0;
    },
    typeNumber: (arg) => {
        if (isNaN(arg)) {
            logger.log('warn', doc.cmd.notNumber, args[0], args[1]);
            return 1;
        }
    }
}
<commit_msg>Fixed some typos.<commit_after>var logger = require('../logger')
  , doc = require('../doc.json')
  , session = require('../app');

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

module.exports = (args) => {
    switch (args[0]) {

        case 'w':       return switchChatWrapper(args);

        case 'scrollb': return chatwin.scrollBack();
        case 'scrollf': return chatwin.scrollForward();
        case 'quit':    return process.exit(0);

        default:
            logger.log('warn', "Invalid command: %s", args[0]);
    }
};

function switchChatWrapper(args) {
    if (helpers.checkArgsLength(args, 2)) return;
    if (helpers.typeNumber(args[1])) return;
    if (session.chats[parseInt(args[1]) - 1] === undefined) {
        logger.log('verbose', doc.cmd.chatNotExist, args[0], args[1]);
    } else chatwin.switchChat(
        session.chats[parseInt(args[1]) - 1]
    );
}

var helpers = {
    checkArgsLength: (args, len) => {
        if (args.length > len) {
            logger.log('warn', doc.cmd.tooManyArguments, args[0]);
            return 1;
        } else if (args.length < len) {
            logger.log('warn', doc.cmd.notEnoughArguments, args[0]);
            return 1;
        } else return 0;
    },
    typeNumber: (arg) => {
        if (isNaN(arg)) {
            logger.log('warn', doc.cmd.notNumber, args[0], args[1]);
            return 1;
        } else return 0;
    }
};
<|endoftext|>


<commit_before>/*
 * jQuery UI @VERSION
 *
 * Copyright (c) 2008 Paul Bakaus (ui.jquery.com)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI
 */
;(function($) {

$.ui = {
	plugin: {
		add: function(module, option, set) {
			var proto = $.ui[module].prototype;
			for(var i in set) {
				proto.plugins[i] = proto.plugins[i] || [];
				proto.plugins[i].push([option, set[i]]);
			}
		},
		call: function(instance, name, args) {
			var set = instance.plugins[name];
			if(!set) { return; }

			for (var i = 0; i < set.length; i++) {
				if (instance.options[set[i][0]]) {
					set[i][1].apply(instance.element, args);
				}
			}
		}
	},
	cssCache: {},
	css: function(name) {
		if ($.ui.cssCache[name]) { return $.ui.cssCache[name]; }
		var tmp = $('
').addClass(name).css({position:'absolute', top:'-5000px', left:'-5000px', display:'block'}).appendTo('body');

		//if (!$.browser.safari)
			//tmp.appendTo('body');

		//Opera and Safari set width and height to 0px instead of auto
		//Safari returns rgba(0,0,0,0) when bgcolor is not set
		$.ui.cssCache[name] = !!(
			(!(/auto|default/).test(tmp.css('cursor')) || (/^[1-9]/).test(tmp.css('height')) || (/^[1-9]/).test(tmp.css('width')) ||
			!(/none/).test(tmp.css('backgroundImage')) || !(/transparent|rgba\(0, 0, 0, 0\)/).test(tmp.css('backgroundColor')))
		);
		try { $('body').get(0).removeChild(tmp.get(0));	} catch(e){}
		return $.ui.cssCache[name];
	},
	disableSelection: function(el) {
		$(el).attr('unselectable', 'on').css('MozUserSelect', 'none').bind('selectstart', function() { return false; });
	},
	enableSelection: function(el) {
		$(el).attr('unselectable', 'off').css('MozUserSelect', '').unbind('selectstart');
	},
	hasScroll: function(e, a) {
		var scroll = (a && a == 'left') ? 'scrollLeft' : 'scrollTop',
			has = false;

		if (e[scroll] > 0) { return true; }

		// TODO: determine which cases actually cause this to happen
		// if the element doesn't have the scroll set, see if it's possible to
		// set the scroll
		e[scroll] = 1;
		has = (e[scroll] > 0);
		e[scroll] = 0;
		return has;
	}
};

/** jQuery core modifications and additions **/

// This adds a selector to check if data exists.
jQuery.expr[':'].data = "jQuery.data(a, m[3])";

var _remove = $.fn.remove;
$.fn.remove = function() {
	$("*", this).add(this).triggerHandler("remove");
	return _remove.apply(this, arguments );
};

// $.widget is a factory to create jQuery plugins
// taking some boilerplate code out of the plugin code
// created by Scott González and Jörn Zaefferer
function getter(namespace, plugin, method) {
	var methods = $[namespace][plugin].getter || [];
	methods = (typeof methods == "string" ? methods.split(/,?\s+/) : methods);
	return ($.inArray(method, methods) != -1);
}

$.widget = function(name, prototype) {
	var namespace = name.split(".")[0];
	name = name.split(".")[1];

	// create plugin method
	$.fn[name] = function(options) {
		var isMethodCall = (typeof options == 'string'),
			args = Array.prototype.slice.call(arguments, 1);

		if (isMethodCall && getter(namespace, name, options)) {
			var instance = $.data(this[0], name);
			return (instance ? instance[options].apply(instance, args)
				: undefined);
		}

		return this.each(function() {
			var instance = $.data(this, name);
			if (isMethodCall && instance && $.isFunction(instance[options])) {
				instance[options].apply(instance, args);
			} else if (!isMethodCall) {
				$.data(this, name, new $[namespace][name](this, options));
			}
		});
	};

	// create widget constructor
	$[namespace][name] = function(element, options) {
		var self = this;

		this.widgetName = name;
		this.widgetEventPrefix = $[namespace][name].eventPrefix || name;
		this.widgetBaseClass = namespace + '-' + name;

		this.options = $.extend({},
			$.widget.defaults,
			$[namespace][name].defaults,
			$.metadata && $.metadata.get(element)[name],
			options);

		this.element = $(element)
			.bind('setData.' + name, function(e, key, value) {
				return self.setData(key, value);
			})
			.bind('getData.' + name, function(e, key) {
				return self.getData(key);
			})
			.bind('remove', function() {
				return self.destroy();
			});

		this.init();
	};

	// add widget prototype
	$[namespace][name].prototype = $.extend({}, $.widget.prototype, prototype);
};

$.widget.prototype = {
	init: function() {},
	destroy: function() {
		this.element.removeData(this.widgetName);
	},

	getData: function(key) {
		return this.options[key];
	},
	setData: function(key, value) {
		this.options[key] = value;

		if (key == 'disabled') {
			this.element[value ? 'addClass' : 'removeClass'](
				this.widgetBaseClass + '-disabled');
		}
	},

	enable: function() {
		this.setData('disabled', false);
	},
	disable: function() {
		this.setData('disabled', true);
	},

	trigger: function(type, e, data) {
		var eventName = (type == this.widgetEventPrefix
			? type : this.widgetEventPrefix + type);
		e = e  || $.event.fix({ type: eventName, target: this.element[0] });
		return this.element.triggerHandler(eventName, [e, data], this.options[type]);
	}
};

$.widget.defaults = {
	disabled: false
};

/** Mouse Interaction Plugin **/

$.ui.mouse = {
	mouseInit: function() {
		var self = this;

		this.element.bind('mousedown.'+this.widgetName, function(e) {
			return self.mouseDown(e);
		});

		// Prevent text selection in IE
		if ($.browser.msie) {
			this._mouseUnselectable = this.element.attr('unselectable');
			this.element.attr('unselectable', 'on');
		}

		this.started = false;
	},

	// TODO: make sure destroying one instance of mouse doesn't mess with
	// other instances of mouse
	mouseDestroy: function() {
		this.element.unbind('.'+this.widgetName);

		// Restore text selection in IE
		($.browser.msie
			&& this.element.attr('unselectable', this._mouseUnselectable));
	},

	mouseDown: function(e) {
		// we may have missed mouseup (out of window)
		(this._mouseStarted && this.mouseUp(e));

		this._mouseDownEvent = e;

		var self = this,
			btnIsLeft = (e.which == 1),
			elIsCancel = (typeof this.options.cancel == "string" ? $(e.target).parents().add(e.target).filter(this.options.cancel).length : false);
		if (!btnIsLeft || elIsCancel || !this.mouseCapture(e)) {
			return true;
		}

		this._mouseDelayMet = !this.options.delay;
		if (!this._mouseDelayMet) {
			this._mouseDelayTimer = setTimeout(function() {
				self._mouseDelayMet = true;
			}, this.options.delay);
		}

		if (this.mouseDistanceMet(e) && this.mouseDelayMet(e)) {
			this._mouseStarted = (this.mouseStart(e) !== false);
			if (!this._mouseStarted) {
				e.preventDefault();
				return true;
			}
		}

		// these delegates are required to keep context
		this._mouseMoveDelegate = function(e) {
			return self.mouseMove(e);
		};
		this._mouseUpDelegate = function(e) {
			return self.mouseUp(e);
		};
		$(document)
			.bind('mousemove.'+this.widgetName, this._mouseMoveDelegate)
			.bind('mouseup.'+this.widgetName, this._mouseUpDelegate);

		return false;
	},

	mouseMove: function(e) {
		// IE mouseup check - mouseup happened when mouse was out of window
		if ($.browser.msie && !e.button) {
			return this.mouseUp(e);
		}

		if (this._mouseStarted) {
			this.mouseDrag(e);
			return false;
		}

		if (this.mouseDistanceMet(e) && this.mouseDelayMet(e)) {
			this._mouseStarted =
				(this.mouseStart(this._mouseDownEvent, e) !== false);
			(this._mouseStarted ? this.mouseDrag(e) : this.mouseUp(e));
		}

		return !this._mouseStarted;
	},

	mouseUp: function(e) {
		$(document)
			.unbind('mousemove.'+this.widgetName, this._mouseMoveDelegate)
			.unbind('mouseup.'+this.widgetName, this._mouseUpDelegate);

		if (this._mouseStarted) {
			this._mouseStarted = false;
			this.mouseStop(e);
		}

		return false;
	},

	mouseDistanceMet: function(e) {
		return (Math.max(
				Math.abs(this._mouseDownEvent.pageX - e.pageX),
				Math.abs(this._mouseDownEvent.pageY - e.pageY)
			) >= this.options.distance
		);
	},

	mouseDelayMet: function(e) {
		return this._mouseDelayMet;
	},

	// These are placeholder methods, to be overriden by extending plugin
	mouseStart: function(e) {},
	mouseDrag: function(e) {},
	mouseStop: function(e) {},
	mouseCapture: function(e) { return true; }
};

$.ui.mouse.defaults = {
	cancel: null,
	distance: 1,
	delay: 0
};

})(jQuery);
<commit_msg>Core: Moved UI core code below jQuery modification code.<commit_after>/*
 * jQuery UI @VERSION
 *
 * Copyright (c) 2008 Paul Bakaus (ui.jquery.com)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI
 */
;(function($) {

/** jQuery core modifications and additions **/

// This adds a selector to check if data exists.
jQuery.expr[':'].data = "jQuery.data(a, m[3])";

var _remove = $.fn.remove;
$.fn.remove = function() {
	$("*", this).add(this).triggerHandler("remove");
	return _remove.apply(this, arguments );
};

// $.widget is a factory to create jQuery plugins
// taking some boilerplate code out of the plugin code
// created by Scott González and Jörn Zaefferer
function getter(namespace, plugin, method) {
	var methods = $[namespace][plugin].getter || [];
	methods = (typeof methods == "string" ? methods.split(/,?\s+/) : methods);
	return ($.inArray(method, methods) != -1);
}

$.widget = function(name, prototype) {
	var namespace = name.split(".")[0];
	name = name.split(".")[1];

	// create plugin method
	$.fn[name] = function(options) {
		var isMethodCall = (typeof options == 'string'),
			args = Array.prototype.slice.call(arguments, 1);

		if (isMethodCall && getter(namespace, name, options)) {
			var instance = $.data(this[0], name);
			return (instance ? instance[options].apply(instance, args)
				: undefined);
		}

		return this.each(function() {
			var instance = $.data(this, name);
			if (isMethodCall && instance && $.isFunction(instance[options])) {
				instance[options].apply(instance, args);
			} else if (!isMethodCall) {
				$.data(this, name, new $[namespace][name](this, options));
			}
		});
	};

	// create widget constructor
	$[namespace][name] = function(element, options) {
		var self = this;

		this.widgetName = name;
		this.widgetEventPrefix = $[namespace][name].eventPrefix || name;
		this.widgetBaseClass = namespace + '-' + name;

		this.options = $.extend({},
			$.widget.defaults,
			$[namespace][name].defaults,
			$.metadata && $.metadata.get(element)[name],
			options);

		this.element = $(element)
			.bind('setData.' + name, function(e, key, value) {
				return self.setData(key, value);
			})
			.bind('getData.' + name, function(e, key) {
				return self.getData(key);
			})
			.bind('remove', function() {
				return self.destroy();
			});

		this.init();
	};

	// add widget prototype
	$[namespace][name].prototype = $.extend({}, $.widget.prototype, prototype);
};

$.widget.prototype = {
	init: function() {},
	destroy: function() {
		this.element.removeData(this.widgetName);
	},

	getData: function(key) {
		return this.options[key];
	},
	setData: function(key, value) {
		this.options[key] = value;

		if (key == 'disabled') {
			this.element[value ? 'addClass' : 'removeClass'](
				this.widgetBaseClass + '-disabled');
		}
	},

	enable: function() {
		this.setData('disabled', false);
	},
	disable: function() {
		this.setData('disabled', true);
	},

	trigger: function(type, e, data) {
		var eventName = (type == this.widgetEventPrefix
			? type : this.widgetEventPrefix + type);
		e = e  || $.event.fix({ type: eventName, target: this.element[0] });
		return this.element.triggerHandler(eventName, [e, data], this.options[type]);
	}
};

$.widget.defaults = {
	disabled: false
};

/** jQuery UI core **/

$.ui = {
	plugin: {
		add: function(module, option, set) {
			var proto = $.ui[module].prototype;
			for(var i in set) {
				proto.plugins[i] = proto.plugins[i] || [];
				proto.plugins[i].push([option, set[i]]);
			}
		},
		call: function(instance, name, args) {
			var set = instance.plugins[name];
			if(!set) { return; }

			for (var i = 0; i < set.length; i++) {
				if (instance.options[set[i][0]]) {
					set[i][1].apply(instance.element, args);
				}
			}
		}
	},
	cssCache: {},
	css: function(name) {
		if ($.ui.cssCache[name]) { return $.ui.cssCache[name]; }
		var tmp = $('
').addClass(name).css({position:'absolute', top:'-5000px', left:'-5000px', display:'block'}).appendTo('body');

		//if (!$.browser.safari)
			//tmp.appendTo('body');

		//Opera and Safari set width and height to 0px instead of auto
		//Safari returns rgba(0,0,0,0) when bgcolor is not set
		$.ui.cssCache[name] = !!(
			(!(/auto|default/).test(tmp.css('cursor')) || (/^[1-9]/).test(tmp.css('height')) || (/^[1-9]/).test(tmp.css('width')) ||
			!(/none/).test(tmp.css('backgroundImage')) || !(/transparent|rgba\(0, 0, 0, 0\)/).test(tmp.css('backgroundColor')))
		);
		try { $('body').get(0).removeChild(tmp.get(0));	} catch(e){}
		return $.ui.cssCache[name];
	},
	disableSelection: function(el) {
		$(el).attr('unselectable', 'on').css('MozUserSelect', 'none').bind('selectstart', function() { return false; });
	},
	enableSelection: function(el) {
		$(el).attr('unselectable', 'off').css('MozUserSelect', '').unbind('selectstart');
	},
	hasScroll: function(e, a) {
		var scroll = (a && a == 'left') ? 'scrollLeft' : 'scrollTop',
			has = false;

		if (e[scroll] > 0) { return true; }

		// TODO: determine which cases actually cause this to happen
		// if the element doesn't have the scroll set, see if it's possible to
		// set the scroll
		e[scroll] = 1;
		has = (e[scroll] > 0);
		e[scroll] = 0;
		return has;
	}
};

/** Mouse Interaction Plugin **/

$.ui.mouse = {
	mouseInit: function() {
		var self = this;

		this.element.bind('mousedown.'+this.widgetName, function(e) {
			return self.mouseDown(e);
		});

		// Prevent text selection in IE
		if ($.browser.msie) {
			this._mouseUnselectable = this.element.attr('unselectable');
			this.element.attr('unselectable', 'on');
		}

		this.started = false;
	},

	// TODO: make sure destroying one instance of mouse doesn't mess with
	// other instances of mouse
	mouseDestroy: function() {
		this.element.unbind('.'+this.widgetName);

		// Restore text selection in IE
		($.browser.msie
			&& this.element.attr('unselectable', this._mouseUnselectable));
	},

	mouseDown: function(e) {
		// we may have missed mouseup (out of window)
		(this._mouseStarted && this.mouseUp(e));

		this._mouseDownEvent = e;

		var self = this,
			btnIsLeft = (e.which == 1),
			elIsCancel = (typeof this.options.cancel == "string" ? $(e.target).parents().add(e.target).filter(this.options.cancel).length : false);
		if (!btnIsLeft || elIsCancel || !this.mouseCapture(e)) {
			return true;
		}

		this._mouseDelayMet = !this.options.delay;
		if (!this._mouseDelayMet) {
			this._mouseDelayTimer = setTimeout(function() {
				self._mouseDelayMet = true;
			}, this.options.delay);
		}

		if (this.mouseDistanceMet(e) && this.mouseDelayMet(e)) {
			this._mouseStarted = (this.mouseStart(e) !== false);
			if (!this._mouseStarted) {
				e.preventDefault();
				return true;
			}
		}

		// these delegates are required to keep context
		this._mouseMoveDelegate = function(e) {
			return self.mouseMove(e);
		};
		this._mouseUpDelegate = function(e) {
			return self.mouseUp(e);
		};
		$(document)
			.bind('mousemove.'+this.widgetName, this._mouseMoveDelegate)
			.bind('mouseup.'+this.widgetName, this._mouseUpDelegate);

		return false;
	},

	mouseMove: function(e) {
		// IE mouseup check - mouseup happened when mouse was out of window
		if ($.browser.msie && !e.button) {
			return this.mouseUp(e);
		}

		if (this._mouseStarted) {
			this.mouseDrag(e);
			return false;
		}

		if (this.mouseDistanceMet(e) && this.mouseDelayMet(e)) {
			this._mouseStarted =
				(this.mouseStart(this._mouseDownEvent, e) !== false);
			(this._mouseStarted ? this.mouseDrag(e) : this.mouseUp(e));
		}

		return !this._mouseStarted;
	},

	mouseUp: function(e) {
		$(document)
			.unbind('mousemove.'+this.widgetName, this._mouseMoveDelegate)
			.unbind('mouseup.'+this.widgetName, this._mouseUpDelegate);

		if (this._mouseStarted) {
			this._mouseStarted = false;
			this.mouseStop(e);
		}

		return false;
	},

	mouseDistanceMet: function(e) {
		return (Math.max(
				Math.abs(this._mouseDownEvent.pageX - e.pageX),
				Math.abs(this._mouseDownEvent.pageY - e.pageY)
			) >= this.options.distance
		);
	},

	mouseDelayMet: function(e) {
		return this._mouseDelayMet;
	},

	// These are placeholder methods, to be overriden by extending plugin
	mouseStart: function(e) {},
	mouseDrag: function(e) {},
	mouseStop: function(e) {},
	mouseCapture: function(e) { return true; }
};

$.ui.mouse.defaults = {
	cancel: null,
	distance: 1,
	delay: 0
};

})(jQuery);
<|endoftext|>


<commit_before>import React from "react"
import Helmet from "react-helmet"
import Link from "gatsby-link"
import css from "./index.module.css"

const H1 = ({children}) =>

{children}

const H2 = ({children}) =>

{children}

const Defn = ({children}) =>

{children}

const Term = ({children}) =>

{children}

const mlWebapp =

        machine learning webapp

const cvPosterSim =

        computer vision poster simulator

const frontendDev =

        frontend development

const InfoA = ({children, href, print}) =>

            {children}

const InfoLink = ({children, to, print}) =>

        <Link className={css.Print} data-print={print} to={to}>
            {children}
        </Link>

export default ({data: {site}}) =>

    <Helmet title={`Resume - ${site.siteMetadata.title}`}/>

Ariel Davis

        <InfoA
            href="mailto:ariel.z.davis@icloud.com"
            print="ariel.z.davis@icloud.com"
        >
            Email
        </InfoA>
        <InfoA
            print="1-908-514-1006"
            href="tel:1-908-514-1006"
        >
            Phone
        </InfoA>
        <InfoLink
            print="azdavis.xyz"
            to="/"
        >
            Website
        </InfoLink>
        <InfoA
            print="github.com/azdavis"
            href="https://github.com/azdavis"
        >
            GitHub
        </InfoA>

Education

    <Term>May 2020</Term>
    <Defn>

Carnegie Mellon University - Pittsburgh, PA

B.S in Computer Science, Minor in Japanese Studies

GPA 4.0

    </Defn>
    <Term>June 2016</Term>
    <Defn>

Summit High School - Summit, NJ

Summa Cum Laude

    </Defn>

Selected Coursework

    <Term>Spring 2018</Term>
    <Defn>

            15-210: Parallel and Sequential Data Structures and Algorithms

15-418: Parallel Computer Architecture and Programming

82-272: Intermediate Japanese II

    </Defn>
    <Term>Fall 2017</Term>
    <Defn>

15-213: Introduction to Computer Systems

82-271: Intermediate Japanese I

82-273: Introduction to Japanese Language and Culture

    </Defn>
    <Term>Summer 2017</Term>
    <Defn>82-172: Elementary Japanese II</Defn>
    <Term>Spring 2017</Term>
    <Defn>

15-251: Great Theoretical Ideas in Computer Science

82-171: Elementary Japanese I

    </Defn>
    <Term>Fall 2016</Term>
    <Defn>

15-131: Great Practical Ideas in Computer Science

15-150: Principles of Functional Programming

    </Defn>
    <Term>Summer 2015</Term>
    <Defn>

15-122: Principles of Imperative Computation

21-127: Concepts of Mathematics

    </Defn>

Activities

    <Term>Spring 2018</Term>
    <Defn>TA: 15-150</Defn>
    <Term>Fall 2017</Term>
    <Defn>TA: 15-131, 15-150</Defn>
    <Term>Summer 2017</Term>
    <Defn>TA: 15-150</Defn>
    <Term>Spring 2017</Term>
    <Defn>
        TartanHacks: helped to create a {mlWebapp}
    </Defn>
    <Term>Fall 2016</Term>
    <Defn>

HackCMU: helped to create a {cvPosterSim}

ScottyLabs: gave a talk on basic {frontendDev}

    </Defn>
    <Term>Summer 2015</Term>
    <Defn>
        Carnegie Mellon University Pre-College: took compressed-form CMU
        classes
    </Defn>
    <Term>Summer 2014</Term>
    <Defn>
        Northwestern University Center for Talent Development: learned
        HTML, CSS
    </Defn>

Achievements

    <Term>Fall 2016</Term>
    <Defn>Dean's List</Defn>
    <Term>Spring 2017</Term>
    <Defn>Dean's List</Defn>
    <Term>Fall 2017</Term>
    <Defn>Dean's List</Defn>
    <Term>2016</Term>
    <Defn>

Summit High School Computer Science Award of Excellence

National AP Scholar

AP Scholar with Distinction

    </Defn>

Skills

    <Term>Languages</Term>
    <Defn>JavaScript, Haskell, Standard ML, Idris, Ruby, C</Defn>
    <Term>Markup</Term>
    <Defn>HTML, CSS, LaTeX, Markdown</Defn>
    <Term>Tools</Term>
    <Defn>Git, GitHub, Make, Shell, POSIX</Defn>

export const pageQuery = graphql`
    query Resume {
        site {
            siteMetadata {
                title
            }
        }
    }
`
<commit_msg>rm Achievements<commit_after>import React from "react"
import Helmet from "react-helmet"
import Link from "gatsby-link"
import css from "./index.module.css"

const H1 = ({children}) =>

{children}

const H2 = ({children}) =>

{children}

const Defn = ({children}) =>

{children}

const Term = ({children}) =>

{children}

const mlWebapp =

        machine learning webapp

const cvPosterSim =

        computer vision poster simulator

const frontendDev =

        frontend development

const InfoA = ({children, href, print}) =>

            {children}

const InfoLink = ({children, to, print}) =>

        <Link className={css.Print} data-print={print} to={to}>
            {children}
        </Link>

export default ({data: {site}}) =>

    <Helmet title={`Resume - ${site.siteMetadata.title}`}/>

Ariel Davis

        <InfoA
            href="mailto:ariel.z.davis@icloud.com"
            print="ariel.z.davis@icloud.com"
        >
            Email
        </InfoA>
        <InfoA
            print="1-908-514-1006"
            href="tel:1-908-514-1006"
        >
            Phone
        </InfoA>
        <InfoLink
            print="azdavis.xyz"
            to="/"
        >
            Website
        </InfoLink>
        <InfoA
            print="github.com/azdavis"
            href="https://github.com/azdavis"
        >
            GitHub
        </InfoA>

Education

    <Term>May 2020</Term>
    <Defn>

Carnegie Mellon University - Pittsburgh, PA

B.S in Computer Science, Minor in Japanese Studies

GPA 4.0

    </Defn>
    <Term>June 2016</Term>
    <Defn>

Summit High School - Summit, NJ

Summa Cum Laude

    </Defn>

Selected Coursework

    <Term>Spring 2018</Term>
    <Defn>

            15-210: Parallel and Sequential Data Structures and Algorithms

15-418: Parallel Computer Architecture and Programming

82-272: Intermediate Japanese II

    </Defn>
    <Term>Fall 2017</Term>
    <Defn>

15-213: Introduction to Computer Systems

82-271: Intermediate Japanese I

82-273: Introduction to Japanese Language and Culture

    </Defn>
    <Term>Summer 2017</Term>
    <Defn>82-172: Elementary Japanese II</Defn>
    <Term>Spring 2017</Term>
    <Defn>

15-251: Great Theoretical Ideas in Computer Science

82-171: Elementary Japanese I

    </Defn>
    <Term>Fall 2016</Term>
    <Defn>

15-131: Great Practical Ideas in Computer Science

15-150: Principles of Functional Programming

    </Defn>
    <Term>Summer 2015</Term>
    <Defn>

15-122: Principles of Imperative Computation

21-127: Concepts of Mathematics

    </Defn>

Activities

    <Term>Spring 2018</Term>
    <Defn>TA: 15-150</Defn>
    <Term>Fall 2017</Term>
    <Defn>TA: 15-131, 15-150</Defn>
    <Term>Summer 2017</Term>
    <Defn>TA: 15-150</Defn>
    <Term>Spring 2017</Term>
    <Defn>
        TartanHacks: helped to create a {mlWebapp}
    </Defn>
    <Term>Fall 2016</Term>
    <Defn>

HackCMU: helped to create a {cvPosterSim}

ScottyLabs: gave a talk on basic {frontendDev}

    </Defn>
    <Term>Summer 2015</Term>
    <Defn>
        Carnegie Mellon University Pre-College: took compressed-form CMU
        classes
    </Defn>
    <Term>Summer 2014</Term>
    <Defn>
        Northwestern University Center for Talent Development: learned
        HTML, CSS
    </Defn>

Skills

    <Term>Languages</Term>
    <Defn>JavaScript, Haskell, Standard ML, Idris, Ruby, C</Defn>
    <Term>Markup</Term>
    <Defn>HTML, CSS, LaTeX, Markdown</Defn>
    <Term>Tools</Term>
    <Defn>Git, GitHub, Make, Shell, POSIX</Defn>

export const pageQuery = graphql`
    query Resume {
        site {
            siteMetadata {
                title
            }
        }
    }
`
<|endoftext|>


<commit_before>/*****************************************************************************
Hz Segmented File Upload Module

TODO:
  - Convert diverted handlers to proper dispatchEvent()s
  - The manager needs to cleanly report the status of individual uploads
    as its progress is updating.  The UI should be allowed to see each
    file go up separately (with file name, size, loaded).
  - The individual uploads (and manager) need to support a suspend/resume
    feature.  This could be augmented with localStorage to continue
    distrupted uploads.
  - The individual uploads (and manager) need to support a cancel feature.

*****************************************************************************/

/*----------------------------------------------------------------------------
Hz Library Boilerplate
----------------------------------------------------------------------------*/
var hz = ( function( ns ) { return ns; } )( hz || {} );

/*----------------------------------------------------------------------------
Module Dependencies
----------------------------------------------------------------------------*/
/*?jspp { "include" : { "hz" : [] } } ?*/

/*----------------------------------------------------------------------------
Hz Upload Submodule
----------------------------------------------------------------------------*/
hz.upload = ( function( ns ) {

    /*------------------------------------------------------------------------
    Public Properties
    ------------------------------------------------------------------------*/

    ns.manager = manager;           //expose the upload manager class
    ns.upload  = upload;            //expose the upload class

    /*------------------------------------------------------------------------
    Public Methods
    ------------------------------------------------------------------------*/

    /*------------------------------------------------------------------------
    Classes
    ------------------------------------------------------------------------*/

    /**
     *  Multiple file upload manager.  Allows user code to upload multiple
     *  files in one large process with little supervision.  This should also
     *  be used as the reference implementation for using the chunked upload
     *  system.
     *
     *  Example usage:
     *
     *      var file_input = document.getElementById( 'file_input' );
     *      var up = new hz.upload.manager( file_input.files );
     *      up.onload = function( e ) { alert( 'All files uploaded!' ); };
     *      up.upload_all();
     *
     *  @param file_list A FileList instance
     *  @param target    The base URL to the upload server handler
     */
    function manager() {

        //default the constructor parameters
        this.file_list = arguments.length > 0 ? arguments[ 0 ] : null;
        this.target    = arguments.length > 1 ? arguments[ 1 ] : null;

        //initialize the uploader object
        this.current    = -1;
        this.onabort    = null;
        this.onerror    = null;
        this.onload     = null;
        this.onprogress = null;
        this.ontimeout  = null;

        //overall transfer status tracking
        this.status = {
            'files_total' : 0,
            'bytes_total' : 0,
            'files_sent'  : 0,
            'bytes_sent'  : 0
        };

        //check for a specified file list
        if( this.file_list.length > 0 ) {

            //initialize the transfer status information
            this.status.files_total = this.file_list.length;
            for( var i = 0; i < this.status.files_total; ++i ) {
                this.status.bytes_total += this.file_list[ i ].size;
            }
        }

    }

    /**
     *  Initiates an upload of all files known to the uploader object.
     *
     */
    manager.prototype.upload_all = function() {

        //reset the current file index
        this.current = -1;

        //initialize the multi-file upload status
        this.status.files_total = this.file_list.length;
        this.status.bytes_total = 0;
        for( var i = 0; i < this.status.files_total; ++i ) {
            this.status.bytes_total += this.file_list[ i ].size;
        }
        this.status.files_sent = 0;
        this.status.bytes_sent = 0;

        //upload the next (first) file in the list
        this.upload_next();

    };

    /**
     *  Initiates an upload of the next file in the list.
     *
     */
    manager.prototype.upload_next = function() {

        //increment the current file index
        this.current += 1;

        //bounds check the current file index
        if( this.current < this.file_list.length ) {

            //create the upload object for the current file
            var up = this.create_upload( this.file_list[ this.current ] );

            //set an object context variable for closed event handlers
            var context = this;

            //pass-through event handlers
            up.onabort   = this.onabort;
            up.onerror   = this.onerror;
            up.ontimeout = this.ontimeout;

            //handle the completion of this upload
            up.onload = function( e ) {

                //update status
                context.status.files_sent += 1;
                context.status.bytes_sent += e.loaded;

                //attempt to upload the next file in the list (if there is one)
                context.upload_next();
            };

            //handle progress updates during the upload
            up.onprogress = function( e ) {
                if( context.onprogress != null ) {
                    var loaded = e.loaded + context.status.bytes_sent;
                    context.onprogress(
                        {
                            'current'          : this.current,
                            'uploaded'         : this.status.files_sent,
                            'lengthComputable' : true,
                            'loaded'           : loaded,
                            'total'            : context.status.bytes_total
                        }
                    );
                }
            };

            //initiate the chunked upload for this file
            up.send();
        }

        //multi-file upload completed, and there's an onload handler
        else if( this.onload != null ) {
            this.onload(
                {
                    'target'           : this,
                    'lengthComputable' : true,
                    'loaded'           : this.status.bytes_sent,
                    'total'            : this.status.bytes_total
                }
            );
        }

    };

    /**
     *  Creates an upload object for the specified file instance.
     *
     *  @param file   A File instance to upload
     *  @param target The base URL to the upload server handler (optional)
     *  @return       An upload object instance that can upload the file,
     *                or null on failure
     */
    manager.prototype.create_upload = function( file ) {

        //set the base target URL
        var target = arguments.length > 1 ? arguments[ 1 ] : this.target;

        //create the upload object and return it
        return new upload( file, target );
    };

    /**
     *  Establishes a chunked file upload for a single file.  The file must be
     *  an instance of a File object.  The user can subscribe to the four
     *  typical XHR events (abort, error, load, progress) using property-style
     *  assignment.
     *
     *  Example usage:
     *      var file_input = document.getElementById( 'file_input' );
     *      var up = new hz.upload.upload(
     *          file_input.files[ 0 ],
     *          'http://example.com/upload_handler.php'
     *      );
     *      up.onprogress = function( status ) {
     *          console.log( status.loaded + '/' + status.total + ' bytes' );
     *      };
     *      up.onload = function( status ) {
     *          console.log( status.loaded + '/' + status.total + ' bytes' );
     *      };
     *      up.send();
     *
     *  @param file   The File instance representing the file to send
     *  @param target The target URL that can handle chunked uploads
     */
    function upload( file, target ) {

        //initialize the upload object
        this.chunk_size  = 8 * 1024 * 1024;
        this.file        = file;
        this.onabort     = null;
        this.onerror     = null;
        this.onload      = null;
        this.onprogress  = null;
        this.ontimeout   = null;
        this.reader      = new FileReader();
        this.to_send     = 0;
        this.target      = target;
        this.xhr         = new XMLHttpRequest();
        this.xhr.timeout = 5 * 60 * 1000;

        //transfer status tracking
        this.status = {
            bytes_total : file.size,
            bytes_sent  : 0
        };

        //set an object context variable for closed event handlers
        var context = this;

        //pass-through event handlers
        this.xhr.onabort = function( event ) {
            if( context.onabort != null ) {
                context.onabort( event );
            }
        };
        this.xhr.onerror = function( event ) {
            if( context.onerror != null ) {
                context.onerror( event );
            }
        };
        this.xhr.ontimeout = function( event ) {
            if( context.ontimeout != null ) {
                context.ontimeout( event );
            }
        }

        //progress is re-mapped to the overall upload (not just a chunk)
        this.xhr.onprogress = function( event ) {
            if( context.onprogress != null ) {
                var loaded = event.loaded + context.status.bytes_sent;
                context.onprogress(
                    {
                        'lengthComputable' : true,
                        'loaded'           : loaded,
                        'total'            : context.status.bytes_total
                    }
                );
            }
        };

        //load is re-mapped to the overall upload (not just a chunk)
        this.xhr.onload = function( event ) {

            //parse the server's response
            var result = JSON.parse( context.xhr.responseText );

            //check the transfer for problems reported by the server
            if( result.status != 0 ) {

                //if the error handler is available...
                if( context.onerror != null ) {

                    //indicate an error with some custom fields
                    context.onerror(
                        {
                            'lengthComputable' : false,
                            'loaded'           : 0,
                            'total'            : 0,
                            'message'          : result.payload,
                            'bytes_sent'       : context.to_send
                        }
                    );
                }
            }

            //the transfer appears successful
            else {

                //increment the total bytes sent
                context.status.bytes_sent += context.to_send;

                //send the next chunk
                context.send();
            }
        };

        //the file reader load event signals when it's ready to upload
        this.reader.onload = function( event ) {

            //construct the URI for the POST request
            var uri = context.target
                + '?name='    + encodeURIComponent( context.file.name )
                + '&type='    + encodeURIComponent( context.file.type )
                + '&time_ms=' + context.file.lastModifiedDate.getTime()
                + '&size='    + context.status.bytes_total
                + '&offset='  + context.status.bytes_sent
                + '&length='  + event.target.result.length;

            //prepare the proper POST request
            context.xhr.open( 'POST', uri, true );
            context.xhr.setRequestHeader(
                'Content-Type',
                'application/octet-stream'
            );
            //note for future generations:
            //  webkit does not allow a script to set Content-Length and
            //  Connection headers for XHR.  If it becomes an issue in the
            //  future, the server will have to deal with what it decides.

            //send the file segment in a POST request
            context.xhr.sendAsBinary( event.target.result );
        };

    }

    /**
     *  Sends the next part of the file to the server.
     *
     */
    upload.prototype.send = function() {

        //determine the number of remaining bytes to send
        var left = this.status.bytes_total - this.status.bytes_sent;

        //check if there are bytes left to send
        if( left > 0 ) {

            //calculate the bytes to send in this transfer
            this.to_send = left > this.chunk_size ? this.chunk_size : left;

            //initiate a file read for the number of bytes to send
            //  -- this is used to complement xhr.sendAsBinary()
            this.reader.readAsBinaryString(

                //specify the part of the file that should be sent
                //ZIH - Chrome may not support file.slice(),
                //      might have to duck-check for file.webkitSlice()
                this.file.slice(
                    this.status.bytes_sent,
                    ( this.status.bytes_sent + this.to_send )
                )
            );
        }

        //there are no more bytes left to send, check for load handler
        else if( this.onload != null ) {

            //fire the load event
            this.onload(
                {
                    'target'           : this,
                    'lengthComputable' : true,
                    'loaded'           : this.status.bytes_sent,
                    'total'            : this.status.bytes_total
                }
            );
        }

    };

    /*------------------------------------------------------------------------
    Private Properties
    ------------------------------------------------------------------------*/

    /*------------------------------------------------------------------------
    Private Methods
    ------------------------------------------------------------------------*/

    return ns;
} )( hz.upload || {} );

/*----------------------------------------------------------------------------
Attempting to add support for sendAsBinary() (thanks, webkit).
----------------------------------------------------------------------------*/

if( ( 'sendAsBinary' in XMLHttpRequest.prototype ) == false ) {
    XMLHttpRequest.prototype.sendAsBinary = function( data ) {
        var num_bytes = data.length;
        var uint8_data = new Uint8Array( num_bytes );
        for( var i = 0; i < num_bytes; ++i ) {
            uint8_data[ i ] = data.charCodeAt( i ) & 0xFF;
        }
        this.send( uint8_data );
    };
}
<commit_msg>Adding support for query parameters in POST target.<commit_after>/*****************************************************************************
Hz Segmented File Upload Module

TODO:
  - Convert diverted handlers to proper dispatchEvent()s
  - The manager needs to cleanly report the status of individual uploads
    as its progress is updating.  The UI should be allowed to see each
    file go up separately (with file name, size, loaded).
  - The individual uploads (and manager) need to support a suspend/resume
    feature.  This could be augmented with localStorage to continue
    distrupted uploads.
  - The individual uploads (and manager) need to support a cancel feature.

*****************************************************************************/

/*----------------------------------------------------------------------------
Hz Library Boilerplate
----------------------------------------------------------------------------*/
var hz = ( function( ns ) { return ns; } )( hz || {} );

/*----------------------------------------------------------------------------
Module Dependencies
----------------------------------------------------------------------------*/
/*?jspp { "include" : { "hz" : [] } } ?*/

/*----------------------------------------------------------------------------
Hz Upload Submodule
----------------------------------------------------------------------------*/
hz.upload = ( function( ns ) {

    /*------------------------------------------------------------------------
    Public Properties
    ------------------------------------------------------------------------*/

    ns.manager = manager;           //expose the upload manager class
    ns.upload  = upload;            //expose the upload class

    /*------------------------------------------------------------------------
    Public Methods
    ------------------------------------------------------------------------*/

    /*------------------------------------------------------------------------
    Classes
    ------------------------------------------------------------------------*/

    /**
     *  Multiple file upload manager.  Allows user code to upload multiple
     *  files in one large process with little supervision.  This should also
     *  be used as the reference implementation for using the chunked upload
     *  system.
     *
     *  Example usage:
     *
     *      var file_input = document.getElementById( 'file_input' );
     *      var up = new hz.upload.manager( file_input.files );
     *      up.onload = function( e ) { alert( 'All files uploaded!' ); };
     *      up.upload_all();
     *
     *  @param file_list A FileList instance
     *  @param target    The base URL to the upload server handler
     */
    function manager() {

        //default the constructor parameters
        this.file_list = arguments.length > 0 ? arguments[ 0 ] : null;
        this.target    = arguments.length > 1 ? arguments[ 1 ] : null;

        //initialize the uploader object
        this.current    = -1;
        this.onabort    = null;
        this.onerror    = null;
        this.onload     = null;
        this.onprogress = null;
        this.ontimeout  = null;

        //overall transfer status tracking
        this.status = {
            'files_total' : 0,
            'bytes_total' : 0,
            'files_sent'  : 0,
            'bytes_sent'  : 0
        };

        //check for a specified file list
        if( this.file_list.length > 0 ) {

            //initialize the transfer status information
            this.status.files_total = this.file_list.length;
            for( var i = 0; i < this.status.files_total; ++i ) {
                this.status.bytes_total += this.file_list[ i ].size;
            }
        }

    }

    /**
     *  Initiates an upload of all files known to the uploader object.
     *
     */
    manager.prototype.upload_all = function() {

        //reset the current file index
        this.current = -1;

        //initialize the multi-file upload status
        this.status.files_total = this.file_list.length;
        this.status.bytes_total = 0;
        for( var i = 0; i < this.status.files_total; ++i ) {
            this.status.bytes_total += this.file_list[ i ].size;
        }
        this.status.files_sent = 0;
        this.status.bytes_sent = 0;

        //upload the next (first) file in the list
        this.upload_next();

    };

    /**
     *  Initiates an upload of the next file in the list.
     *
     */
    manager.prototype.upload_next = function() {

        //increment the current file index
        this.current += 1;

        //bounds check the current file index
        if( this.current < this.file_list.length ) {

            //create the upload object for the current file
            var up = this.create_upload( this.file_list[ this.current ] );

            //set an object context variable for closed event handlers
            var context = this;

            //pass-through event handlers
            up.onabort   = this.onabort;
            up.onerror   = this.onerror;
            up.ontimeout = this.ontimeout;

            //handle the completion of this upload
            up.onload = function( e ) {

                //update status
                context.status.files_sent += 1;
                context.status.bytes_sent += e.loaded;

                //attempt to upload the next file in the list (if there is one)
                context.upload_next();
            };

            //handle progress updates during the upload
            up.onprogress = function( e ) {
                if( context.onprogress != null ) {
                    var loaded = e.loaded + context.status.bytes_sent;
                    context.onprogress(
                        {
                            'current'          : this.current,
                            'uploaded'         : this.status.files_sent,
                            'lengthComputable' : true,
                            'loaded'           : loaded,
                            'total'            : context.status.bytes_total
                        }
                    );
                }
            };

            //initiate the chunked upload for this file
            up.send();
        }

        //multi-file upload completed, and there's an onload handler
        else if( this.onload != null ) {
            this.onload(
                {
                    'target'           : this,
                    'lengthComputable' : true,
                    'loaded'           : this.status.bytes_sent,
                    'total'            : this.status.bytes_total
                }
            );
        }

    };

    /**
     *  Creates an upload object for the specified file instance.
     *
     *  @param file   A File instance to upload
     *  @param target The base URL to the upload server handler (optional)
     *  @return       An upload object instance that can upload the file,
     *                or null on failure
     */
    manager.prototype.create_upload = function( file ) {

        //set the base target URL
        var target = arguments.length > 1 ? arguments[ 1 ] : this.target;

        //create the upload object and return it
        return new upload( file, target );
    };

    /**
     *  Establishes a chunked file upload for a single file.  The file must be
     *  an instance of a File object.  The user can subscribe to the four
     *  typical XHR events (abort, error, load, progress) using property-style
     *  assignment.
     *
     *  Example usage:
     *      var file_input = document.getElementById( 'file_input' );
     *      var up = new hz.upload.upload(
     *          file_input.files[ 0 ],
     *          'http://example.com/upload_handler.php'
     *      );
     *      up.onprogress = function( status ) {
     *          console.log( status.loaded + '/' + status.total + ' bytes' );
     *      };
     *      up.onload = function( status ) {
     *          console.log( status.loaded + '/' + status.total + ' bytes' );
     *      };
     *      up.send();
     *
     *  @param file   The File instance representing the file to send
     *  @param target The target URL that can handle chunked uploads
     */
    function upload( file, target ) {

        //initialize the upload object
        this.chunk_size  = 8 * 1024 * 1024;
        this.file        = file;
        this.onabort     = null;
        this.onerror     = null;
        this.onload      = null;
        this.onprogress  = null;
        this.ontimeout   = null;
        this.reader      = new FileReader();
        this.to_send     = 0;
        this.target      = target;
        this.xhr         = new XMLHttpRequest();
        this.xhr.timeout = 5 * 60 * 1000;

        //transfer status tracking
        this.status = {
            bytes_total : file.size,
            bytes_sent  : 0
        };

        //set an object context variable for closed event handlers
        var context = this;

        //pass-through event handlers
        this.xhr.onabort = function( event ) {
            if( context.onabort != null ) {
                context.onabort( event );
            }
        };
        this.xhr.onerror = function( event ) {
            if( context.onerror != null ) {
                context.onerror( event );
            }
        };
        this.xhr.ontimeout = function( event ) {
            if( context.ontimeout != null ) {
                context.ontimeout( event );
            }
        }

        //progress is re-mapped to the overall upload (not just a chunk)
        this.xhr.onprogress = function( event ) {
            if( context.onprogress != null ) {
                var loaded = event.loaded + context.status.bytes_sent;
                context.onprogress(
                    {
                        'lengthComputable' : true,
                        'loaded'           : loaded,
                        'total'            : context.status.bytes_total
                    }
                );
            }
        };

        //load is re-mapped to the overall upload (not just a chunk)
        this.xhr.onload = function( event ) {

            //parse the server's response
            var result = JSON.parse( context.xhr.responseText );

            //check the transfer for problems reported by the server
            if( result.status != 0 ) {

                //if the error handler is available...
                if( context.onerror != null ) {

                    //indicate an error with some custom fields
                    context.onerror(
                        {
                            'lengthComputable' : false,
                            'loaded'           : 0,
                            'total'            : 0,
                            'message'          : result.payload,
                            'bytes_sent'       : context.to_send
                        }
                    );
                }
            }

            //the transfer appears successful
            else {

                //increment the total bytes sent
                context.status.bytes_sent += context.to_send;

                //send the next chunk
                context.send();
            }
        };

        //the file reader load event signals when it's ready to upload
        this.reader.onload = function( event ) {

            var qa = context.target.indexOf( '?' ) == -1 ? '?' : '&';

            //construct the URI for the POST request
            var uri = context.target + qa
                +  'name='    + encodeURIComponent( context.file.name )
                + '&type='    + encodeURIComponent( context.file.type )
                + '&time_ms=' + context.file.lastModifiedDate.getTime()
                + '&size='    + context.status.bytes_total
                + '&offset='  + context.status.bytes_sent
                + '&length='  + event.target.result.length;

            //prepare the proper POST request
            context.xhr.open( 'POST', uri, true );
            context.xhr.setRequestHeader(
                'Content-Type',
                'application/octet-stream'
            );
            //note for future generations:
            //  webkit does not allow a script to set Content-Length and
            //  Connection headers for XHR.  If it becomes an issue in the
            //  future, the server will have to deal with what it decides.

            //send the file segment in a POST request
            context.xhr.sendAsBinary( event.target.result );
        };

    }

    /**
     *  Sends the next part of the file to the server.
     *
     */
    upload.prototype.send = function() {

        //determine the number of remaining bytes to send
        var left = this.status.bytes_total - this.status.bytes_sent;

        //check if there are bytes left to send
        if( left > 0 ) {

            //calculate the bytes to send in this transfer
            this.to_send = left > this.chunk_size ? this.chunk_size : left;

            //initiate a file read for the number of bytes to send
            //  -- this is used to complement xhr.sendAsBinary()
            this.reader.readAsBinaryString(

                //specify the part of the file that should be sent
                //ZIH - Chrome may not support file.slice(),
                //      might have to duck-check for file.webkitSlice()
                this.file.slice(
                    this.status.bytes_sent,
                    ( this.status.bytes_sent + this.to_send )
                )
            );
        }

        //there are no more bytes left to send, check for load handler
        else if( this.onload != null ) {

            //fire the load event
            this.onload(
                {
                    'target'           : this,
                    'lengthComputable' : true,
                    'loaded'           : this.status.bytes_sent,
                    'total'            : this.status.bytes_total
                }
            );
        }

    };

    /*------------------------------------------------------------------------
    Private Properties
    ------------------------------------------------------------------------*/

    /*------------------------------------------------------------------------
    Private Methods
    ------------------------------------------------------------------------*/

    return ns;
} )( hz.upload || {} );

/*----------------------------------------------------------------------------
Attempting to add support for sendAsBinary() (thanks, webkit).
----------------------------------------------------------------------------*/

if( ( 'sendAsBinary' in XMLHttpRequest.prototype ) == false ) {
    XMLHttpRequest.prototype.sendAsBinary = function( data ) {
        var num_bytes = data.length;
        var uint8_data = new Uint8Array( num_bytes );
        for( var i = 0; i < num_bytes; ++i ) {
            uint8_data[ i ] = data.charCodeAt( i ) & 0xFF;
        }
        this.send( uint8_data );
    };
}
<|endoftext|>


<commit_before>import React from "react";
import PropTypes from "prop-types";
import styledSystemPropTypes from "@styled-system/prop-types";
import Events from "../../utils/helpers/events";
import StyledIconButton from "./icon-button.style";
import Icon from "../icon";
import { filterStyledSystemMarginProps } from "../../style/utils";

const marginPropTypes = filterStyledSystemMarginProps(
  styledSystemPropTypes.space
);

const IconButton = React.forwardRef(({ onAction, children, ...rest }, ref) => {
  const marginProps = filterStyledSystemMarginProps(rest);
  const onKeyDown = (e) => {
    if (Events.isEnterKey(e) || Events.isSpaceKey(e)) {
      e.preventDefault();
      onAction(e);
    } else {
      e.stopPropagation();
    }
  };

  const handleOnAction = (e) => {
    onAction(e);
  };

  return (
    <StyledIconButton
      {...rest}
      onKeyDown={onKeyDown}
      onClick={handleOnAction}
      ref={ref}
      {...marginProps}
    >
      {children}
    </StyledIconButton>
  );
});

IconButton.propTypes = {
  ...marginPropTypes,
  /** Children prop is restricted to one Icon Component */
  children: PropTypes.shape({
    type: PropTypes.oneOf([Icon, PropTypes.element]),
  }).isRequired,
  /** Callback */
  onAction: PropTypes.func.isRequired,
};

export default IconButton;
<commit_msg>fix(icon-button): ensure buttons have discernible text<commit_after>import React from "react";
import PropTypes from "prop-types";
import styledSystemPropTypes from "@styled-system/prop-types";
import Events from "../../utils/helpers/events";
import StyledIconButton from "./icon-button.style";
import Icon from "../icon";
import { filterStyledSystemMarginProps } from "../../style/utils";

const marginPropTypes = filterStyledSystemMarginProps(
  styledSystemPropTypes.space
);

const IconButton = React.forwardRef(
  (
    { "aria-label": ariaLabel, onAction, children, ...rest },

    ref
  ) => {
    const marginProps = filterStyledSystemMarginProps(rest);
    const onKeyDown = (e) => {
      if (Events.isEnterKey(e) || Events.isSpaceKey(e)) {
        e.preventDefault();
        onAction(e);
      } else {
        e.stopPropagation();
      }
    };

    const handleOnAction = (e) => {
      onAction(e);
    };

    return (
      <StyledIconButton
        {...rest}
        aria-label={ariaLabel}
        onKeyDown={onKeyDown}
        onClick={handleOnAction}
        ref={ref}
        {...marginProps}
      >
        {children}
      </StyledIconButton>
    );
  }
);

IconButton.propTypes = {
  ...marginPropTypes,
  /** Children prop is restricted to one Icon Component */
  children: PropTypes.shape({
    type: PropTypes.oneOf([Icon, PropTypes.element]),
  }).isRequired,
  /** Callback */
  onAction: PropTypes.func.isRequired,
  /** Prop to specify the aria-label of the icon-button component */
  "aria-label": PropTypes.string,
};

export default IconButton;
<|endoftext|>


<commit_before>var _      = require('lodash');
var fs     = require('fs');
var ipc    = require('ipc');
var path   = require('path');
var remote = require('remote');

var Dialog = remote.require('dialog');

var ui = {
  input: $('#input'),
  output: $('#output'),
  error: $('#error')
};

var state = (function() {
  var currentWindow = remote.getCurrentWindow();

  var that = {
    isDirty: false,

    reset: function(filename, data) {
      that.isDirty      = false;
      that.filename     = filename;
      that.originalData = data;

      currentWindow.setTitle(`VexEd - ${filename}`);
    },

    markDirty: function() {
      that.isDirty = true;

      if (that.filename) {
        currentWindow.setTitle(`VexEd - ${that.filename}*`);
      } else {
        currentWindow.setTitle(`VexEd - *`);
      }
    }
  };

  return that;
}());

var editor = ace.edit('input');
editor.session.setOption('useWorker', false);
editor.session.setMode('ace/mode/ini');

var vextab = require('./js/editor-renderer/vextab')(ui.input, ui.output, ui.error, editor);

editor.on('change', function() {
  if (editor.getValue !== state.originalData) {
    state.markDirty();
  }
  vextab.render();
});

ipc.on('file-open', function() {
  trySaveNotPersisted(function() {
    Dialog.showOpenDialog(null, {}, function(filenames) {
      if (filenames) {
        var filename = filenames[0];
        fs.readFile(filename, 'utf8', function(err, data) {
          if (err) {
            return Dialog.showErrorBox(`Error opening ${filename}`, err);
          }

          state.reset(filename, data);
          ui.input.innerText = data;
          vextab.render();
        });
      }
    });
  });
});

ipc.on('file-save', function() {
  saveFile();
});

ipc.on('file-save-as', function() {
  saveUnknownFile();
});

ipc.on('file-save-as-pdf', function() {
  var pdf = new jsPDF('s', 'mm');
  pdf.addImage(ui.output.toDataURL('image/png'), 'PNG', 10, 10);

  var filename;
  if (state.filename) {
    filename = path.basename(state.filename, '.vex') + '.pdf';
  } else {
    filename = 'Notation.pdf';
  }

  pdf.save(filename);
});

ipc.on('window-close', function() {
  trySaveNotPersisted(function() {
    ipc.send('app-quit');
  });
});

var saveFile = function(next) {
  if (state.filename) {
    saveKnownFile(state.filename, next);
  } else {
    saveUnknownFile(next);
  }
};

var saveUnknownFile = function(next) {
  Dialog.showSaveDialog(null, {}, function(filename) {
    if (filename) {
      saveKnownFile(filename, next);
    }
  });
};

var saveKnownFile = function(filename, next) {
  var data = ui.input.innerText;
  fs.writeFile(filename, data, function(err) {
    if (err) {
      return Dialog.showErrorBox(`Error saving ${filename}`, err);
    }

    state.reset(filename, data);
    if (next) { next(); }
  });
};

var trySaveNotPersisted = function(next) {
  if (state.isDirty) {
    Dialog.showMessageBox(null, {
      type: 'question',
      message: 'Save the changes?',
      buttons: ['Save', "Don't save"]
    }, function(response) {
      if (response === 0) {
        saveFile(next);
      } else {
        next();
      }
    });
  } else {
    next();
  }
};

var autoHeight = function() {
  var windowHeight = $(window).height();
  var elements = $('.auto-height');

  if ($('body').is('.view-vert')) {
    var heights = _.map(elements, function(e) { return $(e).height(); });
    heights.push(windowHeight);
    heights.push(650);
    height = _.max(heights);
  } else {
    height = windowHeight / 2;
  }

  elements.height(height);
};

var render = function() {
  autoHeight();
  vextab.render();
  editor.resize();
};

$(window).on('resize', function() {
  render();
});

var toggleSplit = function() {
  $('body').toggleClass('view-vert');
  render();
};

$('.view-switch-vert').on('click', function() {
  if ($('body').is(':not(.view-vert)')) {
    toggleSplit();
  }
});

$('.view-switch-horiz').on('click', function() {
  if ($('body').is('.view-vert')) {
    toggleSplit();
  }
});

ipc.on('view-switch-vert', function() {
  if ($('body').is(':not(.view-vert)')) {
    toggleSplit();
  }
});

ipc.on('view-switch-horiz', function() {
  if ($('body').is('.view-vert')) {
    toggleSplit();
  }
});

autoHeight();
vextab.render();
<commit_msg>Fixed PDF export<commit_after>var _      = require('lodash');
var fs     = require('fs');
var ipc    = require('ipc');
var path   = require('path');
var remote = require('remote');

var Dialog = remote.require('dialog');

var ui = {
  input: $('#input'),
  output: $('#output'),
  error: $('#error')
};

var state = (function() {
  var currentWindow = remote.getCurrentWindow();

  var that = {
    isDirty: false,

    reset: function(filename, data) {
      that.isDirty      = false;
      that.filename     = filename;
      that.originalData = data;

      currentWindow.setTitle(`VexEd - ${filename}`);
    },

    markDirty: function() {
      that.isDirty = true;

      if (that.filename) {
        currentWindow.setTitle(`VexEd - ${that.filename}*`);
      } else {
        currentWindow.setTitle(`VexEd - *`);
      }
    }
  };

  return that;
}());

var editor = ace.edit('input');
editor.session.setOption('useWorker', false);
editor.session.setMode('ace/mode/ini');

var vextab = require('./js/editor-renderer/vextab')(ui.input, ui.output, ui.error, editor);

editor.on('change', function() {
  if (editor.getValue !== state.originalData) {
    state.markDirty();
  }
  vextab.render();
});

ipc.on('file-open', function() {
  trySaveNotPersisted(function() {
    Dialog.showOpenDialog(null, {}, function(filenames) {
      if (filenames) {
        var filename = filenames[0];
        fs.readFile(filename, 'utf8', function(err, data) {
          if (err) {
            return Dialog.showErrorBox(`Error opening ${filename}`, err);
          }

          state.reset(filename, data);
          ui.input.innerText = data;
          vextab.render();
        });
      }
    });
  });
});

ipc.on('file-save', function() {
  saveFile();
});

ipc.on('file-save-as', function() {
  saveUnknownFile();
});

ipc.on('file-save-as-pdf', function() {
  var pdf = new jsPDF('s', 'mm');
  pdf.addImage(ui.output.get(0).toDataURL('image/png'), 'PNG', 10, 10);

  var filename;
  if (state.filename) {
    filename = path.basename(state.filename, '.vex') + '.pdf';
  } else {
    filename = 'Notation.pdf';
  }

  pdf.save(filename);
});

ipc.on('window-close', function() {
  trySaveNotPersisted(function() {
    ipc.send('app-quit');
  });
});

var saveFile = function(next) {
  if (state.filename) {
    saveKnownFile(state.filename, next);
  } else {
    saveUnknownFile(next);
  }
};

var saveUnknownFile = function(next) {
  Dialog.showSaveDialog(null, {}, function(filename) {
    if (filename) {
      saveKnownFile(filename, next);
    }
  });
};

var saveKnownFile = function(filename, next) {
  var data = ui.input.innerText;
  fs.writeFile(filename, data, function(err) {
    if (err) {
      return Dialog.showErrorBox(`Error saving ${filename}`, err);
    }

    state.reset(filename, data);
    if (next) { next(); }
  });
};

var trySaveNotPersisted = function(next) {
  if (state.isDirty) {
    Dialog.showMessageBox(null, {
      type: 'question',
      message: 'Save the changes?',
      buttons: ['Save', "Don't save"]
    }, function(response) {
      if (response === 0) {
        saveFile(next);
      } else {
        next();
      }
    });
  } else {
    next();
  }
};

var autoHeight = function() {
  var windowHeight = $(window).height();
  var elements = $('.auto-height');

  if ($('body').is('.view-vert')) {
    var heights = _.map(elements, function(e) { return $(e).height(); });
    heights.push(windowHeight);
    heights.push(650);
    height = _.max(heights);
  } else {
    height = windowHeight / 2;
  }

  elements.height(height);
};

var render = function() {
  autoHeight();
  vextab.render();
  editor.resize();
};

$(window).on('resize', function() {
  render();
});

var toggleSplit = function() {
  $('body').toggleClass('view-vert');
  render();
};

$('.view-switch-vert').on('click', function() {
  if ($('body').is(':not(.view-vert)')) {
    toggleSplit();
  }
});

$('.view-switch-horiz').on('click', function() {
  if ($('body').is('.view-vert')) {
    toggleSplit();
  }
});

ipc.on('view-switch-vert', function() {
  if ($('body').is(':not(.view-vert)')) {
    toggleSplit();
  }
});

ipc.on('view-switch-horiz', function() {
  if ($('body').is('.view-vert')) {
    toggleSplit();
  }
});

autoHeight();
vextab.render();
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

/*jshint forin:true, noarg:true, noempty:true, eqeqeq:true, bitwise:true,
  strict:true, undef:true, curly:true, browser:true, es5:true, esnext:true,
  indent:2, maxerr:50, devel:true, node:true, boss:true, white:true,
  globalstrict:true, nomen:false, newcap:true*/

/*global self:true, addon:true, dump:true */

"use strict";

var prefs = require('simple-prefs');
var tabs = require('tabs');
var winutils = require('window/utils');

const PLACEHOLDERS = [
  'Where do you want to go today?',
  'Just type ”google.com“.  You know you’re going to.',
  'Let’s do this thing!',
  'Hey, I wonder what we should have for lunch?',
  'Where to, boss?',
  'I hear Facebook is nice this time of year…',
  'You know you can search from here, right?',
  'Have you thought about trying Private Browsing Mode?',
  'You are in a maze of twisty web pages, all alike.',
  'Hi!  My name is Url.'
];

var hashTab = function (tab) {
  return tab.id % PLACEHOLDERS.length;
};

var tabActivate = function (tab) {
  var id = hashTab(tab);
  var window = winutils.getMostRecentBrowserWindow();
  window.gURLBar.placeholder = PLACEHOLDERS[id];
};

var run = function () {
  var window = winutils.getMostRecentBrowserWindow();
  window.gURLBar.placeholder = PLACEHOLDERS[0];
  tabs.on('activate', tabActivate);
};

var stop = function () {
  tabs.removeListener('activate', tabActivate);
  var window = winutils.getMostRecentBrowserWindow();
  window.gURLBar.placeholder = 'Search or enter address';
};

var listener = function (prefName) {
  if (prefs.prefs.urlbar) {
    run();
  } else {
    stop();
  }
};

exports.load = function () {
  prefs.on('urlbar', listener);
  listener('urlbar');
};

exports.unload = function () {
  prefs.removeListener('urlbar', listener);
};<commit_msg>Load the text from an etherpad.  (Yeah, it's secure, I checked. ;)<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

/*jshint forin:true, noarg:true, noempty:true, eqeqeq:true, bitwise:true,
  strict:true, undef:true, curly:true, browser:true, es5:true, esnext:true,
  indent:2, maxerr:50, devel:true, node:true, boss:true, white:true,
  globalstrict:true, nomen:false, newcap:true*/

/*global self:true, addon:true, dump:true */

"use strict";

var prefs = require('simple-prefs');
var Request = require('sdk/request').Request;
var tabs = require('tabs');
var winutils = require('window/utils');

var PLACEHOLDERS = [
  'Where do you want to go today?',
  'Just type ”google.com“.  You know you’re going to.',
  'Let’s do this thing!',
  'Hey, I wonder what we should have for lunch?',
  'Where to, boss?',
  'I hear Facebook is nice this time of year…',
  'You know you can search from here, right?',
  'Have you thought about trying Private Browsing Mode?',
  'You are in a maze of twisty web pages, all alike.',
  'Hi!  My name is Url.'
];

var hashTab = function (tab) {
  return tab.id % PLACEHOLDERS.length;
};

var tabActivate = function (tab) {
  var id = hashTab(tab);
  var window = winutils.getMostRecentBrowserWindow();
  window.gURLBar.placeholder = PLACEHOLDERS[id];
};

var loadPlaceholders = function () {
  var etherpadRequest = new Request({
    url: 'https://firefox-ux.etherpad.mozilla.org/ep/pad/export/urlbar-sayings/latest?format=txt',
    onComplete: function (response) {
      if (response.status !== 200) {
        return;
      }
      var result = response.text.split('\n');
      result = result.map(function (x) {
        return x.trim();
      }).filter(function (x) {
        return !x.startsWith('#') && (x !== '');
      });
      PLACEHOLDERS = result;
    }
  }).get();
};

var run = function () {
  var window = winutils.getMostRecentBrowserWindow();
  window.gURLBar.placeholder = PLACEHOLDERS[0];
  loadPlaceholders();
  tabs.on('activate', tabActivate);
};

var stop = function () {
  tabs.removeListener('activate', tabActivate);
  var window = winutils.getMostRecentBrowserWindow();
  window.gURLBar.placeholder = 'Search or enter address';
};

var listener = function (prefName) {
  if (prefs.prefs.urlbar) {
    run();
  } else {
    stop();
  }
};

exports.load = function () {
  prefs.on('urlbar', listener);
  listener('urlbar');
};

exports.unload = function () {
  prefs.removeListener('urlbar', listener);
};<|endoftext|>