text:
/* vendor/jquery.selector/jquery.class.js */

/**
 * Very basic Class utility. Based on base and jquery.class.
 *
 * Class definition: var Foo = Base.extend({ init: function(){ Constructor }; method_name: function(){ Method } });
 *
 * Inheritance: var Bar = Foo.extend({ method_name: function(){ this._super(); } });
 *
 * new-less Constructor: new Foo(arg) <-same as-> Foo(arg)
 */

var Base;

(function(){

	var marker = {}, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;

	// The base Class implementation (does nothing)
	Base = function(){};

	Base.addMethod = function(name, func) {
		var _super = this._super;
		if (_super && fnTest.test(func))	 {
			this.prototype[name] = function(){
				var tmp = this._super;
				this._super = _super[name];
				try {
					var ret = func.apply(this, arguments);
				}
				finally {
					this._super = tmp;
				}
				return ret;
			}
		}
		else this.prototype[name] = func;
	}

	Base.addMethods = function(props) {
		for (var name in props) {
			if (typeof props[name] == 'function') this.addMethod(name, props[name]);
			else this.prototype[name] = props[name];
		}
	}

	// Create a new Class that inherits from this class
	Base.extend = function(props) {

		// The dummy class constructor
		var Kls = function() {
			if (arguments[0] === marker) return;

			if (this instanceof Kls) {
				if (this.init) this.init.apply(this, arguments);
			}
			else {
				var ret = new Kls(marker); if (ret.init) ret.init.apply(ret, arguments); return ret;
			}
		}

		// Add the common class variables and methods
		Kls.constructor = Kls;
		Kls.extend = Base.extend;
		Kls.addMethod = Base.addMethod;
		Kls.addMethods = Base.addMethods;
		Kls._super = this.prototype;

		// Attach the parent object to the inheritance chain
		Kls.prototype = new this(marker);

		// Copy the properties over onto the new prototype
		Kls.addMethods(props);

		return Kls;
	};
})();;

/* vendor/jquery.selector/jquery.selector.js */

(function($){

	var tokens = {
		UNICODE: /\\[0-9a-f]{1,6}(?:\r\n|[ \n\r\t\f])?/,
		ESCAPE: /(?:UNICODE)|\\[^\n\r\f0-9a-f]/,
		NONASCII: /[^\x00-\x7F]/,
		NMSTART: /[_a-z]|(?:NONASCII)|(?:ESCAPE)/,
		NMCHAR: /[_a-z0-9-]|(?:NONASCII)|(?:ESCAPE)/,
		IDENT: /-?(?:NMSTART)(?:NMCHAR)*/,

		NL: /\n|\r\n|\r|\f/,

		STRING: /(?:STRING1)|(?:STRING2)|(?:STRINGBARE)/,
		STRING1: /"(?:(?:ESCAPE)|\\(?:NL)|[^\n\r\f\"])*"/,
		STRING2: /'(?:(?:ESCAPE)|\\(?:NL)|[^\n\r\f\'])*'/,
		STRINGBARE: /(?:(?:ESCAPE)|\\(?:NL)|[^\n\r\f\]])*/,

		FUNCTION: /(?:IDENT)\(\)/,

		INTEGER: /[0-9]+/,

		WITHN: /([-+])?(INTEGER)?(n)\s*(?:([-+])\s*(INTEGER))?/,
		WITHOUTN: /([-+])?(INTEGER)/
	}

	var rx = {
		not: /:not\(/,
		not_end: /\)/,

 		tag: /((?:IDENT)|\*)/,
		id: /#(IDENT)/,
		cls: /\.(IDENT)/,
		attr: /\[\s*(IDENT)\s*(?:([^=]?=)\s*(STRING)\s*)?\]/,
		pseudo_el: /(?::(first-line|first-letter|before|after))|(?:::((?:FUNCTION)|(?:IDENT)))/,
		pseudo_cls_nth: /:nth-child\(\s*(?:(?:WITHN)|(?:WITHOUTN)|(odd|even))\s*\)/,
		pseudo_cls: /:(IDENT)/,

		comb: /\s*(\+|~|>)\s*|\s+/,
		comma: /\s*,\s*/,
		important: /\s+!important\s*$/
	}

	/* Replace placeholders with actual regex, and mark all as case insensitive */
	var token = /[A-Z][A-Z0-9]+/;
	for (var k in rx) {
		var src = rx[k].source;
		while (m = src.match(token)) src = src.replace(m[0], tokens[m[0]].source);
		rx[k] = new RegExp(src, 'gi');
	}

	/**
	 * A string that matches itself against regexii, and keeps track of how much of itself has been matched
	 */
	var ConsumableString = Base.extend({
		init: function(str) {
			this.str = str;
			this.pos = 0;
		},
		match: function(rx) {
			var m;
			rx.lastIndex = this.pos;
			if ((m = rx.exec(this.str)) && m.index == this.pos ) {
				this.pos = rx.lastIndex ? rx.lastIndex : this.str.length ;
				return m;
			}
			return null;
		},
		peek: function(rx) {
			var m;
			rx.lastIndex = this.pos;
			if ((m = rx.exec(this.str)) && m.index == this.pos ) return m;
			return null;
		},
		showpos: function() {
			return this.str.slice(0,this.pos)+'<HERE>' + this.str.slice(this.pos);
		},
		done: function() {
			return this.pos == this.str.length;
		}
	})

	/* A base class that all Selectors inherit off */
	var SelectorBase = Base.extend({});

	/**
	 * A class representing a Simple Selector, as per the CSS3 selector spec
	 */
	var SimpleSelector = SelectorBase.extend({
		init: function() {
			this.tag = null;
			this.id = null;
			this.classes = [];
			this.attrs = [];
			this.nots = [];
			this.pseudo_classes = [];
			this.pseudo_els = [];
		},
		parse: function(selector) {
			var m;

			/* Pull out the initial tag first, if there is one */
			if (m = selector.match(rx.tag)) this.tag = m[1];

			/* Then for each selection type, try and find a match */
			do {
				if (m = selector.match(rx.not)) {
					this.nots[this.nots.length] = SelectorsGroup().parse(selector)
					if (!(m = selector.match(rx.not_end))) {
						throw 'Invalid :not term in selector';
					}
				}
				else if (m = selector.match(rx.id))         this.id = m[1];
				else if (m = selector.match(rx.cls))        this.classes[this.classes.length] = m[1];
				else if (m = selector.match(rx.attr))       this.attrs[this.attrs.length] = [ m[1], m[2], m[3] ];
				else if (m = selector.match(rx.pseudo_el))  this.pseudo_els[this.pseudo_els.length] = m[1] || m[2];
				else if (m = selector.match(rx.pseudo_cls_nth)) {
					if (m[3]) {
						var a = parseInt((m[1]||'')+(m[2]||'1'));
						var b = parseInt((m[4]||'')+(m[5]||'0'));
					}
					else {
						var a = m[8] ? 2 : 0;
						var b = m[8] ? (4-m[8].length) : parseInt((m[6]||'')+m[7]);
					}
					this.pseudo_classes[this.pseudo_classes.length] = ['nth-child', [a, b]];
				}
				else if (m = selector.match(rx.pseudo_cls)) this.pseudo_classes[this.pseudo_classes.length] = [m[1]];

			} while(m && !selector.done());

			return this;
		}
	})

	/**
	 * A class representing a Selector, as per the CSS3 selector spec
	 */
	var Selector = SelectorBase.extend({
		init: function(){
			this.parts = [];
		},
		parse: function(cons){
			this.parts[this.parts.length] = SimpleSelector().parse(cons);

			while (!cons.done() && !cons.peek(rx.comma) && (m = cons.match(rx.comb))) {
				this.parts[this.parts.length] = m[1] || ' ';
				this.parts[this.parts.length] = SimpleSelector().parse(cons);
			}

			return this.parts.length == 1 ? this.parts[0] : this;
		}
	});

	/**
	 * A class representing a sequence of selectors, as per the CSS3 selector spec
	 */
	var SelectorsGroup = SelectorBase.extend({
		init: function(){
			this.parts = [];
		},
		parse: function(cons){
			this.parts[this.parts.length] = Selector().parse(cons);

			while (!cons.done() && (m = cons.match(rx.comma))) {
				this.parts[this.parts.length] = Selector().parse(cons);
			}

			return this.parts.length == 1 ? this.parts[0] : this;
		}
	});

	$.selector = function(s){
		var cons = ConsumableString(s);
		var res = SelectorsGroup().parse(cons);

		res.selector = s;

		if (!cons.done()) throw 'Could not parse selector - ' + cons.showpos() ;
		else return res;
	}

	$.selector.SelectorBase = SelectorBase;
	$.selector.SimpleSelector = SimpleSelector;
	$.selector.Selector = Selector;
	$.selector.SelectorsGroup = SelectorsGroup;

})(jQuery)
;

/* vendor/jquery.selector/jquery.selector.specifity.js */

(function($) {

	$.selector.SimpleSelector.addMethod('specifity', function() {
		if (this.spec) return this.spec;

		var spec = [
			this.id ? 1 : 0,
			this.classes.length + this.attrs.length + this.pseudo_classes.length,
			((this.tag && this.tag != '*') ? 1 : 0) + this.pseudo_els.length
		];
		$.each(this.nots, function(i,not){
			var ns = not.specifity(); spec[0] += ns[0]; spec[1] += ns[1]; spec[2] += ns[2];
		});

		return this.spec = spec;
	})

	$.selector.Selector.addMethod('specifity', function(){
		if (this.spec) return this.spec;

		var spec = [0,0,0];
		$.each(this.parts, function(i,part){
			if (i%2) return;
			var ps = part.specifity(); spec[0] += ps[0]; spec[1] += ps[1]; spec[2] += ps[2];
		});

		return this.spec = spec;
	})

	$.selector.SelectorsGroup.addMethod('specifity', function(){
		if (this.spec) return this.spec;

		var spec = [0,0,0];
		$.each(this.parts, function(i,part){
			var ps = part.specifity(); spec[0] += ps[0]; spec[1] += ps[1]; spec[2] += ps[2];
		});

		return this.spec = spec;
	})

})(jQuery);
;

/* vendor/jquery.selector/jquery.selector.matches.js */

/*
This attempts to do the opposite of Sizzle.
Sizzle is good for finding elements for a selector, but not so good for telling if an individual element matches a selector
*/

(function($) {

	/**** CAPABILITY TESTS ****/
	var div = document.createElement('div');
	div.innerHTML = '<form id="test"><input name="id" type="text"/></form>';

	// In IE 6-7, getAttribute often does the wrong thing (returns similar to el.attr), so we need to use getAttributeNode on that browser
	var getAttributeDodgy = div.firstChild.getAttribute('id') !== 'test';

	// Does browser support Element.firstElementChild, Element.previousElementSibling, etc.
	var hasElementTraversal = div.firstElementChild && div.firstElementChild.tagName == 'FORM';

	// Does browser support Element.children
	var hasChildren = div.children && div.children[0].tagName == 'FORM';

	var FUNC_IN  = /^\s*function\s*\([^)]*\)\s*{/;
	var FUNC_OUT = /}\s*$/;

	var funcToString = function(f) {
		return (''+f).replace(FUNC_IN,'').replace(FUNC_OUT,'');
	}

	// Can we use Function#toString ?
	try {
		var testFunc = function(){ return 'good' };
		if ((new Function('',funcToString(testFunc)))() != 'good') funcToString = false;
	}
	catch(e) { funcToString = false; console.log(e.message);/*pass*/ }

	/**** INTRO ****/

	var GOOD = /GOOD/g;
	var BAD = /BAD/g;

	var STARTS_WITH_QUOTES = /^['"]/g;

	var join = function(js) {
		return js.join('\n');
	}

	var join_complex = function(js) {
		code = new String(js.join('\n')); // String objects can have properties set. strings can't
		code.complex = true;
		return code;
	}

	/**** ATTRIBUTE ACCESSORS ****/

	// Not all attribute names can be used as identifiers, so we encode any non-acceptable characters as hex
	var varForAttr = function(attr) {
		return '_' + attr.replace(/^[^A-Za-z]|[^A-Za-z0-9]/g, function(m){ return '_0x' + m.charCodeAt(0).toString(16) + '_'; });
	}

	var getAttr;

	// Good browsers
	if (!getAttributeDodgy) {
		getAttr = function(attr){ return 'var '+varForAttr(attr)+' = el.getAttribute("'+attr+'");' ; }
	}
	// IE 6, 7
	else {
		// On IE 6 + 7, getAttribute still has to be called with DOM property mirror name, not attribute name. Map attributes to those names
		var getAttrIEMap = { 'class': 'className', 'for': 'htmlFor' };

		getAttr = function(attr) {
			var ieattr = getAttrIEMap[attr] || attr;
			return 'var '+varForAttr(attr)+' = el.getAttribute("'+ieattr+'",2) || (el.getAttributeNode("'+attr+'")||{}).nodeValue;';
		}
	}

	/**** ATTRIBUTE COMPARITORS ****/

	var attrchecks = {
		'-':  '!K',
		'=':  'K != "V"',
		'!=': 'K == "V"',
		'~=': '_WS_K.indexOf(" V ") == -1',
		'^=': '!K || K.indexOf("V") != 0',
		'*=': '!K || K.indexOf("V") == -1',
		'$=': '!K || K.substr(K.length-"V".length) != "V"'
	}

	/**** STATE TRACKER ****/

	var State = $.selector.State = Base.extend({
		init: function(){
			this.reset();
		},
		reset: function() {
			this.attrs = {}; this.wsattrs = {};
		},

		prev: function(){
			this.reset();
			if (hasElementTraversal) return 'el = el.previousElementSibling';
			return 'while((el = el.previousSibling) && el.nodeType != 1) {}';
		},
		next: function() {
			this.reset();
			if (hasElementTraversal) return 'el = el.nextElementSibling';
			return 'while((el = el.nextSibling) && el.nodeType != 1) {}';
		},
		prevLoop: function(body){
			this.reset();
			if (hasElementTraversal) return join([ 'while(el = el.previousElementSibling){', body]);
			return join([
				'while(el = el.previousSibling){',
					'if (el.nodeType != 1) continue;',
					body,
			]);
		},
		parent: function() {
			this.reset();
			return 'el = el.parentNode;';
		},
		parentLoop: function(body) {
			this.reset();
			return join([
				'while((el = el.parentNode) && el.nodeType == 1){',
					body,
				'}'
			]);
		},

		uses_attr: function(attr) {
			if (this.attrs[attr]) return;
			this.attrs[attr] = true;
			return getAttr(attr);
		},
		uses_wsattr: function(attr) {
			if (this.wsattrs[attr]) return;
			this.wsattrs[attr] = true;
			return join([this.uses_attr(attr), 'var _WS_'+varForAttr(attr)+' = " "+'+varForAttr(attr)+'+" ";']);
		},

		save: function(lbl) {
			return 'var el'+lbl+' = el;';
		},
		restore: function(lbl) {
			this.reset();
			return 'el = el'+lbl+';';
		}
	});

	/**** PSEUDO-CLASS DETAILS ****/

	var pseudoclschecks = {
		'first-child': join([
			'var cel = el;',
			'while(cel = cel.previousSibling){ if (cel.nodeType === 1) BAD; }',
		]),
		'last-child': join([
			'var cel = el;',
			'while(cel = cel.nextSibling){ if (cel.nodeType === 1) BAD; }'
		]),
		'nth-child': function(a,b) {
			var get_i = join([
				'var i = 1, cel = el;',
				'while(cel = cel.previousSibling){',
					'if (cel.nodeType === 1) i++;',
				'}',
			]);

			if (a == 0) return join([
				get_i,
				'if (i- '+b+' != 0) BAD;'
			]);
			else if (b == 0 && a >= 0) return join([
				get_i,
				'if (i%'+a+' != 0 || i/'+a+' < 0) BAD;'
			]);
			else if (b == 0 && a < 0) return join([
				'BAD;'
			]);
			else return join([
				get_i,
				'if ((i- '+b+')%'+a+' != 0 || (i- '+b+')/'+a+' < 0) BAD;'
			]);
		}
	};

	// Needs to refence contents of object, so must be injected after definition
	pseudoclschecks['only-child'] = join([
		pseudoclschecks['first-child'],
		pseudoclschecks['last-child']
	]);

	/**** SimpleSelector ****/

	$.selector.SimpleSelector.addMethod('compile', function(el) {
		var js = [];

		/* Check against element name */
		if (this.tag && this.tag != '*') {
			js[js.length] = 'if (el.tagName != "'+this.tag.toUpperCase()+'") BAD;';
		}

		/* Check against ID */
		if (this.id) {
			js[js.length] = el.uses_attr('id');
			js[js.length] = 'if (_id !== "'+this.id+'") BAD;';
		}

		/* Build className checking variable */
		if (this.classes.length) {
			js[js.length] = el.uses_wsattr('class');

			/* Check against class names */
			$.each(this.classes, function(i, cls){
				js[js.length] = 'if (_WS__class.indexOf(" '+cls+' ") == -1) BAD;';
			})
		}

		/* Check against attributes */
		$.each(this.attrs, function(i, attr){
			js[js.length] = (attr[1] == '~=') ? el.uses_wsattr(attr[0]) : el.uses_attr(attr[0]);
			var check = attrchecks[ attr[1] || '-' ];
			check = check.replace( /K/g, varForAttr(attr[0])).replace( /V/g, attr[2] && attr[2].match(STARTS_WITH_QUOTES) ? attr[2].slice(1,-1) : attr[2] );
			js[js.length] = 'if ('+check+') BAD;';
		});

		/* Check against nots */
		$.each(this.nots, function(i, not){
			var lbl = ++lbl_id;
			var func = join([
				'l'+lbl+':{',
					not.compile(el).replace(BAD, 'break l'+lbl).replace(GOOD, 'BAD'),
				'}'
			]);

			if (!(not instanceof $.selector.SimpleSelector)) func = join([
				el.save(lbl),
				func,
				el.restore(lbl)
			])

			js[js.length] = func;
		});

		/* Check against pseudo-classes */
		$.each(this.pseudo_classes, function(i, pscls){
			var check = pseudoclschecks[pscls[0]];
			if (check) {
				js[js.length] = ( typeof check == 'function' ? check.apply(this, pscls[1]) : check );
			}
			else if (check = $.find.selectors.filters[pscls[0]]) {
				if (funcToString) {
					js[js.length] = funcToString(check).replace(/elem/g,'el').replace(/return([^;]+);/,'if (!($1)) BAD;');
				}
				else {
					js[js.length] = 'if (!$.find.selectors.filters.'+pscls[0]+'(el)) BAD;'
				}
			}
		});

		js[js.length] = 'GOOD';

		/* Pass */
		return join(js);
	});

	var lbl_id = 0;
	/** Turns an compiled fragment into the first part of a combination */
	function as_subexpr(f) {
		if (f.complex)
			return join([
				'l'+(++lbl_id)+':{',
					f.replace(GOOD, 'break l'+lbl_id),
				'}',
			]);
		else
			return f.replace(GOOD, '');
	}

	var combines = {
		' ': function(el, f1, f2) {
			return join_complex([
				f2,
				'while(true){',
					el.parent(),
					'if (!el || el.nodeType !== 1) BAD;',
					f1.compile(el).replace(BAD, 'continue'),
				'}'
			]);
		},

		'>': function(el, f1, f2) {
			return join([
				f2,
				el.parent(),
				'if (!el || el.nodeType !== 1) BAD;',
				f1.compile(el)
			]);
		},

		'~': function(el, f1, f2) {
			return join_complex([
				f2,
				el.prevLoop(),
					f1.compile(el).replace(BAD, 'continue'),
				'}',
				'BAD;'
			]);
		},

		'+': function(el, f1, f2) {
			return join([
				f2,
				el.prev(),
				'if (!el) BAD;',
				f1.compile(el)
			]);
		}
	};

	$.selector.Selector.addMethod('compile', function(el) {
		l = this.parts.length;

		expr = this.parts[--l].compile(el);
		while (l) {
			combinator = this.parts[--l];
			expr = combines[combinator](el, this.parts[--l], as_subexpr(expr));
		}

		return expr;
	});

	$.selector.SelectorsGroup.addMethod('compile', function(el) {
		var expr = [], lbl = ++lbl_id;

		for (var i=0; i < this.parts.length; i++) {
			expr[expr.length] = join([
				i == 0 ? el.save(lbl) : el.restore(lbl),
				'l'+lbl+'_'+i+':{',
					this.parts[i].compile(el).replace(BAD, 'break l'+lbl+'_'+i),
				'}'
			]);
		}

		expr[expr.length] = 'BAD;';
		return join(expr);
	});

	$.selector.SelectorBase.addMethod('matches', function(el){
		this.matches = new Function('el', join([
			'if (!el) return false;',
			this.compile(new State()).replace(BAD, 'return false').replace(GOOD, 'return true')
		]));
		return this.matches(el);
	});

})(jQuery);

;

/* src/jquery.focusinout.js */

(function($){

	/**
	 * Add focusin and focusout support to bind and live for browers other than IE. Designed to be usable in a delegated fashion (like $.live)
	 * Copyright (c) 2007 Jörn Zaefferer
	 */
	$.support.focusInOut = !!($.browser.msie);
	if (!$.support.focusInOut) {
		// Emulate focusin and focusout by binding focus and blur in capturing mode
		$.each({focus: 'focusin', blur: 'focusout'}, function(original, fix){
			$.event.special[fix] = {
				setup: function(){
					if (!this.addEventListener) return false;
					this.addEventListener(original, $.event.special[fix].handler, true);
				},
				teardown: function(){
					if (!this.removeEventListener) return false;
					this.removeEventListener(original, $.event.special[fix].handler, true);
				},
				handler: function(e){
					arguments[0] = $.event.fix(e);
					arguments[0].type = fix;
					return $.event.handle.apply(this, arguments);
				}
			};
		});
	}

	(function(){
		//IE has some trouble with focusout with select and keyboard navigation
		var activeFocus = null;

		$(document)
			.bind('focusin', function(e){
				var target = e.realTarget || e.target;
				if (activeFocus && activeFocus !== target) {
					e.type = 'focusout';
					$(activeFocus).trigger(e);
					e.type = 'focusin';
					e.target = target;
				}
				activeFocus = target;
			})
			.bind('focusout', function(e){
				activeFocus = null;
			});
	})();

})(jQuery);;

/* src/jquery.entwine.js */

var console;

(function($) {

	var namespaces = {};

	$.entwine = function() {
		$.fn.entwine.apply(null, arguments);
	}

	/**
	 * A couple of utility functions for accessing the store outside of this closure, and for making things
	 * operate in a little more easy-to-test manner
	 */
	$.extend($.entwine, {
		/**
		 * Get all the namespaces. Useful for introspection? Internal interface of Namespace not guaranteed consistant
		 */
		namespaces: namespaces,

		/**
		 * Remove all entwine rules
		 */
		clear_all_rules: function() {
			// Remove proxy functions
			for (var k in $.fn) { if ($.fn[k].entwine) delete $.fn[k] ; }
			// Remove bound events - TODO: Make this pluggable, so this code can be moved to jquery.entwine.events.js
			$(document).unbind('.entwine');
			// Remove namespaces, and start over again
			namespaces = $.entwine.namespaces = {};
		},

		WARN_LEVEL_NONE: 0,
		WARN_LEVEL_IMPORTANT: 1,
		WARN_LEVEL_BESTPRACTISE: 2,

		/**
		 * Warning level. Set to a higher level to get warnings dumped to console.
		 */
		warningLevel: 0,

		/** Utility to optionally display warning messages depending on level */
		warn: function(message, level) {
			if (level <= $.entwine.warningLevel && console && console.warn) {
				console.warn(message);
				if (console.trace) console.trace();
			}
		},

		warn_exception: function(where, /* optional: */ on, e) {
			if ($.entwine.WARN_LEVEL_IMPORTANT <= $.entwine.warningLevel && console && console.warn) {
				if (arguments.length == 2) { e = on; on = null; }

				if (on) console.warn('Uncaught exception',e,'in',where,'on',on);
				else    console.warn('Uncaught exception',e,'in',where);

				if (e.stack) console.warn("Stack Trace:\n" + e.stack);
			}
		}
	});

	/** Stores a count of definitions, so that we can sort identical selectors by definition order */
	var rulecount = 0;

	var Rule = Base.extend({
		init: function(selector, name) {
			this.selector = selector;
			this.specifity = selector.specifity();
			this.important = 0;
			this.name = name;
			this.rulecount = rulecount++;
		}
	});

	Rule.compare = function(a, b) {
		var as = a.specifity, bs = b.specifity;

		return (a.important - b.important) ||
		       (as[0] - bs[0]) ||
		       (as[1] - bs[1]) ||
		       (as[2] - bs[2]) ||
		       (a.rulecount - b.rulecount) ;
	}

	$.entwine.RuleList = function() {
		var list = [];

		list.addRule = function(selector, name){
			var rule = Rule(selector, name);

			list[list.length] = rule;
			list.sort(Rule.compare);

			return rule;
		};

		return list;
	}

	var handlers = [];

	/**
	 * A Namespace holds all the information needed for adding entwine methods to a namespace (including the _null_ namespace)
	 */
	$.entwine.Namespace = Base.extend({
		init: function(name){
			if (name && !name.match(/^[A-Za-z0-9.]+$/)) $.entwine.warn('Entwine namespace '+name+' is not formatted as period seperated identifiers', $.entwine.WARN_LEVEL_BESTPRACTISE);
			name = name || '__base';

			this.name = name;
			this.store = {};

			namespaces[name] = this;

			if (name == "__base") {
				this.injectee = $.fn
				this.$ = $;
			}
			else {
				// We're in a namespace, so we build a Class that subclasses the jQuery Object Class to inject namespace functions into
				var subfn = function(){}
				this.injectee = subfn.prototype = new $();

				// And then we provide an overriding $ that returns objects of our new Class, and an overriding pushStack to catch further selection building
				var bound$ = this.$ = function(a) {
					// Try the simple way first
					var jq = $.fn.init.apply(new subfn(), arguments);
					if (jq instanceof subfn) return jq;

					// That didn't return a bound object, so now we need to copy it
					var rv = new subfn();
					rv.selector = jq.selector; rv.context = jq.context; var i = rv.length = jq.length;
					while (i--) rv[i] = jq[i];
					return rv;
				}
				this.injectee.pushStack = function(elems, name, selector){
					var ret = bound$(elems);

					// Add the old object onto the stack (as a reference)
					ret.prevObject = this;
					ret.context = this.context;

					if ( name === "find" ) ret.selector = this.selector + (this.selector ? " " : "") + selector;
					else if ( name )       ret.selector = this.selector + "." + name + "(" + selector + ")";

					// Return the newly-formed element set
					return ret;
				}

				// Copy static functions through from $ to this.$ so e.g. $.ajax still works
				// @bug, @cantfix: Any class functions added to $ after this call won't get mirrored through
				$.extend(this.$, $);

				// We override entwine to inject the name of this namespace when defining blocks inside this namespace
				var entwine_wrapper = this.injectee.entwine = function(spacename) {
					var args = arguments;

					if (!spacename || typeof spacename != 'string') { args = $.makeArray(args); args.unshift(name); }
					else if (spacename.charAt(0) != '.') args[0] = name+'.'+spacename;

					return $.fn.entwine.apply(this, args);
				}

				this.$.entwine = function() {
					entwine_wrapper.apply(null, arguments);
				}

				for (var i = 0; i < handlers.length; i++) {
					var handler = handlers[i], builder;

					// Inject jQuery object method overrides
					if (builder = handler.namespaceMethodOverrides) {
						var overrides = builder(this);
						for (var k in overrides) this.injectee[k] = overrides[k];
					}

					// Inject $.entwine function overrides
					if (builder = handler.namespaceStaticOverrides) {
						var overrides = builder(this);
						for (var k in overrides) this.$.entwine[k] = overrides[k];
					}
				}
			}
		},

		/**
		 * Returns a function that does selector matching against the function list for a function name
		 * Used by proxy for all calls, and by ctorProxy to handle _super calls
		 * @param {String} name - name of the function as passed in the construction object
		 * @param {String} funcprop - the property on the Rule object that gives the actual function to call
		 * @param {function} basefunc - the non-entwine function to use as the catch-all function at the bottom of the stack
		 */
		one: function(name, funcprop, basefunc) {
			var namespace = this;
			var funcs = this.store[name];

			var one = function(el, args, i){
				if (i === undefined) i = funcs.length;
				while (i--) {
					if (funcs[i].selector.matches(el)) {
						var ret, tmp_i = el.i, tmp_f = el.f;
						el.i = i; el.f = one;
						try { ret = funcs[i][funcprop].apply(namespace.$(el), args); }
						finally { el.i = tmp_i; el.f = tmp_f; }
						return ret;
					}
				}
				// If we didn't find a entwine-defined function, but there is a non-entwine function to use as a base, try that
				if (basefunc) return basefunc.apply(namespace.$(el), args);
			}

			return one;
		},

		/**
		 * A proxy is a function attached to a callable object (either the base jQuery.fn or a subspace object) which handles
		 * finding and calling the correct function for each member of the current jQuery context
		 * @param {String} name - name of the function as passed in the construction object
		 * @param {function} basefunc - the non-entwine function to use as the catch-all function at the bottom of the stack
		 */
		build_proxy: function(name, basefunc) {
			var one = this.one(name, 'func', basefunc);

			var prxy = function() {
				var rv, ctx = $(this);

				var i = ctx.length;
				while (i--) rv = one(ctx[i], arguments);
				return rv;
			};

			return prxy;
		},

		bind_proxy: function(selector, name, func) {
			var rulelist = this.store[name] || (this.store[name] = $.entwine.RuleList());

			var rule = rulelist.addRule(selector, name); rule.func = func;

			if (!this.injectee.hasOwnProperty(name) || !this.injectee[name].entwine) {
				this.injectee[name] = this.build_proxy(name, this.injectee.hasOwnProperty(name) ? this.injectee[name] : null);
				this.injectee[name].entwine = true;
			}

			if (!this.injectee[name].entwine) {
				$.entwine.warn('Warning: Entwine function '+name+' clashes with regular jQuery function - entwine function will not be callable directly on jQuery object', $.entwine.WARN_LEVEL_IMPORTANT);
			}
		},

		add: function(selector, data) {
			// For every item in the hash, try ever method handler, until one returns true
			for (var k in data) {
				var v = data[k];

				for (var i = 0; i < handlers.length; i++) {
					if (handlers[i].bind && handlers[i].bind.call(this, selector, k, v)) break;
				}
			}
		},

		has: function(ctx, name) {
			var rulelist = this.store[name];
			if (!rulelist) return false;

			/* We go forward this time, since low specifity is likely to knock out a bunch of elements quickly */
			for (var i = 0 ; i < rulelist.length; i++) {
				ctx = ctx.not(rulelist[i].selector);
				if (!ctx.length) return true;
			}
			return false;
		}
	});

	/**
	 * A handler is some javascript code that adds support for some time of key / value pair passed in the hash to the Namespace add method.
	 * The default handlers provided (and included by default) are event, ctor and properties
	 */
	$.entwine.Namespace.addHandler = function(handler) {
		for (var i = 0; i < handlers.length && handlers[i].order < handler.order; i++) { /* Pass */ }
		handlers.splice(i, 0, handler);
	}

	$.entwine.Namespace.addHandler({
		order: 50,

		bind: function(selector, k, v){
			if ($.isFunction(v)) {
				this.bind_proxy(selector, k, v);
				return true;
			}
		}
	});

	$.extend($.fn, {
		/**
		 * Main entwine function. Used for new definitions, calling into a namespace (or forcing the base namespace) and entering a using block
		 *
		 */
		entwine: function(spacename) {
			var i = 0;
			/* Don't actually work out selector until we try and define something on it - we might be opening a namespace on an function-traveresed object
			   which have non-standard selectors like .parents(.foo).slice(0,1) */
			var selector = null;

			/* By default we operator on the base namespace */
			var namespace = namespaces.__base || $.entwine.Namespace();

			/* If the first argument is a string, then it's the name of a namespace. Look it up */
			if (typeof spacename == 'string') {
				if (spacename.charAt('0') == '.') spacename = spacename.substr(1);
				if (spacename) namespace = namespaces[spacename] || $.entwine.Namespace(spacename);
				i=1;
			}

			/* All remaining arguments should either be using blocks or definition hashs */
			while (i < arguments.length) {
				var res = arguments[i++];

				// If it's a function, call it - either it's a using block or it's a namespaced entwine definition
				if ($.isFunction(res)) {
					if (res.length != 1) $.entwine.warn('Function block inside entwine definition does not take $ argument properly', $.entwine.WARN_LEVEL_IMPORTANT);
					res = res.call(namespace.$(this), namespace.$);
				}

				// If we have a entwine definition hash, inject it into namespace
				if (res) {
					if (selector === null) selector = this.selector ? $.selector(this.selector) : false;

					if (selector) namespace.add(selector, res);
					else $.entwine.warn('Entwine block given to entwine call without selector. Make sure you call $(selector).entwine when defining blocks', $.entwine.WARN_LEVEL_IMPORTANT);
				}
			}

			/* Finally, return the jQuery object 'this' refers to, wrapped in the new namespace */
			return namespace.$(this);
		},

		/**
		 * Calls the next most specific version of the current entwine method
		 */
		_super: function(){
			var rv, i = this.length;
			while (i--) {
				var el = this[0];
				rv = el.f(el, arguments, el.i);
			}
			return rv;
		}
	});

})(jQuery);
;

/* src/jquery.entwine.dommaybechanged.js */

(function($){

	/** What to call to run a function 'soon'. Normally setTimeout, but for syncronous mode we override so soon === now */
	var runSoon = window.setTimeout;

	/** The timer handle for the asyncronous matching call */
	var check_id = null;

	/** Fire the change event. Only fires on the document node, so bind to that */
	var triggerEvent = function() {
		$(document).triggerHandler('DOMMaybeChanged');
		check_id = null;
	}

	$.extend($.entwine, {
		/**
		 * Make onmatch and onunmatch work in synchronous mode - that is, new elements will be detected immediately after
		 * the DOM manipulation that made them match. This is only really useful for during testing, since it's pretty slow
		 * (otherwise we'd make it the default).
		 */
		synchronous_mode: function() {
			if (check_id) clearTimeout(check_id); check_id = null;
			runSoon = function(func, delay){ func.call(this); return null; }
		},

		/**
		 * Trigger onmatch and onunmatch now - usefull for after DOM manipulation by methods other than through jQuery.
		 * Called automatically on document.ready
		 */
		triggerMatching: function() {
			matching();
		}
	});

	function registerMutateFunction() {
		$.each(arguments, function(i,func){
			var old = $.fn[func];
			$.fn[func] = function() {
				var rv = old.apply(this, arguments);
				if (!check_id) check_id = runSoon(triggerEvent, 100);
				return rv;
			}
		})
	}

	function registerSetterGetterFunction() {
		$.each(arguments, function(i,func){
			var old = $.fn[func];
			$.fn[func] = function(a, b) {
				var rv = old.apply(this, arguments);
				if (!check_id && (b !== undefined || typeof a != 'string')) check_id = runSoon(triggerEvent, 100);
				return rv;
			}
		})
	}

	// Register core DOM manipulation methods
	registerMutateFunction('append', 'prepend', 'after', 'before', 'wrap', 'removeAttr', 'addClass', 'removeClass', 'toggleClass', 'empty', 'remove');
	registerSetterGetterFunction('attr');

	// And on DOM ready, trigger matching once
	$(function(){ triggerEvent(); })

})(jQuery);;

/* src/jquery.entwine.events.js */

(function($) {

	/* If we are any browser other than IE or Safari, we don't have to do anything special to handle
	 * onchange delegation */
	$.support.bubblingChange = !($.browser.msie || $.browser.safari);

	/* Return true if node b is the same as, or is a descendant of, node a */
	if (document.compareDocumentPosition) {
		var is_or_contains = function(a, b) {
			return a && b && (a == b || !!(a.compareDocumentPosition(b) & 16));
		}
	}
	else {
		var is_or_contains = function(a, b) {
			return a && b && (a == b || (a.contains ? a.contains(b) : true));
		}
	}

	/* Add the methods to handle event binding to the Namespace class */
	$.entwine.Namespace.addMethods({
		build_event_proxy: function(name) {
			var one = this.one(name, 'func');

			var prxy = function(e, data) {
				// For events that do not bubble we manually trigger delegation (see delegate_submit below)
				// If this event is a manual trigger, the event we actually want to bubble is attached as a property of the passed event
				e = e.delegatedEvent || e;

				var el = e.target;
				while (el && el.nodeType == 1 && !e.isPropagationStopped()) {
					var ret = one(el, arguments);
					if (ret !== undefined) e.result = ret;
					if (ret === false) { e.preventDefault(); e.stopPropagation(); }

					el = el.parentNode;
				}
			};

			return prxy;
		},

		build_mouseenterleave_proxy: function(name) {
			var one = this.one(name, 'func');

			var prxy = function(e) {
				var el = e.target;
				var rel = e.relatedTarget;

				while (el && el.nodeType == 1 && !e.isPropagationStopped()) {
					/* We know el contained target. If it also contains relatedTarget then we didn't mouseenter / leave. What's more, every ancestor will also
					contan el and rel, and so we can just stop bubbling */
					if (is_or_contains(el, rel)) break;

					var ret = one(el, arguments);
					if (ret !== undefined) e.result = ret;
					if (ret === false) { e.preventDefault(); e.stopPropagation(); }

					el = el.parentNode;
				}
			};

			return prxy;
		},

		build_change_proxy: function(name) {
			var one = this.one(name, 'func');

			var prxy = function(e) {
				var el = e.target;
				// If this is a keydown event, only worry about the enter key, since browsers only trigger onchange on enter or focus loss
				if (e.type === 'keydown' && e.keyCode !== 13) return;
				// Make sure this is event is for an input type we're interested in
				if (el.tagName !== 'INPUT' && el.tagName !== 'TEXTAREA' && el.tagName !== 'SELECT') return;

				var $el = $(el), nowVal, oldVal = $el.data('changeVal');

				// Detect changes on checkboxes & radiobuttons, which have different value logic. We don't use el.value, since el is part
				// of a set, and we only want to raise onchange once for a single user action.
				if (el.type == 'checkbox' || el.type == 'radio') {
					if (!el.disabled && e.type === 'click') {
						nowVal = el.checked;
						// If radio, we get two changes - the activation, and the deactivation. We only want to fire one change though
						if ((el.type === 'checkbox' || nowVal === true) && oldVal !== nowVal) e.type = 'change';
					}
				}
				// Detect changes on other input types. In this case value is OK.
				else {
					nowVal = el.value;
					if (oldVal !== undefined && oldVal !== nowVal) e.type = 'change';
				}

				// Save the current value for next time
				if (nowVal !== undefined) $el.data('changeVal', nowVal);

				// And if we decided that a change happened, do the actual triggering
				if (e.type == 'change') {
					while (el && el.nodeType == 1 && !e.isPropagationStopped()) {
						var ret = one(el, arguments);
						if (ret !== undefined) e.result = ret;
						if (ret === false) { e.preventDefault(); e.stopPropagation(); }

						el = el.parentNode;
					}
				}
			};

			return prxy;
		},

		bind_event: function(selector, name, func, event) {
			var funcs = this.store[name] || (this.store[name] = $.entwine.RuleList()) ;
			var proxies = funcs.proxies || (funcs.proxies = {});

			var rule = funcs.addRule(selector, name); rule.func = func;

			if (!proxies[name]) {
				switch (name) {
					case 'onmouseenter':
						proxies[name] = this.build_mouseenterleave_proxy(name);
						event = 'mouseover';
						break;
					case 'onmouseleave':
						proxies[name] = this.build_mouseenterleave_proxy(name);
						event = 'mouseout';
						break;
					case 'onchange':
						if (!$.support.bubblingChange) {
							proxies[name] = this.build_change_proxy(name);
							event = 'click focusin focusout keydown';
						}
						break;
					case 'onsubmit':
						event = 'delegatedSubmit';
						break;
					case 'onfocus':
					case 'onblur':
						$.entwine.warn('Event '+event+' not supported - using focusin / focusout instead', $.entwine.WARN_LEVEL_IMPORTANT);
				}

				// If none of the special handlers created a proxy, use the generic proxy
				if (!proxies[name]) proxies[name] = this.build_event_proxy(name);

				$(document).bind(event+'.entwine', proxies[name]);
			}
		}
	});

	$.entwine.Namespace.addHandler({
		order: 40,

		bind: function(selector, k, v){
			var match, event;
			if ($.isFunction(v) && (match = k.match(/^on(.*)/))) {
				event = match[1];
				this.bind_event(selector, k, v, event);
				return true;
			}
		}
	});

	// Find all forms and bind onsubmit to trigger on the document too.
	// This is the only event that can't be grabbed via delegation

	var form_binding_cache = $([]); // A cache for already-handled form elements
	var delegate_submit = function(e, data){
		var delegationEvent = $.Event('delegatedSubmit'); delegationEvent.delegatedEvent = e;
		return $(document).trigger(delegationEvent, data);
	}

	$(document).bind('DOMMaybeChanged', function(){
		var forms = $('form');
		// Only bind to forms we haven't processed yet
		forms.not(form_binding_cache).bind('submit', delegate_submit);
		// Then remember the current set of forms
		form_binding_cache = forms;
	});

})(jQuery);
	;

/* src/jquery.entwine.ctors.js */

(function($) {

	/* Add the methods to handle constructor & destructor binding to the Namespace class */
	$.entwine.Namespace.addMethods({
		bind_condesc: function(selector, name, func) {
			var ctors = this.store.ctors || (this.store.ctors = $.entwine.RuleList()) ;

			var rule;
			for (var i = 0 ; i < ctors.length; i++) {
				if (ctors[i].selector.selector == selector.selector) {
					rule = ctors[i]; break;
				}
			}
			if (!rule) {
				rule = ctors.addRule(selector, 'ctors');
			}

			rule[name] = func;

			if (!ctors[name+'proxy']) {
				var one = this.one('ctors', name);
				var namespace = this;

				var proxy = function(els, i, func) {
					var j = els.length;
					while (j--) {
						var el = els[j];

						var tmp_i = el.i, tmp_f = el.f;
						el.i = i; el.f = one;

						try      { func.call(namespace.$(el)); }
						catch(e) { $.entwine.warn_exception(name, el, e); }
						finally  { el.i = tmp_i; el.f = tmp_f; }
					}
				}

				ctors[name+'proxy'] = proxy;
			}
		}
	});

	$.entwine.Namespace.addHandler({
		order: 30,

		bind: function(selector, k, v) {
			if ($.isFunction(v) && (k == 'onmatch' || k == 'onunmatch')) {
				this.bind_condesc(selector, k, v);
				return true;
			}
		}
	});

	/**
	 * Finds all the elements that now match a different rule (or have been removed) and call onmatch on onunmatch as appropriate
	 *
	 * Because this has to scan the DOM, and is therefore fairly slow, this is normally triggered off a short timeout, so that
	 * a series of DOM manipulations will only trigger this once.
	 *
	 * The downside of this is that things like:
	 *   $('#foo').addClass('tabs'); $('#foo').tabFunctionBar();
	 * won't work.
	 */
	$(document).bind('DOMMaybeChanged', function(){
		// For every namespace
		for (var k in $.entwine.namespaces) {
			// That has constructors or destructors
			var ctors = $.entwine.namespaces[k].store.ctors;
			if (ctors) {

				// Keep a record of elements that have matched already
				var matched = $([]), add, rem, res, rule, ctor, dtor;
				// Stepping through each selector from most to least specific
				var j = ctors.length;
				while (j--) {
					// Build some quick-access variables
					rule = ctors[j];
					sel = rule.selector.selector;
					ctor = rule.onmatch;
					dtor = rule.onunmatch;

					// Get the list of elements that match this selector, that haven't yet matched a more specific selector
					res = add = $(sel).not(matched);

					// If this selector has a list of elements it matched against last time
					if (rule.cache) {
						// Find the ones that are extra this time
						add = res.not(rule.cache);
						if (dtor) {
							// Find the ones that are gone this time
							rem = rule.cache.not(res);
							// And call the destructor on them
							if (rem.length) ctors.onunmatchproxy(rem, j, dtor);
						}
					}

					// Call the constructor on the newly matched ones
					if (add.length && ctor) ctors.onmatchproxy(add, j, ctor);

					// Add these matched ones to the list tracking all elements matched so far
					matched = matched.add(res);
					// And remember this list of matching elements again this selector, so next matching we can find the unmatched ones
					ctors[j].cache = res;
				}
			}
		}
	})

})(jQuery);
;

/* src/jquery.entwine.properties.js */

(function($) {

	var entwine_prepend = '__entwine!';

	var getEntwineData = function(el, namespace, property) {
		return el.data(entwine_prepend + namespace + '!' + property);
	}

	var setEntwineData = function(el, namespace, property, value) {
		return el.data(entwine_prepend + namespace + '!' + property, value);
	}

	var getEntwineDataAsHash = function(el, namespace) {
		var hash = {};
		var id = jQuery.data(el[0]);

		var matchstr = entwine_prepend + namespace + '!';
		var matchlen = matchstr.length;

		var cache = jQuery.cache[id];
		for (var k in cache) {
			if (k.substr(0,matchlen) == matchstr) hash[k.substr(matchlen)] = cache[k];
		}

		return hash;
	}

	var setEntwineDataFromHash = function(el, namespace, hash) {
		for (var k in hash) setEntwineData(namespace, k, hash[k]);
	}

	var entwineData = function(el, namespace, args) {
		switch (args.length) {
			case 0:
				return getEntwineDataAsHash(el, namespace);
			case 1:
				if (typeof args[0] == 'string') return getEntwineData(el, namespace, args[0]);
				else                            return setEntwineDataFromHash(el, namespace, args[0]);
			default:
				return setEntwineData(el, namespace, args[0], args[1]);
		}
	}

	$.extend($.fn, {
		entwineData: function() {
			return entwineData(this, '__base', arguments);
		}
	});

	$.entwine.Namespace.addHandler({
		order: 60,

		bind: function(selector, k, v) {
			if (k.charAt(0) != k.charAt(0).toUpperCase()) $.entwine.warn('Entwine property '+k+' does not start with a capital letter', $.entwine.WARN_LEVEL_BESTPRACTISE);

			// Create the getters and setters

			var getterName = 'get'+k;
			var setterName = 'set'+k;

			this.bind_proxy(selector, getterName, function() { return this.entwineData(k) || v ; });
			this.bind_proxy(selector, setterName, function(v){ return this.entwineData(k, v); });

			// Get the get and set proxies we just created

			var getter = this.injectee[getterName];
			var setter = this.injectee[setterName];

			// And bind in the jQuery-style accessor

			this.bind_proxy(selector, k, function(v){ return (arguments.length == 1 ? setter : getter).call(this, v) ; });

			return true;
		},

		namespaceMethodOverrides: function(namespace){
			return {
				entwineData: function() {
					return entwineData(this, namespace.name, arguments);
				}
			};
		}
	});

})(jQuery);
;

/* src/jquery.entwine.legacy.js */

(function($) {

	// Adds back concrete methods for backwards compatibility
	$.concrete = $.entwine;
	$.fn.concrete = $.fn.entwine;
	$.fn.concreteData = $.fn.entwineData;

	// Use addHandler to hack in the namespace.$.concrete equivilent to the namespace.$.entwine namespace-injection
	$.entwine.Namespace.addHandler({
		order: 100,
		bind: function(selector, k, v) { return false; },

		namespaceMethodOverrides: function(namespace){
			namespace.$.concrete = namespace.$.entwine;
			namespace.injectee.concrete = namespace.injectee.entwine;
			namespace.injectee.concreteData = namespace.injectee.entwineData;
			return {};
		}
	});

})(jQuery);
;


text:
package de.peeeq.wurstscript.translation.imtranslation;

import de.peeeq.wurstscript.WurstOperator;
import de.peeeq.wurstscript.ast.AstElement;
import de.peeeq.wurstscript.jassIm.ImClass;
import de.peeeq.wurstscript.jassIm.ImFunction;
import de.peeeq.wurstscript.jassIm.ImProg;
import de.peeeq.wurstscript.jassIm.ImStmts;
import de.peeeq.wurstscript.jassIm.ImVar;
import de.peeeq.wurstscript.jassIm.ImVars;
import de.peeeq.wurstscript.jassIm.JassIm;
import de.peeeq.wurstscript.types.TypesHelper;

/**
 * Manages object ids in a queue. This way the time each object is
 * inactive is maximized and thus errors should be easier to detect
 *
 */
public class RecycleCodeGeneratorQueue implements RecycleCodeGenerator {

	@Override
	public void createAllocFunc(ImTranslator translator, ImProg prog, ImClass c) {
		ImFunction f = translator.allocFunc.getFor(c);
		prog.getFunctions().add(f);
		ImVars locals = f.getLocals();
		ImStmts body = f.getBody();
		AstElement tr = c.getTrace();

		ImVar thisVar = JassIm.ImVar(tr, TypesHelper.imInt(), "this", false);
		locals.add(thisVar);

		ClassManagementVars mVars = translator.getClassManagementVarsFor(c);
		// if freeCount == 0 then
		ImStmts elseBlock = JassIm.ImStmts();
		ImStmts thenBlock = JassIm.ImStmts();
		body.add(JassIm.ImIf(tr,
				JassIm.ImOperatorCall(WurstOperator.EQ, JassIm.ImExprs(JassIm.ImVarAccess(mVars.freeCount), JassIm.ImIntVal(0))),
				thenBlock, elseBlock));
		// maxIndex = maxIndex + 1
		thenBlock.add(JassIm.ImSet(tr, mVars.maxIndex,
				JassIm.ImOperatorCall(WurstOperator.PLUS, JassIm.ImExprs(JassIm.ImVarAccess(mVars.maxIndex), JassIm.ImIntVal(1)))));
		// this = maxIndex
		thenBlock.add(JassIm.ImSet(tr, thisVar, JassIm.ImVarAccess(mVars.maxIndex)));
		// else:
		// freeCount = freeCount - 1
		elseBlock.add(JassIm.ImSet(tr, mVars.freeCount, JassIm.ImOperatorCall(WurstOperator.MINUS, JassIm.ImExprs(JassIm.ImVarAccess(mVars.freeCount), JassIm.ImIntVal(1)))));
		// this = free[freeCount]
		elseBlock.add(JassIm.ImSet(tr, thisVar, JassIm.ImVarArrayAccess(mVars.free, JassIm.ImVarAccess(mVars.freeCount))));
		// endif
		// typeId[this] = ...
		body.add(JassIm.ImSetArray(tr, mVars.typeId, JassIm.ImVarAccess(thisVar), JassIm.ImIntVal(c.attrTypeId())));

		// return this
		body.add(JassIm.ImReturn(tr, JassIm.ImVarAccess(thisVar)));
	}

	@Override
	public void createDeallocFunc(ImTranslator translator, ImProg prog, ImClass c) {
		AstElement tr = c.getTrace();
		ImFunction f = translator.deallocFunc.getFor(c);
		prog.getFunctions().add(f);
		ImStmts body = f.getBody();
		ImVar thisVar = f.getParameters().get(0);

		ClassManagementVars mVars = translator.getClassManagementVarsFor(c);

		// if typeId[this] == 0 then error
		body.add(JassIm.ImIf(tr,
				JassIm.ImOperatorCall(WurstOperator.EQ,
						JassIm.ImExprs(JassIm.ImVarArrayAccess(mVars.typeId, JassIm.ImVarAccess(thisVar)), JassIm.ImIntVal(0))),
				// then
				// error
				JassIm.ImStmts(translator.imError(JassIm.ImStringVal("Double free: object of type " + c.getName()))),
				// else
				JassIm.ImStmts(
						// free[freeCount] = this
						JassIm.ImSetArray(tr, mVars.free, JassIm.ImVarAccess(mVars.freeCount), JassIm.ImVarAccess(thisVar)),
						// freeCount++
						JassIm.ImSet(tr, mVars.freeCount, JassIm.ImOperatorCall(WurstOperator.PLUS, JassIm.ImExprs(JassIm.ImVarAccess(mVars.freeCount), JassIm.ImIntVal(1)))),
						// typeId[this] = 0
						JassIm.ImSetArray(tr, mVars.typeId, JassIm.ImVarAccess(thisVar), JassIm.ImIntVal(0))
						)));

	}
}

redpajama_set_name: RedPajamaGithub


text:
/* ###
 * IP: GHIDRA
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package ghidra.program.model.data;

import javax.swing.ImageIcon;

import ghidra.docking.settings.Settings;
import ghidra.program.model.mem.MemBuffer;
import ghidra.program.model.mem.MemoryAccessException;
import ghidra.util.Msg;

public class PngDataType extends BuiltIn implements Dynamic, Resource {
	public static byte[] MAGIC = new byte[] { (byte) 0x89, (byte) 0x50, (byte) 0x4e, (byte) 0x47,
		(byte) 0x0d, (byte) 0x0a, (byte) 0x1a, (byte) 0x0a };

	public static byte[] MASK = new byte[] { (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff,
		(byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff };

	public PngDataType() {
		this(null);
	}

	public PngDataType(DataTypeManager dtm) {
		super(null, "PNG-Image", dtm);
	}

	@Override
	public int getLength() {
		return -1;
	}

	@Override
	public int getLength(MemBuffer buf, int maxLength) {
		try {
			PngResource png = new PngResource(buf);
			return png.getLength();
		}
		catch (MemoryAccessException e) {
			Msg.error(this, "PNG error: " + e.getMessage());
		}
		catch (InvalidDataTypeException e) {
			Msg.error(this, "Invalid PNG data at " + buf.getAddress());
		}
		return -1;
	}

	@Override
	public boolean canSpecifyLength() {
		return false;
	}

	@Override
	public DataType clone(DataTypeManager dtm) {
		if (dtm == getDataTypeManager()) {
			return this;
		}
		return new PngDataType(dtm);
	}

	@Override
	public String getDescription() {
		return "PNG Image stored within program";
	}

	@Override
	public String getMnemonic(Settings settings) {
		return "PNG";
	}

	@Override
	public String getRepresentation(MemBuffer buf, Settings settings, int length) {
		return "<PNG-Image>";
	}

	private static class PngDataImage extends DataImage {

		private final byte[] data;

		PngDataImage(byte[] data) {
			this.data = data;
		}

		@Override
		public ImageIcon getImageIcon() {
			return new ImageIcon(data, "<PNG-Image>");
		}

		@Override
		public String getImageFileType() {
			return "png";
		}
	}

	@Override
	public Object getValue(MemBuffer buf, Settings settings, int length) {
		byte[] data = new byte[length];
		if (buf.getBytes(data, 0) != length) {
			return null;
		}
		return new PngDataImage(data);
	}

	@Override
	public Class<?> getValueClass(Settings settings) {
		return PngDataImage.class;
	}

	@Override
	public String getDefaultLabelPrefix() {
		return "PNG";
	}

	@Override
	public DataType getReplacementBaseType() {
		return ByteDataType.dataType;
	}
}


text:
<project>
    <modelVersion>4.0.0</modelVersion>
    <groupId>ru.evgenyhodz.servlets</groupId>
    <artifactId>chapter_009</artifactId>
    <version>1.0</version>
    <packaging>pom</packaging>
    <name>chapter_009</name>

    <parent>
        <groupId>evgenyhodz</groupId>
        <artifactId>git_test</artifactId>
        <version>1.0</version>
        <relativePath>../pom.xml</relativePath>
    </parent>

    <modules>
        <module>echoservlet</module>
        <module>usercrudservlet</module>
        <module>usercrudservlet2</module>
        <module>phrasegenerator</module>
        <module>usercrudservlet3</module>
        <module>usercrudservlet4</module>
        <module>usercrudservlet5</module>
        <module>usercrudservlet6</module>
        <module>usercrudservlet7</module>
        <module>usercrudservlet8</module>
    </modules>

    <dependencies>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>9.3-1102-jdbc4</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.25</version>
        </dependency>
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>2.9.9</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/jstl/jstl -->
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.webjars/bootstrap -->
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap</artifactId>
            <version>3.3.7</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/taglibs/standard -->
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>
    </dependencies>

</project>


text:
package androidx.test.internal.events.client;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;

import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.services.events.discovery.TestDiscoveryErrorEvent;
import androidx.test.services.events.discovery.TestDiscoveryEvent;
import androidx.test.services.events.discovery.TestDiscoveryFinishedEvent;
import androidx.test.services.events.discovery.TestDiscoveryStartedEvent;
import androidx.test.services.events.discovery.TestFoundEvent;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.Description;
import org.junit.runner.Result;
import org.junit.runner.RunWith;
import org.junit.runner.notification.Failure;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

/** Unit tests fpr {@link TestDiscoveryListener}. */
@RunWith(AndroidJUnit4.class)
public class TestDiscoveryListenerTest {
  @Mock TestEventClientConnectListener mockConnectListener;
  @Mock TestDiscoveryEventService discoveryEventService;

  @Before
  public void before() {
    MockitoAnnotations.initMocks(this);
  }

  @Test
  public void testFound() throws TestEventClientException {
    TestDiscoveryListener testDiscoveryListener = new TestDiscoveryListener(discoveryEventService);
    Description testDescription = Description.createTestDescription(getClass(), "sampleTest");

    testDiscoveryListener.testRunStarted(Description.EMPTY);
    testDiscoveryListener.testFinished(testDescription);
    testDiscoveryListener.testRunFinished(new Result());

    ArgumentCaptor<TestDiscoveryEvent> argument = ArgumentCaptor.forClass(TestDiscoveryEvent.class);
    verify(discoveryEventService, times(3)).send(argument.capture());

    assertThat(argument.getAllValues().get(0), instanceOf(TestDiscoveryStartedEvent.class));
    TestFoundEvent infoEvent = (TestFoundEvent) argument.getAllValues().get(1);
    assertThat(argument.getAllValues().get(2), instanceOf(TestDiscoveryFinishedEvent.class));

    assertThat(
        infoEvent.testCase.getClassAndMethodName(),
        is(getClass().getCanonicalName() + "#sampleTest"));
  }

  @Test
  public void testFailure_initError() throws TestEventClientException {
    ArgumentCaptor<TestDiscoveryEvent> argument = ArgumentCaptor.forClass(TestDiscoveryEvent.class);
    TestDiscoveryListener testDiscoveryListener = new TestDiscoveryListener(discoveryEventService);
    Description testDescription = Description.createTestDescription("a.b", "initializationError");

    testDiscoveryListener.testRunStarted(Description.EMPTY);
    testDiscoveryListener.testFailure(new Failure(testDescription, new RuntimeException()));
    testDiscoveryListener.testFinished(testDescription);
    testDiscoveryListener.testRunFinished(new Result());

    verify(discoveryEventService, times(3)).send(argument.capture());
    assertThat(argument.getAllValues().get(0), instanceOf(TestDiscoveryStartedEvent.class));
    assertThat(argument.getAllValues().get(1), instanceOf(TestDiscoveryErrorEvent.class));
    assertThat(argument.getAllValues().get(2), instanceOf(TestDiscoveryFinishedEvent.class));
    verifyNoMoreInteractions(discoveryEventService);
  }

  @Test
  public void reportProcessCrashed() throws TestEventClientException {
    ArgumentCaptor<TestDiscoveryEvent> argument = ArgumentCaptor.forClass(TestDiscoveryEvent.class);
    TestDiscoveryListener testDiscoveryListener = new TestDiscoveryListener(discoveryEventService);

    boolean result = testDiscoveryListener.reportProcessCrash(new RuntimeException());

    assertTrue(result);
    verify(discoveryEventService, times(3)).send(argument.capture());
    assertThat(argument.getAllValues().get(0), instanceOf(TestDiscoveryStartedEvent.class));
    assertThat(argument.getAllValues().get(1), instanceOf(TestDiscoveryErrorEvent.class));
    assertThat(argument.getAllValues().get(2), instanceOf(TestDiscoveryFinishedEvent.class));
    verifyNoMoreInteractions(discoveryEventService);
  }
}


text:
@php $delay = 0; $increment = 150; @endphp
<script>
    var notyf = new Notyf({ delay: 5000 });
    @if(Session::has('error'))
        notyf.alert("{{ Session::get('error') }}");
        @php $delay += $increment; @endphp
    @elseif(Session::has('success'))
        notyf.confirm("{{ Session::get('success') }}");
        @php $delay += $increment; @endphp
    @endif
    @foreach($errors->all() as $error)
        setTimeout(function() {
            notyf.alert("{{ $error }}");
        }, {{ $delay }});
        @php $delay += $increment; @endphp
    @endforeach
</script>


text:
package com.google.api.ads.dfp.jaxws.v201508;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
 *             Creates new {@link CustomField} objects.
 *
 *             The following fields are required:
 *

 *
{@link CustomField#name}

 *
{@link CustomField#entityType}

 *
{@link CustomField#dataType}

 *
{@link CustomField#visibility}

 *

 *
 *             @param customFields the custom fields to create
 *             @return the created custom fields with their IDs filled in
 *
 *
 *
Java class for createCustomFields element declaration.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <element name="createCustomFields">
 *   <complexType>
 *     <complexContent>
 *       <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *         <sequence>
 *           <element name="customFields" type="{https://www.google.com/apis/ads/publisher/v201508}CustomField" maxOccurs="unbounded" minOccurs="0"/>
 *         </sequence>
 *       </restriction>
 *     </complexContent>
 *   </complexType>
 * </element>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "customFields"
})
@XmlRootElement(name = "createCustomFields")
public class CustomFieldServiceInterfacecreateCustomFields {

    protected List<CustomField> customFields;

    /**
     * Gets the value of the customFields property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the customFields property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getCustomFields().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link CustomField }
     *
     *
     */
    public List<CustomField> getCustomFields() {
        if (customFields == null) {
            customFields = new ArrayList<CustomField>();
        }
        return this.customFields;
    }

}


text:
#include "PPSprite.h"

PPSprite * PPSprite::createSprite( const char *pszFileName,const char *soundName/*=NULL*/ )
{
    PPSprite *pPPSprite = new PPSprite();
    if(pPPSprite&&pPPSprite->initWithSpriteFrameName(pszFileName))
    {
        pPPSprite->autorelease();
        pPPSprite->m_pSoundName = soundName;
    }
    return pPPSprite;
}

PPSprite * PPSprite::createFromFile( const char *pszFileName,const char *soundName/*=NULL*/ )
{
    PPSprite *pPPSprite = new PPSprite();
    if(pPPSprite&&pPPSprite->initWithFile(pszFileName))
    {
        pPPSprite->autorelease();
        pPPSprite->m_pSoundName = soundName;
    }
    return pPPSprite;
}

void PPSprite::onEnter()
{
    CCSprite::onEnter();
    CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this,m_iTouchPriority,true);
}

void PPSprite::onExit()
{
    CCSprite::onExit();
    CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(this);
}

bool PPSprite::ccTouchBegan( CCTouch *pTouch, CCEvent *pEvent )
{
    if(_isContainPoint(pTouch))
    {
        _playEffect();
        if(m_pBeganTarget)
            (m_pBeganTarget->*beganSelector)(this);
        return true;
    }
    return false;
}

void PPSprite::ccTouchMoved( CCTouch *pTouch, CCEvent *pEvent )
{
    if(m_pMovedTarget)
        (m_pMovedTarget->*movedSelector)(this);
}

void PPSprite::ccTouchEnded( CCTouch *pTouch, CCEvent *pEvent )
{
    if(m_pEndedTarget)
        (m_pEndedTarget->*endedSelector)(this);
}

void PPSprite::setBeganTarget( CCObject* target,SEL_MenuHandler beganHandler )
{
    this->m_pBeganTarget = target;
    this->beganSelector = beganHandler;
}

void PPSprite::setEndedTarget( CCObject* target,SEL_MenuHandler endedHandler )
{
    this->m_pEndedTarget = target;
    this->endedSelector = endedHandler;
}

void PPSprite::setMovedTarget( CCObject* target,SEL_MenuHandler movedHandler )
{
    this->m_pMovedTarget = target;
    this->movedSelector = movedHandler;
}

void PPSprite::setTouchEnabled( bool enabled )
{
    if (m_bTouchEnable!= enabled)
    {
        m_bTouchEnable = enabled;
        if (m_bRunning)
        {
            if (enabled)
            {
                CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this,m_iTouchPriority,false);
            }
            else
            {
                CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(this);
            }
        }
    }
}

void PPSprite::setTouchPriority( int priority )
{
    //在设置的权重的时候 先移除掉事件代码 然后重新添加 来设置权重
    if(m_iTouchPriority!=priority)
    {
        m_iTouchPriority = priority;
        if(m_bTouchEnable)
        {
            setTouchEnabled(false);
            setTouchEnabled(true);
        }

    }
}

bool PPSprite::_isContainPoint( CCTouch *pTouch )
{
    CCPoint arPoint = getAnchorPointInPoints();
    CCPoint point = convertTouchToNodeSpaceAR(pTouch);
    CCSize spriteSize = getContentSize();
    CCRect spriteRect = CCRectMake(-arPoint.x,-arPoint.y,spriteSize.width,spriteSize.height);
    return spriteRect.containsPoint(point);
}

void PPSprite::_playEffect()
{
    if(m_pSoundName)
        SimpleAudioEngine::sharedEngine()->playEffect(this->m_pSoundName);
}


text:
module StateShifter

  class State

    attr_reader :name, :events, :initial
    attr_accessor :entry_callback, :entry_callback_args

    def initialize name, initial=false
      @name = name
      @events = {}
      @initial = initial
      @entry_callback = nil
      @entry_callback_args = nil
    end

    def has_entry_callback?
      !@entry_callback.nil?
    end

    def initial?
      @initial
    end

    def final?
      @events.empty?
    end

    def draw graph, options
      node = graph.add_nodes(@name.to_s,
                            :label => @name.to_s,
                            :width => '1',
                            :height => '1',
                            :shape => final? ? 'doublecircle' : 'ellipse'
                           )

      graph.add_edges(graph.add_nodes('starting_state', :shape => 'point'), node) if initial?

      node
    end

  end

end


text:
'use strict';

const Command = require('../../Command.js');
const EarthCycleEmbed = require('../../embeds/EarthCycleEmbed.js');

/**
 * Displays the current stage in Earth's cycle
 */
class EarthCycle extends Command {
  /**
   * Constructs a callable command
   * @param {Genesis} bot  The bot object
   */
  constructor(bot) {
    super(bot, 'warframe.misc.cycle', 'cycle', 'Current and remaining time in cycle of Earth rotation.');
  }

  /**
   * Run the command
   * @param {Message} message Message with a command to handle, reply to,
   *                          or perform an action based on parameters.
   * @returns {string} success status
   */
  async run(message) {
    this.bot.caches.pc.getDataJson()
      .then(ws => this.messageManager
        .embed(message, new EarthCycleEmbed(this.bot, ws.earthCycle), true, true))
      .catch(this.logger.error);
    return this.messageManager.statuses.SUCCESS;
  }
}

module.exports = EarthCycle;


text:
"use strict";

var assert = require("chai").assert;
var transform = require("../");

describe("inline-import", function () {

  describe("with signle quote", function () {
    it("converts inline imports", function () {
      var source = "var foo = {bar: import('baz')};\n";
      var expect = "var foo = {bar: __inlineImport_0};\nimport __inlineImport_0 from 'baz';\n";
      assert.equal(transform(source), expect);
    });
  });

  describe("with double quote", function () {
    it("converts inline imports", function () {
      var source = 'var foo = {bar: import("baz")};\n';
      var expect = "var foo = {bar: __inlineImport_0};\nimport __inlineImport_0 from 'baz';\n";
      assert.equal(transform(source), expect);
    });
  });

  it("ignores comments", function () {
    var source = "/* import('foo')}; */ import('bar')\n";
    var expected = "/* import('foo')}; */ __inlineImport_0\nimport __inlineImport_0 from 'bar';\n";
    assert.equal(transform(source), expected);
  });

  it("ignores line comments", function () {
    var source = "// import('foo')};\nimport('bar')\n";
    var expected = "// import('foo')};\n__inlineImport_0\nimport __inlineImport_0 from 'bar';\n";
    assert.equal(transform(source), expected);
  });

  it("ignores single quote string", function () {
    var source = "'import(\"foo\")};' import('bar')\n";
    var expected = "'import(\"foo\")};' __inlineImport_0\nimport __inlineImport_0 from 'bar';\n";
    assert.equal(transform(source), expected);
  });

  it("ignores double quote string", function () {
    var source = '"import(\'foo\')};" import("bar")\n';
    var expected = '"import(\'foo\')};" __inlineImport_0\nimport __inlineImport_0 from \'bar\';\n';
    assert.equal(transform(source), expected);
  });

  // TODO
  // it("ignores template string", function () {
  //   var source = "`import(\"foo\")} ${import('bar')}`\n"
  //     "import('baz')\n";
  //   var expected = "`import(\"foo\")} ${__inlineImport_0}`\n"
  //     "__inlineImport_1\n"
  //     "import __inlineImport_0 from 'bar';\n"
  //     "import __inlineImport_1 from 'baz';\n";
  //   assert.equal(transform(source), expected);
  // });
})


text:
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <errno.h>
#include "../common/utils.h"
#include "ctx.h"
#include "rules.h"
#include "reloader.h"

// we are not going to unit-test these functions, then printing errors
// directly is not a big issue

static pthread_mutex_t mutex_running = PTHREAD_MUTEX_INITIALIZER;
static bool running = false;
static int reloader_status_code = 0;
static void (*handler_func)(int) = NULL;

static void
sig_handler(int signum)
{
    bm_reloader_stop(signum + 128);
}

int
bm_reloader_run(bm_ctx_t **ctx, bm_rule_exec_func_t rule_exec,
    bc_slist_t *outputs, bc_trie_t *args)
{
    // install ^C handler
    struct sigaction current_action;
    if (sigaction(SIGINT, NULL, &current_action) < 0) {
        fprintf(stderr, "blogc-make: failed to run reloader: %s\n", strerror(errno));
        return 1;
    }
    if (current_action.sa_handler != sig_handler) {  // not installed yet
        // backup current handler
        pthread_mutex_lock(&mutex_running);
        handler_func = current_action.sa_handler;
        pthread_mutex_unlock(&mutex_running);

        // set new handler
        struct sigaction new_action;
        new_action.sa_handler = sig_handler;
        sigemptyset(&new_action.sa_mask);
        new_action.sa_flags = 0;
        if (sigaction(SIGINT, &new_action, NULL) < 0) {
            fprintf(stderr, "blogc-make: failed to run reloader: %s\n",
                strerror(errno));
            return 1;
        }
    }

    pthread_mutex_lock(&mutex_running);
    running = true;
    pthread_mutex_unlock(&mutex_running);

    while (running) {
        if (!bm_ctx_reload(ctx)) {
            fprintf(stderr, "blogc-make: warning: failed to reload context. "
                "retrying in 5 seconds ...\n\n");
            sleep(5);
            continue;
        }
        if (0 != rule_exec(*ctx, outputs, args)) {
            fprintf(stderr, "blogc-make: warning: failed to rebuild website. "
                "retrying in 5 seconds ...\n\n");
            sleep(5);
            continue;
        }
        sleep(1);
    }

    return reloader_status_code;
}

void
bm_reloader_stop(int status_code)
{
    pthread_mutex_lock(&mutex_running);

    running = false;
    reloader_status_code = status_code;

    // reraise if SIGINT
    if (status_code == SIGINT + 128) {

        // reinstall old ^C handler
        struct sigaction new_action;
        new_action.sa_handler = handler_func;
        sigemptyset(&new_action.sa_mask);
        new_action.sa_flags = 0;
        sigaction(SIGINT, &new_action, NULL);

        // run it
        raise(SIGINT);

        // SIGINT will usually kill the process, but in the case that the
        // `handler_func` prevents it, our custom handler will be reinstalled
        // by `bm_reloader_run`.
    }

    pthread_mutex_unlock(&mutex_running);
}


text:
#ifndef IVW_BASETRACK_H
#define IVW_BASETRACK_H

#include <modules/animation/animationmoduledefine.h>
#include <inviwo/core/common/inviwo.h>
#include <inviwo/core/util/indirectiterator.h>

#include <modules/animation/datastructures/track.h>
#include <modules/animation/datastructures/keyframesequence.h>
#include <modules/animation/datastructures/keyframesequenceobserver.h>

namespace inviwo {

namespace animation {

template <typename Seq>
class BaseTrack : public Track, public KeyframeSequenceObserver {
public:
    using seq_type = Seq;
    using key_type = typename Seq::key_type;
    using value_type = typename Seq::value_type;
    using iterator = util::IndirectIterator<typename std::vector<std::unique_ptr<Seq>>::iterator>;
    using const_iterator =
        util::IndirectIterator<typename std::vector<std::unique_ptr<Seq>>::const_iterator>;

    static_assert(std::is_base_of<KeyframeSequence, Seq>::value,
                  "Seq has to derive from KeyframeSequence");

    BaseTrack(const std::string& identifier, const std::string& name, size_t priority = 0);
    virtual ~BaseTrack();

    virtual bool isEnabled() const override;
    virtual void setEnabled(bool enabled) override;

    virtual const std::string& getIdentifier() const override;
    virtual void setIdentifier(const std::string& identifier) override;

    virtual const std::string& getName() const override;
    virtual void setName(const std::string& name) override;

    virtual size_t getPriority() const override;
    virtual void setPriority(size_t priority) override;

    virtual Seconds getFirstTime() const override;
    virtual Seconds getLastTime() const override;
    virtual std::vector<Seconds> getAllTimes() const override;

    virtual size_t size() const override;
    virtual bool empty() const override;

    virtual Seq& operator[](size_t i) override;
    virtual const Seq& operator[](size_t i) const override;

    virtual const Seq& getFirst() const override;
    virtual Seq& getFirst() override;
    virtual const Seq& getLast() const override;
    virtual Seq& getLast() override;

    iterator begin();
    const_iterator begin() const;
    iterator end();
    const_iterator end() const;

    virtual void add(Seconds time, bool asNewSequence) override;
    virtual void add(std::unique_ptr<KeyframeSequence> sequence) override;
    virtual void add(std::unique_ptr<Seq> sequence);

    virtual std::unique_ptr<KeyframeSequence> remove(size_t i) override;
    virtual std::unique_ptr<Keyframe> remove(Keyframe* key) override;
    virtual std::unique_ptr<KeyframeSequence> remove(KeyframeSequence* seq) override;

    virtual void serialize(Serializer& s) const override;
    virtual void deserialize(Deserializer& d) override;

protected:
    virtual void onKeyframeSequenceMoved(KeyframeSequence* seq) override;
    void addToClosestSequence(std::unique_ptr<key_type> key);

    bool enabled_{true};
    std::string identifier_;
    std::string name_;
    size_t priority_{0};

    // Sorted list of non-overlapping sequences of key frames
    std::vector<std::unique_ptr<Seq>> sequences_;
};

template <typename Seq>
BaseTrack<Seq>::BaseTrack(const std::string& identifier, const std::string& name, size_t priority)
    : identifier_{identifier}, name_{name}, priority_{priority} {}

template <typename Seq>
BaseTrack<Seq>::~BaseTrack() {
    while (size() > 0) {
        remove(size() - 1);
    }
}

template <typename Seq>
bool BaseTrack<Seq>::isEnabled() const {
    return enabled_;
}
template <typename Seq>
void BaseTrack<Seq>::setEnabled(bool enabled) {
    if (enabled_ != enabled) {
        enabled_ = enabled;
        this->notifyEnabledChanged(this);
    }
}

template <typename Seq>
const std::string& BaseTrack<Seq>::getIdentifier() const {
    return identifier_;
}
template <typename Seq>
void BaseTrack<Seq>::setIdentifier(const std::string& identifier) {
    if (identifier_ != identifier) {
        identifier_ = identifier;
        this->notifyIdentifierChanged(this);
    }
}

template <typename Seq>
const std::string& BaseTrack<Seq>::getName() const {
    return name_;
}
template <typename Seq>
void BaseTrack<Seq>::setName(const std::string& name) {
    if (name_ != name) {
        name_ = name;
        this->notifyNameChanged(this);
    }
}

template <typename Seq>
size_t BaseTrack<Seq>::getPriority() const {
    return priority_;
}
template <typename Seq>
void BaseTrack<Seq>::setPriority(size_t priority) {
    if (priority_ != priority) {
        priority_ = priority;
        this->notifyPriorityChanged(this);
    }
}

template <typename Seq>
Seconds BaseTrack<Seq>::getFirstTime() const {
    if (sequences_.empty()) {
        return Seconds{0.0};
    } else {
        return sequences_.front()->getFirstTime();
    }
}
template <typename Seq>
Seconds BaseTrack<Seq>::getLastTime() const {
    if (sequences_.empty()) {
        return Seconds{0.0};
    } else {
        return sequences_.back()->getLastTime();
    }
}
template <typename Seq>
std::vector<Seconds> BaseTrack<Seq>::getAllTimes() const {
    std::vector<Seconds> result;
    for (const auto& seq : sequences_) {
        for (size_t i = 0; i < seq->size(); i++) {
            result.push_back((*seq)[i].getTime());
        }
    }
    std::sort(result.begin(), result.end());
    return result;
}

template <typename Seq>
size_t BaseTrack<Seq>::size() const {
    return sequences_.size();
}
template <typename Seq>
bool BaseTrack<Seq>::empty() const {
    return sequences_.empty();
}

template <typename Seq>
Seq& BaseTrack<Seq>::operator[](size_t i) {
    return *sequences_[i];
}

template <typename Seq>
const Seq& BaseTrack<Seq>::operator[](size_t i) const {
    return *sequences_[i];
}

template <typename Seq>
const Seq& BaseTrack<Seq>::getFirst() const {
    return *sequences_.front();
}
template <typename Seq>
Seq& BaseTrack<Seq>::getFirst() {
    return *sequences_.front();
}
template <typename Seq>
const Seq& BaseTrack<Seq>::getLast() const {
    return *sequences_.back();
}
template <typename Seq>
Seq& BaseTrack<Seq>::getLast() {
    return *sequences_.back();
}

template <typename Seq>
auto BaseTrack<Seq>::begin() -> iterator {
    return util::makeIndirectIterator<true>(sequences_.begin());
}

template <typename Seq>
auto BaseTrack<Seq>::begin() const -> const_iterator {
    return util::makeIndirectIterator<true>(sequences_.begin());
}

template <typename Seq>
auto BaseTrack<Seq>::end() -> iterator {
    return util::makeIndirectIterator<true>(sequences_.end());
}

template <typename Seq>
auto BaseTrack<Seq>::end() const -> const_iterator {
    return util::makeIndirectIterator<true>(sequences_.end());
}

/**
 * Track of sequences
 * ----------X======X====X-----------------X=========X-------X=====X--------
 * |- case 1-|-case 2----------------------|-case 2----------|-case 2------|
 *           |-case 2a---|---------case 2b-|
 */
template <typename Seq>
void BaseTrack<Seq>::add(Seconds time, bool asNewSequence) {
    auto addNew = [this](std::unique_ptr<key_type> key) {
        std::vector<std::unique_ptr<key_type>> keys;
        keys.push_back(std::move(key));
        add(std::make_unique<Seq>(std::move(keys)));
    };

    auto key = std::make_unique<key_type>(time);
    if (sequences_.empty()) {
        addNew(std::move(key));
        return;
    }

    // 'it' will be the first seq. with a first time larger then 'to'.
    auto it = std::upper_bound(this->begin(), this->end(), time);
    if (it == this->begin()) {  // case 1
        if (asNewSequence) {
            addNew(std::move(key));
        } else {
            it->add(std::move(key));
        }
    } else {  // case 2
        auto& seq1 = *std::prev(it);
        if (time < seq1.getLastTime()) {  // case 2a
            seq1.add(std::move(key));
        } else {  // case 2b
            if (asNewSequence) {
                addNew(std::move(key));
            } else {
                addToClosestSequence(std::move(key));
            }
        }
    }
}

/**
 * Track of sequences
 * ----------X======X====X-----------------X=========X-------X=====X--------
 * |- case 1-|-case 2----------------------|-case 2----------|-case 3------|
 *           |-case 2a-----------|-case 2b-|
 */
template <typename Seq>
void BaseTrack<Seq>::addToClosestSequence(std::unique_ptr<key_type> key) {
    // 'it' will be the first seq. with a first time larger then 'to'.
    auto it = std::upper_bound(this->begin(), this->end(), key->getTime());

    if (it == this->begin()) {  // case 1
        it->add(std::move(key));
    } else if (it == this->end()) {  // case 3
        auto& seq1 = *std::prev(it);
        seq1.add(std::move(key));
    } else {  // case 2
        auto& seq1 = *std::prev(it);
        auto& seq2 = *it;
        if ((key->getTime() - seq1.getLastTime()) < (seq2.getFirstTime() - key->getTime())) {
            seq1.add(std::move(key));  // case 2a
        } else {
            seq2.add(std::move(key));  // case 2b
        }
    }
}

template <typename Seq>
void BaseTrack<Seq>::add(std::unique_ptr<KeyframeSequence> sequence) {
    if (auto s = util::dynamic_unique_ptr_cast<Seq>(std::move(sequence))) {
        add(std::move(s));
    } else {
        throw Exception("Invalid sequence type", IvwContext);
    }
}

template <typename Seq>
void BaseTrack<Seq>::add(std::unique_ptr<Seq> sequence) {
    auto it = std::upper_bound(sequences_.begin(), sequences_.end(), sequence,
                               [](const auto& a, const auto& b) { return *a < *b; });

    if (it != sequences_.begin()) {
        if ((*std::prev(it))->getLastTime() > sequence->getFirstTime()) {
            throw Exception("Overlapping Sequence", IvwContext);
        }
    }
    if (it != sequences_.end() && (*it)->getFirstTime() < sequence->getFirstTime()) {
        throw Exception("Overlapping Sequence", IvwContext);
    }

    auto inserted = sequences_.insert(it, std::move(sequence));
    this->notifyKeyframeSequenceAdded(this, inserted->get());
    (*inserted)->KeyframeSequenceObserverble::addObserver(this);
}

template <typename Seq>
std::unique_ptr<KeyframeSequence> BaseTrack<Seq>::remove(size_t i) {
    if (i < sequences_.size()) {
        auto seq = std::move(sequences_[i]);
        sequences_.erase(sequences_.begin() + i);
        notifyKeyframeSequenceRemoved(this, seq.get());
        return std::move(seq);
    } else {
        return nullptr;
    }
}

template <typename Seq>
std::unique_ptr<Keyframe> BaseTrack<Seq>::remove(Keyframe* key) {
    for (auto& seq : sequences_) {
        if (auto res = seq->remove(key)) {
            if (seq->size() == 0) {
                remove(seq.get());
            }
            return std::move(res);
        }
    }
    return nullptr;
}
template <typename Seq>
std::unique_ptr<KeyframeSequence> BaseTrack<Seq>::remove(KeyframeSequence* seq) {
    auto it = std::find_if(sequences_.begin(), sequences_.end(),
                           [&](auto& elem) { return elem.get() == seq; });
    if (it != sequences_.end()) {
        auto res = std::move(*it);
        sequences_.erase(it);
        notifyKeyframeSequenceRemoved(this, res.get());
        return std::move(res);
    } else {
        return nullptr;
    }
}

template <typename Seq>
void BaseTrack<Seq>::onKeyframeSequenceMoved(KeyframeSequence* seq) {
    const bool atFront = sequences_.front().get() == seq;
    const bool atBack = sequences_.back().get() == seq;

    std::stable_sort(sequences_.begin(), sequences_.end(),
                     [](const auto& a, const auto& b) { return *a < *b; });

    // handle overlap?

    if (atFront || sequences_.front().get() == seq) {
        this->notifyFirstMoved(this);
    }

    if (atBack || sequences_.back().get() == seq) {
        this->notifyLastMoved(this);
    }
}

template <typename Seq>
void BaseTrack<Seq>::serialize(Serializer& s) const {
    s.serialize("type", getClassIdentifier(), SerializationTarget::Attribute);
    s.serialize("identifier", identifier_, SerializationTarget::Attribute);
    s.serialize("name", name_);
    s.serialize("enabled", enabled_);
    s.serialize("priority", priority_);
    s.serialize("sequences", sequences_, "sequence");
}
template <typename Seq>
void BaseTrack<Seq>::deserialize(Deserializer& d) {
    {
        auto old = identifier_;
        d.deserialize("identifier", identifier_, SerializationTarget::Attribute);
        if (old != identifier_) this->notifyIdentifierChanged(this);
    }
    {
        auto old = name_;
        d.deserialize("name", name_);
        if (old != name_) this->notifyNameChanged(this);
    }
    {
        auto old = enabled_;
        d.deserialize("enabled", enabled_);
        if (old != enabled_) this->notifyEnabledChanged(this);
    }
    {
        auto old = priority_;
        d.deserialize("priority", priority_);
        if (old != priority_) this->notifyPriorityChanged(this);
    }

    using Elem = std::unique_ptr<Seq>;
    util::IndexedDeserializer<Elem>("sequences", "sequence")
        .onNew([&](Elem& seq) {
            this->notifyKeyframeSequenceAdded(this, seq.get());
            seq->KeyframeSequenceObserverble::addObserver(this);
        })
        .onRemove([&](Elem& seq) { this->notifyKeyframeSequenceRemoved(this, seq.get()); })(
            d, sequences_);
}

}  // namespace animation

}  // namespace inviwo

#endif  // IVW_BASETRACK_H


text:
'use strict';
const path = require('path');
const execa = require('execa');

const create = (columns, rows) => ({
	columns: parseInt(columns, 10),
	rows: parseInt(rows, 10)
});

module.exports = () => {
	const env = process.env;
	const stdout = process.stdout;
	const stderr = process.stderr;

	if (stdout && stdout.columns && stdout.rows) {
		return create(stdout.columns, stdout.rows);
	}

	if (stderr && stderr.columns && stderr.rows) {
		return create(stderr.columns, stderr.rows);
	}

	// these values are static, so not the first choice
	if (env.COLUMNS && env.LINES) {
		return create(env.COLUMNS, env.LINES);
	}

	if (process.platform === 'win32') {
		try {
			// Binary: https://github.com/sindresorhus/win-term-size
			const size = execa.sync(path.join(__dirname, 'vendor/win-term-size.exe')).stdout.split(/\r?\n/);

			if (size.length === 2) {
				return create(size[0], size[1]);
			}
		} catch (err) {}
	} else {
		if (process.platform === 'darwin') {
			try {
				// Binary is from https://www.xquartz.org
				const size = execa.shellSync(path.join(__dirname, 'vendor/resize'), ['-u']).stdout.match(/\d+/g);

				if (size.length === 2) {
					return create(size[0], size[1]);
				}
			} catch (err) {}
		}

		// `resize` is preferred as it works even when all file descriptors are redirected
		// https://linux.die.net/man/1/resize
		try {
			const size = execa.sync('resize', ['-u']).stdout.match(/\d+/g);

			if (size.length === 2) {
				return create(size[0], size[1]);
			}
		} catch (err) {}

		try {
			const columns = execa.sync('tput', ['cols']).stdout;
			const rows = execa.sync('tput', ['lines']).stdout;

			if (columns && rows) {
				return create(columns, rows);
			}
		} catch (err) {}
	}

	return create(80, 24);
};


text:
\documentclass[12pt]{article}
\bibliographystyle{plain}
\usepackage[dvips]{graphicx}
\usepackage{program}
\newcommand{\institute}[1]{\emph{#1}}
\title{Blob-Tracker using FVision and XVision2}
\author{Jatin D. Shah}
\date{\today}

\newtheorem{defn}{Definition}[section]
\begin{document}
\maketitle
\section{Introduction}
\par A blob-tracker tracks the motion of a region of specific color in a video sequence. The region is generally described as a rectangle or a circle. In this project, the blob tracker assumes that the region to be tracked is rectangular. The tracker samples a small window where it expects to find the blob. Then the blob is identified using suitable functions from a vision library. This process is repeated every frame by changing the location of the window to match the motion of the blob tracker.
\par In this project, I have implemented a blob-tracker in Haskell. The vision library used is a C++ library, XVision2; these library functions were accessed in Haskell using FVision, which is an interface to the XVision2 through GreenCard.
\section{Parts of Blob Tracker}
\par As described above, once the user clicks on a blob, a small rectangular region around the blob of size {\tt blobSize} centered at the position clicked is sampled. The FVision function {\tt getColorSelector} returns the color of this region. The type of this function is: $$\mbox{\tt getColorSelector :: ImageRGB -> ColorSelector}$$ and it is defined in {\tt NXVision2.gc}. The feedback loop described in the next section described in the next section tracks the motion of a blob of the color returned by {\tt getColorSelector}.
\subsection{Feedback Loop}
\par This part of the program attempts to locate the present position of the blob using its position in the previous frame and the color of the blob. It is implemented using FRP primitive {\tt loopB} in file {\tt FRPExtra.hs}. A skeleton of the program is code is shown below\footnote{This is not the actual program code}:
\begin{verbatim}
newXY =
      loopB (\newXY ->
         let
           positionX = (centerX)
                            `delayB` (fst (derefB newXY))
           positionY = (centerY)
                            `delayB` (snd (derefB newXY))
           ...
           window = getRegion video positionX positionY windowSize windowSize
           (blobX,blobY,blobW,blobH) = stepBlob2 positionX positionY
                                                 window color
           ...
           newX = positionX + blobX + blobH/2
           newY = positionY + blobY + blobW/2
         in
           pairZ newX newY
          )
\end{verbatim}
\par In the code shown above {\tt centerX} and {\tt centerY} is the location clicked by the user. {\tt loopB} implements the feedback loop where position of the loop (represented by {\tt positionX/Y} and {\tt newX/Y})is fed back to the system.
\par The function {\tt getRegion} cuts out a window from the image and the function {\tt stepBlob2} find the blob in the window cut by {\tt getRegion}. These are FVision functions (defined in file {\tt NXVision2.gc}).
\subsection{Motion Prediction}
\par Here it is assumed that the blob is moving with a constant velocity so we only try to approximate the first derivative of position to find the position of the blob. The {\tt derivativeB} function from FRP is not used as John Peterson has doubts if it will work. Instead, last two positions of the blob are tracked and the first derivative is approximated from those positions. The basic structure of the new code is shown below:
\begin{verbatim}
newXY =
        loopB (\newXYref ->
            let
                    position0X = (centerX)
                                    `delayB` (fst (derefB newXYref))
                    position1X = position0X
                                    `delayB` (snd (derefB newXYref))
                    ...

                    dispX = position0X - position1X
                    predictedPositionX = position0X + dispX
                    ...
              )
\end{verbatim}
\par In this case, {\tt position0X} and {\tt position1X} are the two previous positions of the blob ({\tt position0X} being the more recent position)
\par These positions are used to find the {\tt predictedPositionX/Y} which are passed to the tracker instead of the previous positions.
\subsection{Adaptive Window Resizing}
\par It may happen that inspite of motion prediction, the blob tracker may lose track of the blob. In such a situation, one might try to find the blob in the entire image. But this can be very slow. A better strategy would be to increase the window size by a small factor until the tracker finds the blob. The window size can later be decreased once the tracker has begun to track the blobs properly.
\par The code shown below achieves that\footnote{In the actual code, we wait if we do not find a blob for {\tt threshold} consecutive frames. This has to be done because {\tt stepBlob2} sometimes erroneously returns that it has not found the blob even when it is tracking the blob properly.}
\begin{verbatim}
newXY = loopB (\newXYref ->
            let
                ...
                (blobX,blobY,blobH,blobW) = stepBlob2 ...
                dataError = (blobX<*0 ||* blobY<*0 ||* blobH<*0 ||* blobW<*0)
                         ||* (blobH==*0 &&* blobW==*0)
                newX=ifX dataError position0X (position0X+blobX+blobW/2)
                newWinSz = if dataError
                              (changeWinSz oldWinSz percent)
                              (changeWinSz oldWinSz (-percent))
                ...
              )
\end{verbatim}
\par If the function {\tt stepBlob2} returns negative values implying that blob is not found then position of the blob is not changed. Further, if {\tt stepBlob2} is unable to find the blob then window size is increased.
\section{Implementation Issues}
There are several issues regarding implementation of this blob tracker in Haskell. The program runs extremely slowly in both hugs and GHC implementation of Haskell.
\subsection{Space Leak in FRP}
\par It seems that the implementation of the program I have discussed in this paper suffers from some kind of space leak problem which I was unable to detect. The problem is aggravated if I used more graphics primitives. It should be noted that the space leak is present even if the program is compiled using GHC.
\subsection{Choosing a Window Size}
\par Ideally, the algorithm for changing the window size should converge at a that size which minimizes the number of {\it no blob found} returns by {\tt stepBlob2}. But the algorithm described in this paper is unable to do this. My algorithm, decreases the window size to minimum possible if it is tracking properly and increases it if it fails to track. Thus, in this implementation, proper tracking of by the program requires that the window size entered by the user is appropriate. Since we are using first order motion prediction, we will be able to track all blobs moving with constant velocities with window sizes about the size of the blob. Window sizes about the size of the blob will be sufficient for accelerated blobs once we incorporate second-order motion prediction.
\par If the window size is smaller than the object, then {\tt stepBlob2} returns the approximately entire window as blob. The window sizes should be increased in this situation as well.
\end{document}


text:
div.codeblock { border: 1px solid #66cc66; padding: 3px; margin: 0ex 3em; background: #ddddff; }
div.jsblock { border: 1px solid #66cc66; padding: 3px; margin: 0ex 3em; background: #ddffff; }
pre { margin: 0px; padding: 2px; }
pre.code { color: #000066; margin-top: 1em; padding: 0px; }
pre.code.fst,pre.geo.fst  { margin-top: 0px; }
pre.result { color: #006600; background: #ddffdd; }
pre.regexp { color: #99ccaa; background: #eeffdd; }
pre.output { color: #993333; background: #dddddd; }
pre.draw2d { color: #aa9999; background: #ddeedd; }
pre.pragma { color: #996600; background: #ffffcc; }
pre.geo    { color: #660000; background: #9999ff; margin-top: 1em; }
code { background: #ddddff; }
pre.block>code { background: inherit; }
pre.block {
background: #ddddee;
margin: 0em 2em;
padding: 1em;
border-radius: 1em;
}
table { border-collapse:collapse; }
table td, table th { padding: 0.5ex 1em;  border: 1px solid black; }
table td, table th, table code { background: #ffffff; }
a.hlink { margin-left: 0.5em; opacity: 0.1; text-decoration: none; }
a.hlink:hover { text-decoration: underline; }
a.hlink::after { content: "¶"; }
a.hlink:hover { opacity: 0.8; }
a { text-decoration: none; }
a:hover { text-decoration: underline; }
kbd {
display: inline-block;
padding: 0.2em 0.3em;
margin: 0em 0.1em;
color: #555;
vertical-align: middle;
background-color: #eee;
border: solid 1px #bbb;
border-bottom-color: #aaa;
border-radius: 0.3em;
box-shadow: inset 0 -1px 0 #aaa;
}