text:
(function(context, factory) {

	//INDEXOF POLLYFILL
	[].indexOf||(Array.prototype.indexOf=function(a,b,c){for(c=this.length,b=(c+~~b)%c;b<c&&(!(b in this)||this[b]!==a);b++);return b^c?b:-1;});

	//AMD
	if(typeof define === 'function' && define.amd) { define(constructAMD); }

	//GLOBAL
	else { constructGlobal(); }

	/**
	 * Construct AMD version of the library
	 */
	function constructAMD() {

		//create a library instance
		return init();

		//spawns a library instance
		function init() {
			var library;
			library = factory('amd');
			library.fork = init;
			return library;
		}
	}

	/**
	 * Construct a Global version of the library
	 */
	function constructGlobal() {
		var library;

		//create a library instance
		library = init();
		library.noConflict('KeyboardJS', 'k');

		//spawns a library instance
		function init() {
			var library, namespaces = [], previousValues = {};

			library = factory('global');
			library.fork = init;
			library.noConflict = noConflict;
			return library;

			//sets library namespaces
			function noConflict(    ) {
				var args, nI, newNamespaces;

				newNamespaces = Array.prototype.slice.apply(arguments);

				for(nI = 0; nI < namespaces.length; nI += 1) {
					if(typeof previousValues[namespaces[nI]] === 'undefined') {
						delete context[namespaces[nI]];
					} else {
						context[namespaces[nI]] = previousValues[namespaces[nI]];
					}
				}

				previousValues = {};

				for(nI = 0; nI < newNamespaces.length; nI += 1) {
					if(typeof newNamespaces[nI] !== 'string') {
						throw new Error('Cannot replace namespaces. All new namespaces must be strings.');
					}
					previousValues[newNamespaces[nI]] = context[newNamespaces[nI]];
					context[newNamespaces[nI]] = library;
				}

				namespaces = newNamespaces;

				return namespaces;
			}
		}
	}
})(this, function(env) {
	var KeyboardJS = {}, locales = {}, locale, map, macros, activeKeys = [], bindings = [], activeBindings = [],
	activeMacros = [], aI, usLocale;

	///////////////////////
	// DEFUALT US LOCALE //
	///////////////////////

	//define US locale
	//If you create a new locale please submit it as a pull request or post
	// it in the issue tracker at
	// http://github.com/RobertWhurst/KeyboardJS/issues/
	usLocale = {
		"map": {

			//general
			"3": ["cancel"],
			"8": ["backspace"],
			"9": ["tab"],
			"12": ["clear"],
			"13": ["enter"],
			"16": ["shift"],
			"17": ["ctrl"],
			"18": ["alt", "menu"],
			"19": ["pause", "break"],
			"20": ["capslock"],
			"27": ["escape", "esc"],
			"32": ["space", "spacebar"],
			"33": ["pageup"],
			"34": ["pagedown"],
			"35": ["end"],
			"36": ["home"],
			"37": ["left"],
			"38": ["up"],
			"39": ["right"],
			"40": ["down"],
			"41": ["select"],
			"42": ["printscreen"],
			"43": ["execute"],
			"44": ["snapshot"],
			"45": ["insert", "ins"],
			"46": ["delete", "del"],
			"47": ["help"],
			"91": ["command", "windows", "win", "super", "leftcommand", "leftwindows", "leftwin", "leftsuper"],
			"92": ["command", "windows", "win", "super", "rightcommand", "rightwindows", "rightwin", "rightsuper"],
			"145": ["scrolllock", "scroll"],
			"186": ["semicolon", ";"],
			"187": ["equal", "equalsign", "="],
			"188": ["comma", ","],
			"189": ["dash", "-"],
			"190": ["period", "."],
			"191": ["slash", "forwardslash", "/"],
			"192": ["graveaccent", "`"],
			"219": ["openbracket", "["],
			"220": ["backslash", "\\"],
			"221": ["closebracket", "]"],
			"222": ["apostrophe", "'"],

			//0-9
			"48": ["zero", "0"],
			"49": ["one", "1"],
			"50": ["two", "2"],
			"51": ["three", "3"],
			"52": ["four", "4"],
			"53": ["five", "5"],
			"54": ["six", "6"],
			"55": ["seven", "7"],
			"56": ["eight", "8"],
			"57": ["nine", "9"],

			//numpad
			"96": ["numzero", "num0"],
			"97": ["numone", "num1"],
			"98": ["numtwo", "num2"],
			"99": ["numthree", "num3"],
			"100": ["numfour", "num4"],
			"101": ["numfive", "num5"],
			"102": ["numsix", "num6"],
			"103": ["numseven", "num7"],
			"104": ["numeight", "num8"],
			"105": ["numnine", "num9"],
			"106": ["nummultiply", "num*"],
			"107": ["numadd", "num+"],
			"108": ["numenter"],
			"109": ["numsubtract", "num-"],
			"110": ["numdecimal", "num."],
			"111": ["numdevide", "num/"],
			"144": ["numlock", "num"],

			//function keys
			"112": ["f1"],
			"113": ["f2"],
			"114": ["f3"],
			"115": ["f4"],
			"116": ["f5"],
			"117": ["f6"],
			"118": ["f7"],
			"119": ["f8"],
			"120": ["f9"],
			"121": ["f10"],
			"122": ["f11"],
			"123": ["f12"]
		},
		"macros": [

			//secondary key symbols
			['shift + `', ["tilde", "~"]],
			['shift + 1', ["exclamation", "exclamationpoint", "!"]],
			['shift + 2', ["at", "@"]],
			['shift + 3', ["number", "#"]],
			['shift + 4', ["dollar", "dollars", "dollarsign", "$"]],
			['shift + 5', ["percent", "%"]],
			['shift + 6', ["caret", "^"]],
			['shift + 7', ["ampersand", "and", "&"]],
			['shift + 8', ["asterisk", "*"]],
			['shift + 9', ["openparen", "("]],
			['shift + 0', ["closeparen", ")"]],
			['shift + -', ["underscore", "_"]],
			['shift + =', ["plus", "+"]],
			['shift + (', ["opencurlybrace", "opencurlybracket", "{"]],
			['shift + )', ["closecurlybrace", "closecurlybracket", "}"]],
			['shift + \\', ["verticalbar", "|"]],
			['shift + ;', ["colon", ":"]],
			['shift + \'', ["quotationmark", "\""]],
			['shift + !,', ["openanglebracket", "<"]],
			['shift + .', ["closeanglebracket", ">"]],
			['shift + /', ["questionmark", "?"]]
		]
	};
	//a-z and A-Z
	for (aI = 65; aI <= 90; aI += 1) {
		usLocale.map[aI] = String.fromCharCode(aI + 32);
		usLocale.macros.push(['shift + ' + String.fromCharCode(aI + 32) + ', capslock + ' + String.fromCharCode(aI + 32), [String.fromCharCode(aI)]]);
	}
	registerLocale('us', usLocale);
	getSetLocale('us');

	//////////
	// INIT //
	//////////

	//enable the library
	enable();

	/////////
	// API //
	/////////

	//assemble the library and return it
	KeyboardJS.enable = enable;
	KeyboardJS.disable = disable;
	KeyboardJS.activeKeys = getActiveKeys;
	KeyboardJS.on = createBinding;
	KeyboardJS.clear = removeBindingByKeyCombo;
	KeyboardJS.clear.key = removeBindingByKeyName;
	KeyboardJS.locale = getSetLocale;
	KeyboardJS.locale.register = registerLocale;
	KeyboardJS.macro = createMacro;
	KeyboardJS.macro.remove = removeMacro;
	KeyboardJS.key = {};
	KeyboardJS.key.name = getKeyName;
	KeyboardJS.key.code = getKeyCode;
	KeyboardJS.combo = {};
	KeyboardJS.combo.active = isSatisfiedCombo;
	KeyboardJS.combo.parse = parseKeyCombo;
	KeyboardJS.combo.stringify = stringifyKeyCombo;
	return KeyboardJS;

	//////////////////////
	// INSTANCE METHODS //
	//////////////////////

	/**
	 * Enables KeyboardJS
	 */
	function enable() {
		if(window.addEventListener) {
			document.addEventListener('keydown', keydown, false);
			document.addEventListener('keyup', keyup, false);
			window.addEventListener('blur', reset, false);
			window.addEventListener('webkitfullscreenchange', reset, false);
			window.addEventListener('mozfullscreenchange', reset, false);
		} else if(window.attachEvent) {
			document.attachEvent('onkeydown', keydown);
			document.attachEvent('onkeyup', keyup);
			window.attachEvent('onblur', reset);
		}
	}

	/**
	 * Exits all active bindings and disables KeyboardJS
	 */
	function disable() {
		reset();
		if(window.removeEventListener) {
			document.removeEventListener('keydown', keydown, false);
			document.removeEventListener('keyup', keyup, false);
			window.removeEventListener('blur', reset, false);
			window.removeEventListener('webkitfullscreenchange', reset, false);
			window.removeEventListener('mozfullscreenchange', reset, false);
		} else if(window.detachEvent) {
			document.detachEvent('onkeydown', keydown);
			document.detachEvent('onkeyup', keyup);
			window.detachEvent('onblur', reset);
		}
	}

	////////////////////
	// EVENT HANDLERS //
	////////////////////

	/**
	 * Exits all active bindings. Optionally passes an event to all binding
	 *  handlers.
	 * @param  {KeyboardEvent}	event	[Optional]
	 */
	function reset(event) {
		activeKeys = [];
		pruneMacros();
		pruneBindings(event);
	}

	/**
	 * Key down event handler.
	 * @param  {KeyboardEvent}	event
	 */
	function keydown(event) {
		var keyNames, kI;
		keyNames = getKeyName(event.keyCode);
		if(keyNames.length < 1) { return; }
		for(kI = 0; kI < keyNames.length; kI += 1) {
			addActiveKey(keyNames[kI]);
		}
		executeMacros();
		executeBindings(event);
	}

	/**
	 * Key up event handler.
	 * @param  {KeyboardEvent} event
	 */
	function keyup(event) {
		var keyNames, kI;
		keyNames = getKeyName(event.keyCode);
		if(keyNames.length < 1) { return; }
		for(kI = 0; kI < keyNames.length; kI += 1) {
			removeActiveKey(keyNames[kI]);
		}
		pruneMacros();
		pruneBindings(event);
	}

	/**
	 * Accepts a key code and returns the key names defined by the current
	 *  locale.
	 * @param  {Number}	keyCode
	 * @return {Array}	keyNames	An array of key names defined for the key
	 *  code as defined by the current locale.
	 */
	function getKeyName(keyCode) {
		return map[keyCode] || [];
	}

	/**
	 * Accepts a key name and returns the key code defined by the current
	 *  locale.
	 * @param  {Number}	keyName
	 * @return {Number|false}
	 */
	function getKeyCode(keyName) {
		var keyCode;
		for(keyCode in map) {
			if(!map.hasOwnProperty(keyCode)) { continue; }
			if(map[keyCode].indexOf(keyName) > -1) { return keyCode; }
		}
		return false;
	}

	////////////
	// MACROS //
	////////////

	/**
	 * Accepts a key combo and an array of key names to inject once the key
	 *  combo is satisfied.
	 * @param  {String}	combo
	 * @param  {Array}	injectedKeys
	 */
	function createMacro(combo, injectedKeys) {
		if(typeof combo !== 'string' && (typeof combo !== 'object' || typeof combo.push !== 'function')) {
			throw new Error("Cannot create macro. The combo must be a string or array.");
		}
		if(typeof injectedKeys !== 'object' || typeof injectedKeys.push !== 'function') {
			throw new Error("Cannot create macro. The injectedKeys must be an array.");
		}
		macros.push([combo, injectedKeys]);
	}

	/**
	 * Accepts a key combo and clears any and all macros bound to that key
	 * combo.
	 * @param  {String} combo
	 */
	function removeMacro(combo) {
		var macro;
		if(typeof combo !== 'string' && (typeof combo !== 'object' || typeof combo.push !== 'function')) { throw new Error("Cannot remove macro. The combo must be a string or array."); }
		for(mI = 0; mI < macros.length; mI += 1) {
			macro = macros[mI];
			if(compareCombos(combo, macro[0])) {
				removeActiveKey(macro[1]);
				macros.splice(mI, 1);
				break;
			}
		}
	}

	/**
	 * Executes macros against the active keys. Each macro's key combo is
	 *  checked and if found to be satisfied, the macro's key names are injected
	 *  into active keys.
	 */
	function executeMacros() {
		var mI, combo, kI;
		for(mI = 0; mI < macros.length; mI += 1) {
			combo = parseKeyCombo(macros[mI][0]);
			if(activeMacros.indexOf(macros[mI]) === -1 && isSatisfiedCombo(combo)) {
				activeMacros.push(macros[mI]);
				for(kI = 0; kI < macros[mI][1].length; kI += 1) {
					addActiveKey(macros[mI][1][kI]);
				}
			}
		}
	}

	/**
	 * Prunes active macros. Checks each active macro's key combo and if found
	 *  to no longer to be satisfied, each of the macro's key names are removed
	 *  from active keys.
	 */
	function pruneMacros() {
		var mI, combo, kI;
		for(mI = 0; mI < activeMacros.length; mI += 1) {
			combo = parseKeyCombo(activeMacros[mI][0]);
			if(isSatisfiedCombo(combo) === false) {
				for(kI = 0; kI < activeMacros[mI][1].length; kI += 1) {
					removeActiveKey(activeMacros[mI][1][kI]);
				}
				activeMacros.splice(mI, 1);
				mI -= 1;
			}
		}
	}

	//////////////
	// BINDINGS //
	//////////////

	/**
	 * Creates a binding object, and, if provided, binds a key down hander and
	 *  a key up handler. Returns a binding object that emits keyup and
	 *  keydown events.
	 * @param  {String}		keyCombo
	 * @param  {Function}	keyDownCallback	[Optional]
	 * @param  {Function}	keyUpCallback	[Optional]
	 * @return {Object}		binding
	 */
	function createBinding(keyCombo, keyDownCallback, keyUpCallback) {
		var api = {}, binding, subBindings = [], bindingApi = {}, kI,
		subCombo;

		//break the combo down into a combo array
		if(typeof keyCombo === 'string') {
			keyCombo = parseKeyCombo(keyCombo);
		}

		//bind each sub combo contained within the combo string
		for(kI = 0; kI < keyCombo.length; kI += 1) {
			binding = {};

			//stringify the combo again
			subCombo = stringifyKeyCombo([keyCombo[kI]]);

			//validate the sub combo
			if(typeof subCombo !== 'string') { throw new Error('Failed to bind key combo. The key combo must be string.'); }

			//create the binding
			binding.keyCombo = subCombo;
			binding.keyDownCallback = [];
			binding.keyUpCallback = [];

			//inject the key down and key up callbacks if given
			if(keyDownCallback) { binding.keyDownCallback.push(keyDownCallback); }
			if(keyUpCallback) { binding.keyUpCallback.push(keyUpCallback); }

			//stash the new binding
			bindings.push(binding);
			subBindings.push(binding);
		}

		//build the binding api
		api.clear = clear;
		api.on = on;
		return api;

		/**
		 * Clears the binding
		 */
		function clear() {
			var bI;
			for(bI = 0; bI < subBindings.length; bI += 1) {
				bindings.splice(bindings.indexOf(subBindings[bI]), 1);
			}
		}

		/**
		 * Accepts an event name. and any number of callbacks. When the event is
		 *  emitted, all callbacks are executed. Available events are key up and
		 *  key down.
		 * @param  {String}	eventName
		 * @return {Object}	subBinding
		 */
		function on(eventName    ) {
			var api = {}, callbacks, cI, bI;

			//validate event name
			if(typeof eventName !== 'string') { throw new Error('Cannot bind callback. The event name must be a string.'); }
			if(eventName !== 'keyup' && eventName !== 'keydown') { throw new Error('Cannot bind callback. The event name must be a "keyup" or "keydown".'); }

			//gather the callbacks
			callbacks = Array.prototype.slice.apply(arguments, [1]);

			//stash each the new binding
			for(cI = 0; cI < callbacks.length; cI += 1) {
				if(typeof callbacks[cI] === 'function') {
					if(eventName === 'keyup') {
						for(bI = 0; bI < subBindings.length; bI += 1) {
							subBindings[bI].keyUpCallback.push(callbacks[cI]);
						}
					} else if(eventName === 'keydown') {
						for(bI = 0; bI < subBindings.length; bI += 1) {
							subBindings[bI].keyDownCallback.push(callbacks[cI]);
						}
					}
				}
			}

			//construct and return the sub binding api
			api.clear = clear;
			return api;

			/**
			* Clears the binding
			*/
			function clear() {
				var cI, bI;
				for(cI = 0; cI < callbacks.length; cI += 1) {
					if(typeof callbacks[cI] === 'function') {
						if(eventName === 'keyup') {
							for(bI = 0; bI < subBindings.length; bI += 1) {
								subBindings[bI].keyUpCallback.splice(subBindings[bI].keyUpCallback.indexOf(callbacks[cI]), 1);
							}
						} else {
							for(bI = 0; bI < subBindings.length; bI += 1) {
								subBindings[bI].keyDownCallback.splice(subBindings[bI].keyDownCallback.indexOf(callbacks[cI]), 1);
							}
						}
					}
				}
			}
		}
	}

	/**
	 * Clears all binding attached to a given key combo. Key name order does not
	 * matter as long as the key combos equate.
	 * @param  {String}	keyCombo
	 */
	function removeBindingByKeyCombo(keyCombo) {
		var bI, binding, keyName;
		for(bI = 0; bI < bindings.length; bI += 1) {
			binding = bindings[bI];
			if(compareCombos(keyCombo, binding.keyCombo)) {
				bindings.splice(bI, 1); bI -= 1;
			}
		}
	}

	/**
	 * Clears all binding attached to key combos containing a given key name.
	 * @param  {String}	keyName
	 */
	function removeBindingByKeyName(keyName) {
		var bI, cI, binding;
		if(keyName) {
			for(bI = 0; bI < bindings.length; bI += 1) {
				binding = bindings[bI];
				for(cI = 0; cI < binding.keyCombo.length; cI += 1) {
					if(binding.keyCombo[kI].indexOf(keyName) > -1) {
						bindings.splice(bI, 1); bI -= 1;
						break;
					}
				}
			}
		} else {
			bindings = [];
		}
	}

	/**
	 * Executes bindings that are active. Only allows the keys to be used once
	 *  as to prevent binding overlap.
	 * @param  {KeyboardEvent}	event	The keyboard event.
	 */
	function executeBindings(event) {
		var bI, sBI, binding, bidningKeys, remainingKeys, cI, killEventBubble, kI, bindingKeysSatisfied,
		index, sortedBindings = [], bindingWeight;

		remainingKeys = [].concat(activeKeys);
		for(bI = 0; bI < bindings.length; bI += 1) {
			bindingWeight = extractComboKeys(bindings[bI].keyCombo).length;
			if(!sortedBindings[bindingWeight]) { sortedBindings[bindingWeight] = []; }
			sortedBindings[bindingWeight].push(bindings[bI]);
		}
		for(sBI = sortedBindings.length - 1; sBI >= 0; sBI -= 1) {
			if(!sortedBindings[sBI]) { continue; }
			for(bI = 0; bI < sortedBindings[sBI].length; bI += 1) {
				binding = sortedBindings[sBI][bI];
				bindingKeys = extractComboKeys(binding.keyCombo);
				bindingKeysSatisfied = true;
				for(kI = 0; kI < bindingKeys.length; kI += 1) {
					if(remainingKeys.indexOf(bindingKeys[kI]) === -1) {
						bindingKeysSatisfied = false;
						break;
					}
				}
				if(bindingKeysSatisfied && isSatisfiedCombo(binding.keyCombo)) {
					activeBindings.push(binding);
					for(kI = 0; kI < bindingKeys.length; kI += 1) {
						index = remainingKeys.indexOf(bindingKeys[kI]);
						if(index > -1) {
							remainingKeys.splice(index, 1);
							kI -= 1;
						}
					}
					for(cI = 0; cI < binding.keyDownCallback.length; cI += 1) {
						if (binding.keyDownCallback[cI](event, getActiveKeys(), binding.keyCombo) === false) {
							killEventBubble = true;
						}
					}
					if(killEventBubble === true) {
						event.preventDefault();
						event.stopPropagation();
					}
				}
			}
		}
	}

	/**
	 * Removes bindings that are no longer satisfied by the active keys. Also
	 *  fires the key up callbacks.
	 * @param  {KeyboardEvent}	event
	 */
	function pruneBindings(event) {
		var bI, cI, binding, killEventBubble;
		for(bI = 0; bI < activeBindings.length; bI += 1) {
			binding = activeBindings[bI];
			if(isSatisfiedCombo(binding.keyCombo) === false) {
				for(cI = 0; cI < binding.keyUpCallback.length; cI += 1) {
					if (binding.keyUpCallback[cI](event, getActiveKeys(), binding.keyCombo) === false) {
						killEventBubble = true;
					}
				}
				if(killEventBubble === true) {
					event.preventDefault();
					event.stopPropagation();
				}
				activeBindings.splice(bI, 1);
				bI -= 1;
			}
		}
	}

	///////////////////
	// COMBO STRINGS //
	///////////////////

	/**
	 * Compares two key combos returning true when they are functionally
	 *  equivalent.
	 * @param  {String}	keyComboArrayA keyCombo A key combo string or array.
	 * @param  {String}	keyComboArrayB keyCombo A key combo string or array.
	 * @return {Boolean}
	 */
	function compareCombos(keyComboArrayA, keyComboArrayB) {
		var cI, sI, kI;
		keyComboArrayA = parseKeyCombo(keyComboArrayA);
		keyComboArrayB = parseKeyCombo(keyComboArrayB);
		if(keyComboArrayA.length !== keyComboArrayB.length) { return false; }
		for(cI = 0; cI < keyComboArrayA.length; cI += 1) {
			if(keyComboArrayA[cI].length !== keyComboArrayB[cI].length) { return false; }
			for(sI = 0; sI < keyComboArrayA[cI].length; sI += 1) {
				if(keyComboArrayA[cI][sI].length !== keyComboArrayB[cI][sI].length) { return false; }
				for(kI = 0; kI < keyComboArrayA[cI][sI].length; kI += 1) {
					if(keyComboArrayB[cI][sI].indexOf(keyComboArrayA[cI][sI][kI]) === -1) { return false; }
				}
			}
		}
		return true;
	}

	/**
	 * Checks to see if a key combo string or key array is satisfied by the
	 *  currently active keys. It does not take into account spent keys.
	 * @param  {String}	keyCombo	A key combo string or array.
	 * @return {Boolean}
	 */
	function isSatisfiedCombo(keyCombo) {
		var cI, sI, stage, kI, stageOffset = 0, index, comboMatches;
		keyCombo = parseKeyCombo(keyCombo);
		for(cI = 0; cI < keyCombo.length; cI += 1) {
			comboMatches = true;
			stageOffset = 0;
			for(sI = 0; sI < keyCombo[cI].length; sI += 1) {
				stage = [].concat(keyCombo[cI][sI]);
				for(kI = stageOffset; kI < activeKeys.length; kI += 1) {
					index = stage.indexOf(activeKeys[kI]);
					if(index > -1) {
						stage.splice(index, 1);
						stageOffset = kI;
					}
				}
				if(stage.length !== 0) { comboMatches = false; break; }
			}
			if(comboMatches) { return true; }
		}
		return false;
	}

	/**
	 * Accepts a key combo array or string and returns a flat array containing all keys referenced by
	 * the key combo.
	 * @param  {String}	keyCombo	A key combo string or array.
	 * @return {Array}
	 */
	function extractComboKeys(keyCombo) {
		var cI, sI, kI, keys = [];
		keyCombo = parseKeyCombo(keyCombo);
		for(cI = 0; cI < keyCombo.length; cI += 1) {
			for(sI = 0; sI < keyCombo[cI].length; sI += 1) {
				keys = keys.concat(keyCombo[cI][sI]);
			}
		}
		return keys;
	}

	/**
	 * Parses a key combo string into a 3 dimensional array.
	 * - Level 1 - sub combos.
	 * - Level 2 - combo stages. A stage is a set of key name pairs that must
	 *  be satisfied in the order they are defined.
	 * - Level 3 - each key name to the stage.
	 * @param  {String|Array}	keyCombo	A key combo string.
	 * @return {Array}
	 */
	function parseKeyCombo(keyCombo) {
		var s = keyCombo, i = 0, op = 0, ws = false, nc = false, combos = [], combo = [], stage = [], key = '';

		if(typeof keyCombo === 'object' && typeof keyCombo.push === 'function') { return keyCombo; }
		if(typeof keyCombo !== 'string') { throw new Error('Cannot parse "keyCombo" because its type is "' + (typeof keyCombo) + '". It must be a "string".'); }

		//remove leading whitespace
		while(s.charAt(i) === ' ') { i += 1; }
		while(true) {
			if(s.charAt(i) === ' ') {
				//white space & next combo op
				while(s.charAt(i) === ' ') { i += 1; }
				ws = true;
			} else if(s.charAt(i) === ',') {
				if(op || nc) { throw new Error('Failed to parse key combo. Unexpected , at character index ' + i + '.'); }
				nc = true;
				i += 1;
			} else if(s.charAt(i) === '+') {
				//next key
				if(key.length) { stage.push(key); key = ''; }
				if(op || nc) { throw new Error('Failed to parse key combo. Unexpected + at character index ' + i + '.'); }
				op = true;
				i += 1;
			} else if(s.charAt(i) === '>') {
				//next stage op
				if(key.length) { stage.push(key); key = ''; }
				if(stage.length) { combo.push(stage); stage = []; }
				if(op || nc) { throw new Error('Failed to parse key combo. Unexpected > at character index ' + i + '.'); }
				op = true;
				i += 1;
			} else if(i < s.length - 1 && s.charAt(i) === '!' && (s.charAt(i + 1) === '>' || s.charAt(i + 1) === ',' || s.charAt(i + 1) === '+')) {
				key += s.charAt(i + 1);
				op = false;
				ws = false;
				nc = false;
				i += 2;
			} else if(i < s.length && s.charAt(i) !== '+' && s.charAt(i) !== '>' && s.charAt(i) !== ',' && s.charAt(i) !== ' ') {
				//end combo
				if(op === false && ws === true || nc === true) {
					if(key.length) { stage.push(key); key = ''; }
					if(stage.length) { combo.push(stage); stage = []; }
					if(combo.length) { combos.push(combo); combo = []; }
				}
				op = false;
				ws = false;
				nc = false;
				//key
				while(i < s.length && s.charAt(i) !== '+' && s.charAt(i) !== '>' && s.charAt(i) !== ',' && s.charAt(i) !== ' ') {
					key += s.charAt(i);
					i += 1;
				}
			} else {
				//unknown char
				i += 1;
				continue;
			}
			//end of combos string
			if(i >= s.length) {
				if(key.length) { stage.push(key); key = ''; }
				if(stage.length) { combo.push(stage); stage = []; }
				if(combo.length) { combos.push(combo); combo = []; }
				break;
			}
		}
		return combos;
	}

	/**
	 * Stringifys a key combo.
	 * @param  {Array|String}	keyComboArray	A key combo array. If a key
	 *  combo string is given it will be returned.
	 * @return {String}
	 */
	function stringifyKeyCombo(keyComboArray) {
		var cI, ccI, output = [];
		if(typeof keyComboArray === 'string') { return keyComboArray; }
		if(typeof keyComboArray !== 'object' || typeof keyComboArray.push !== 'function') { throw new Error('Cannot stringify key combo.'); }
		for(cI = 0; cI < keyComboArray.length; cI += 1) {
			output[cI] = [];
			for(ccI = 0; ccI < keyComboArray[cI].length; ccI += 1) {
				output[cI][ccI] = keyComboArray[cI][ccI].join(' + ');
			}
			output[cI] = output[cI].join(' > ');
		}
		return output.join(' ');
	}

	/////////////////
	// ACTIVE KEYS //
	/////////////////

	/**
	 * Returns the a copy of the active keys array.
	 * @return {Array}
	 */
	function getActiveKeys() {
		return [].concat(activeKeys);
	}

	/**
	 * Adds a key to the active keys array, but only if it has not already been
	 *  added.
	 * @param {String}	keyName	The key name string.
	 */
	function addActiveKey(keyName) {
		if(keyName.match(/\s/)) { throw new Error('Cannot add key name ' + keyName + ' to active keys because it contains whitespace.'); }
		if(activeKeys.indexOf(keyName) > -1) { return; }
		activeKeys.push(keyName);
	}

	/**
	 * Removes a key from the active keys array.
	 * @param  {String}	keyNames	The key name string.
	 */
	function removeActiveKey(keyName) {
		var keyCode = getKeyCode(keyName);
		if(keyCode === '91' || keyCode === '92') { activeKeys = []; } //remove all key on release of super.
		else { activeKeys.splice(activeKeys.indexOf(keyName), 1); }
	}

	/////////////
	// LOCALES //
	/////////////

	/**
	 * Registers a new locale. This is useful if you would like to add support for a new keyboard layout. It could also be useful for
	 * alternative key names. For example if you program games you could create a locale for your key mappings. Instead of key 65 mapped
	 * to 'a' you could map it to 'jump'.
	 * @param  {String}	localeName	The name of the new locale.
	 * @param  {Object}	localeMap	The locale map.
	 */
	function registerLocale(localeName, localeMap) {

		//validate arguments
		if(typeof localeName !== 'string') { throw new Error('Cannot register new locale. The locale name must be a string.'); }
		if(typeof localeMap !== 'object') { throw new Error('Cannot register ' + localeName + ' locale. The locale map must be an object.'); }
		if(typeof localeMap.map !== 'object') { throw new Error('Cannot register ' + localeName + ' locale. The locale map is invalid.'); }

		//stash the locale
		if(!localeMap.macros) { localeMap.macros = []; }
		locales[localeName] = localeMap;
	}

	/**
	 * Swaps the current locale.
	 * @param  {String}	localeName	The locale to activate.
	 * @return {Object}
	 */
	function getSetLocale(localeName) {

		//if a new locale is given then set it
		if(localeName) {
			if(typeof localeName !== 'string') { throw new Error('Cannot set locale. The locale name must be a string.'); }
			if(!locales[localeName]) { throw new Error('Cannot set locale to ' + localeName + ' because it does not exist. If you would like to submit a ' + localeName + ' locale map for KeyboardJS please submit it at https://github.com/RobertWHurst/KeyboardJS/issues.'); }

			//set the current map and macros
			map = locales[localeName].map;
			macros = locales[localeName].macros;

			//set the current locale
			locale = localeName;
		}

		//return the current locale
		return locale;
	}
});


text:
module Kalman

export State,
AbstractState,
UnscentedState,
Observation,
KalmanFilter,
LinearKalmanFilter,
BasicKalmanFilter,
Model,
ObservationModel,
LinearModel,
LinearObservationModel,
predict,
update,
predictupdate,
predict!,
update!,
predictupdate!,
BasicExtendedKalmanFilter,
NonlinearModel,
NonlinearObservationModel,
ExtendedKalmanFilter,
AdditiveUnscentedKalmanFilter,
UnscentedKalmanFilter,
AdditiveUnscentedModel,
AdditiveUnscentedObservationModel,
sigma,
AugmentedUnscentedModel,
AugmentedUnscentedObservationModel,
AugmentedUnscentedKalmanFilter,
augment

include("bkf.jl")
include("filter.jl")
include("ekf.jl")
include("unscented.jl")
include("augmented.jl")

# Nullable Observations work but only for Julia v0.4
if VERSION >= v"0.4.0-"
    include("nullable.jl")
end

end # module

redpajama_set_name: RedPajamaGithub


text:
package com.twitter.crunch;

public interface NodeFilter {
  boolean accept(Node node);
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="hello">Hello World, Wifiutils_testActivity!</string>
    <string name="app_name">WifiGlue</string>
    <string name="netname">Network Name</string>
    <string name="netpwd">Network Password</string>
    <string name="create">Create</string>
    <string name="connect">Connect</string>
    <string name="stop">Stop</string>
    <string name="notif_title">Service Notification for User</string>
    <string name="exit_srv">Exit Service</string>
    <string name="test_1">Test=1</string>
    <string name="test_2">Test=2</string>
    <string name="test_3">Test=3</string>
    <string name="start_srv">Start Service</string>
    <string name="tether_title">WifiGlue Thether</string>
    <string name="wifidirect_title">WifiGlue Direct</string>
    <string name="discovery_title">WifiGlue Discovery</string>
    <string name="test">Test</string>

</resources>


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
    Licensed to the Apache Software Foundation (ASF) under one or more
    contributor license agreements.  See the NOTICE file distributed with
    this work for additional information regarding copyright ownership.
    The ASF licenses this file to You under the Apache License, Version 2.0
    (the "License"); you may not use this file except in compliance with
    the License.  You may obtain a copy of the License at

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

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

<module xmlns="http://geronimo.apache.org/xml/ns/deployment-${geronimoSchemaVersion}">

    <!-- ServerInfo service -->
    <gbean name="ServerInfo" class="org.apache.geronimo.system.serverinfo.BasicServerInfo">
        <attribute name="useSystemProperties">true</attribute>
    </gbean>

    <!--Repository-->
    <gbean name="Repository" class="org.apache.geronimo.system.repository.Maven2Repository">
        <attribute name="root">repository/</attribute>
        <reference name="ServerInfo">
            <name>ServerInfo</name>
        </reference>
    </gbean>

    <!--Configuration Store service-->
    <gbean name="Local" class="org.apache.geronimo.system.configuration.RepositoryConfigurationStore">
        <reference name="Repository">
            <name>Repository</name>
        </reference>
    </gbean>

    <!--User-editable attribute service-->
    <gbean name="AttributeManager" class="org.apache.geronimo.system.configuration.LocalAttributeManager">
        <reference name="ServerInfo">
            <name>ServerInfo</name>
        </reference>
        <attribute name="readOnly">true</attribute>
        <attribute name="configFile">var/config/config.xml</attribute>
        <attribute name="substitutionsFile">var/config/config-substitutions.properties</attribute>
        <attribute name="substitutionPrefix">org.apache.geronimo.config.substitution.</attribute>
    </gbean>

    <!-- ArtifactManager -->
    <gbean name="ArtifactManager" class="org.apache.geronimo.kernel.repository.DefaultArtifactManager"/>

    <!-- ArtifactResolver -->
    <gbean name="ArtifactResolver" class="org.apache.geronimo.system.resolver.ExplicitDefaultArtifactResolver">
        <reference name="ArtifactManager">
            <name>ArtifactManager</name>
        </reference>
        <reference name="Repositories"></reference>
        <attribute name="versionMapLocation">var/config/client_artifact_aliases.properties</attribute>
        <reference name="ServerInfo">
            <name>ServerInfo</name>
        </reference>
    </gbean>

    <!--Configuration Manager service-->
    <gbean name="ConfigurationManager" class="org.apache.geronimo.kernel.config.KernelConfigurationManager">
        <reference name="Repositories">
        </reference>
        <reference name="Stores">
        </reference>
        <reference name="AttributeStore">
            <name>AttributeManager</name>
        </reference>
        <reference name="PersistentConfigurationList">
            <type>AttributeStore</type>
            <name>AttributeManager</name>
        </reference>
        <reference name="ArtifactManager">
            <name>ArtifactManager</name>
        </reference>
        <reference name="ArtifactResolver">
            <name>ArtifactResolver</name>
        </reference>
    </gbean>

    <gbean name="DependencyManager" class="org.apache.geronimo.system.configuration.DependencyManager">
        <reference name="Repositories"></reference>
        <reference name="ArtifactResolver">
            <name>ArtifactResolver</name>
        </reference>
    </gbean>

    <!-- Logging service -->
    <!--
    <gbean name="Logger" class="org.apache.geronimo.system.logging.log4j.Log4jService">
        <attribute name="configFileName">var/log/client-log4j.properties</attribute>
        <attribute name="refreshPeriodSeconds">60</attribute>
        <reference name="ServerInfo">
            <name>ServerInfo</name>
        </reference>
    </gbean>
    -->

    <gbean name="EmbeddedClientCommandLine" class="org.apache.geronimo.system.main.EmbeddedClientCommandLine"/>

</module>


text:
package com.sequenceiq.cloudbreak.cloud.openstack.status;

import com.google.common.base.Strings;
import com.sequenceiq.cloudbreak.cloud.model.ResourceStatus;

public class HeatStackStatus {

    private HeatStackStatus() {
    }

    public static ResourceStatus mapResourceStatus(String status) {
        if (Strings.isNullOrEmpty(status) || status.contains("FAILED")) {
            return ResourceStatus.FAILED;
        }

        switch (status) {
            case "CREATE_COMPLETE":
                return ResourceStatus.CREATED;
            case "DELETE_COMPLETE":
                return ResourceStatus.DELETED;
            case "UPDATE_COMPLETE":
                return ResourceStatus.UPDATED;
            default:
                return ResourceStatus.IN_PROGRESS;

        }
    }
}


text:
using base::ASCIIToUTF16;
using base::TimeTicks;
using content::InterstitialPage;
using content::InterstitialPageDelegate;
using content::NavigationController;
using content::NavigationEntry;

namespace {

// URL for help page.
const char kHelpURL[] = "https://support.google.com/chrome/answer/4454607";

// Constants for the Experience Sampling instrumentation.
const char kEventNameBase[] = "ssl_interstitial_";
const char kEventNotOverridable[] = "notoverridable_";
const char kEventOverridable[] = "overridable_";

// Events for UMA. Do not reorder or change!
enum SSLExpirationAndDecision {
  EXPIRED_AND_PROCEED,
  EXPIRED_AND_DO_NOT_PROCEED,
  NOT_EXPIRED_AND_PROCEED,
  NOT_EXPIRED_AND_DO_NOT_PROCEED,
  END_OF_SSL_EXPIRATION_AND_DECISION,
};

// Rappor prefix
const char kSSLRapporPrefix[] = "ssl";

void RecordSSLExpirationPageEventState(bool expired_but_previously_allowed,
                                       bool proceed,
                                       bool overridable) {
  SSLExpirationAndDecision event;
  if (expired_but_previously_allowed && proceed)
    event = EXPIRED_AND_PROCEED;
  else if (expired_but_previously_allowed && !proceed)
    event = EXPIRED_AND_DO_NOT_PROCEED;
  else if (!expired_but_previously_allowed && proceed)
    event = NOT_EXPIRED_AND_PROCEED;
  else
    event = NOT_EXPIRED_AND_DO_NOT_PROCEED;

  if (overridable) {
    UMA_HISTOGRAM_ENUMERATION(
        "interstitial.ssl.expiration_and_decision.overridable",
        event,
        END_OF_SSL_EXPIRATION_AND_DECISION);
  } else {
    UMA_HISTOGRAM_ENUMERATION(
        "interstitial.ssl.expiration_and_decision.nonoverridable",
        event,
        END_OF_SSL_EXPIRATION_AND_DECISION);
  }
}

void LaunchDateAndTimeSettings() {
  // The code for each OS is completely separate, in order to avoid bugs like
  // https://crbug.com/430877 .
#if defined(OS_ANDROID)
  chrome::android::OpenDateAndTimeSettings();

#elif defined(OS_CHROMEOS)
  std::string sub_page = std::string(chrome::kSearchSubPage) + "#" +
      l10n_util::GetStringUTF8(IDS_OPTIONS_SETTINGS_SECTION_TITLE_DATETIME);
  chrome::ShowSettingsSubPageForProfile(
      ProfileManager::GetActiveUserProfile(), sub_page);

#elif defined(OS_IOS)
  // iOS does not have a way to launch the date and time settings.
  NOTREACHED();

#elif defined(OS_LINUX)
  struct ClockCommand {
    const char* pathname;
    const char* argument;
  };
  static const ClockCommand kClockCommands[] = {
    // Unity
    { "/usr/bin/unity-control-center", "datetime" },
    // GNOME
    //
    // NOTE: On old Ubuntu, naming control panels doesn't work, so it
    // opens the overview. This will have to be good enough.
    { "/usr/bin/gnome-control-center", "datetime" },
    { "/usr/local/bin/gnome-control-center", "datetime" },
    { "/opt/bin/gnome-control-center", "datetime" },
    // KDE
    { "/usr/bin/kcmshell4", "clock" },
    { "/usr/local/bin/kcmshell4", "clock" },
    { "/opt/bin/kcmshell4", "clock" },
  };

  base::CommandLine command(base::FilePath(""));
  for (size_t i = 0; i < arraysize(kClockCommands); ++i) {
    base::FilePath pathname(kClockCommands[i].pathname);
    if (base::PathExists(pathname)) {
      command.SetProgram(pathname);
      command.AppendArg(kClockCommands[i].argument);
      break;
    }
  }
  if (command.GetProgram().empty()) {
    // Alas, there is nothing we can do.
    return;
  }

  base::LaunchOptions options;
  options.wait = false;
  options.allow_new_privs = true;
  base::LaunchProcess(command, options);

#elif defined(OS_MACOSX)
  base::CommandLine command(base::FilePath("/usr/bin/open"));
  command.AppendArg("/System/Library/PreferencePanes/DateAndTime.prefPane");

  base::LaunchOptions options;
  options.wait = false;
  base::LaunchProcess(command, options);

#elif defined(OS_WIN)
  base::FilePath path;
  PathService::Get(base::DIR_SYSTEM, &path);
  static const base::char16 kControlPanelExe[] = L"control.exe";
  path = path.Append(base::string16(kControlPanelExe));
  base::CommandLine command(path);
  command.AppendArg(std::string("/name"));
  command.AppendArg(std::string("Microsoft.DateAndTime"));

  base::LaunchOptions options;
  options.wait = false;
  base::LaunchProcess(command, options);

#else
  NOTREACHED();

#endif
  // Don't add code here! (See the comment at the beginning of the function.)
}

bool IsErrorDueToBadClock(const base::Time& now, int error) {
  if (SSLErrorInfo::NetErrorToErrorType(error) !=
          SSLErrorInfo::CERT_DATE_INVALID) {
    return false;
  }
  return SSLErrorClassification::IsUserClockInThePast(now) ||
      SSLErrorClassification::IsUserClockInTheFuture(now);
}

}  // namespace

// static
InterstitialPageDelegate::TypeID SSLBlockingPage::kTypeForTesting =
    &SSLBlockingPage::kTypeForTesting;

// Note that we always create a navigation entry with SSL errors.
// No error happening loading a sub-resource triggers an interstitial so far.
SSLBlockingPage::SSLBlockingPage(content::WebContents* web_contents,
                                 int cert_error,
                                 const net::SSLInfo& ssl_info,
                                 const GURL& request_url,
                                 int options_mask,
                                 const base::Time& time_triggered,
                                 const base::Callback<void(bool)>& callback)
    : SecurityInterstitialPage(web_contents, request_url),
      callback_(callback),
      cert_error_(cert_error),
      ssl_info_(ssl_info),
      overridable_(IsOptionsOverridable(options_mask)),
      danger_overridable_(true),
      strict_enforcement_((options_mask & STRICT_ENFORCEMENT) != 0),
      expired_but_previously_allowed_(
          (options_mask & EXPIRED_BUT_PREVIOUSLY_ALLOWED) != 0),
      time_triggered_(time_triggered) {
  interstitial_reason_ =
      IsErrorDueToBadClock(time_triggered_, cert_error_) ?
      SSL_REASON_BAD_CLOCK : SSL_REASON_SSL;

  // We collapse the Rappor metric name to just "ssl" so we don't leak
  // the "overridable" bit.  We skip Rappor altogether for bad clocks.
  // This must be done after calculating |interstitial_reason_| above.
  metrics_helper_.reset(new SecurityInterstitialMetricsHelper(
      web_contents, request_url, GetUmaHistogramPrefix(), kSSLRapporPrefix,
      (interstitial_reason_ == SSL_REASON_BAD_CLOCK
           ? SecurityInterstitialMetricsHelper::SKIP_RAPPOR
           : SecurityInterstitialMetricsHelper::REPORT_RAPPOR),
      GetSamplingEventName()));

  metrics_helper_->RecordUserDecision(SecurityInterstitialMetricsHelper::SHOW);
  metrics_helper_->RecordUserInteraction(
      SecurityInterstitialMetricsHelper::TOTAL_VISITS);

  ssl_error_classification_.reset(new SSLErrorClassification(
      web_contents,
      time_triggered_,
      request_url,
      cert_error_,
      *ssl_info_.cert.get()));
  ssl_error_classification_->RecordUMAStatistics(overridable_);

  // Creating an interstitial without showing (e.g. from chrome://interstitials)
  // it leaks memory, so don't create it here.
}

bool SSLBlockingPage::ShouldCreateNewNavigation() const {
  return true;
}

InterstitialPageDelegate::TypeID SSLBlockingPage::GetTypeForTesting() const {
  return SSLBlockingPage::kTypeForTesting;
}

SSLBlockingPage::~SSLBlockingPage() {
#if defined(ENABLE_CAPTIVE_PORTAL_DETECTION)
  // Captive portal detection results can arrive anytime during the interstitial
  // is being displayed, so record it when the interstitial is going away.
  ssl_error_classification_->RecordCaptivePortalUMAStatistics(overridable_);
#endif
  if (!callback_.is_null()) {
    // The page is closed without the user having chosen what to do, default to
    // deny.
    metrics_helper_->RecordUserDecision(
        SecurityInterstitialMetricsHelper::DONT_PROCEED);
    RecordSSLExpirationPageEventState(
        expired_but_previously_allowed_, false, overridable_);
    NotifyDenyCertificate();
  }
}

void SSLBlockingPage::PopulateInterstitialStrings(
    base::DictionaryValue* load_time_data) {
  CHECK(load_time_data);
  base::string16 url(GetFormattedHostName());
  // Shared values for both the overridable and non-overridable versions.
  load_time_data->SetString("type", "SSL");

  // Shared UI configuration for all SSL interstitials.
  load_time_data->SetString("errorCode", net::ErrorToString(cert_error_));
  load_time_data->SetString(
      "openDetails",
      l10n_util::GetStringUTF16(IDS_SSL_V2_OPEN_DETAILS_BUTTON));
  load_time_data->SetString(
      "closeDetails",
      l10n_util::GetStringUTF16(IDS_SSL_V2_CLOSE_DETAILS_BUTTON));

  // Conditional UI configuration.
  if (interstitial_reason_ == SSL_REASON_BAD_CLOCK) {
    load_time_data->SetBoolean("bad_clock", true);
    load_time_data->SetBoolean("overridable", false);

#if defined(OS_IOS)
    load_time_data->SetBoolean("hide_primary_button", true);
#else
    load_time_data->SetBoolean("hide_primary_button", false);
#endif

    // We're showing the SSL clock warning to be helpful, but we haven't warned
    // them about the risks. (And there might still be an SSL error after they
    // fix their clock.) Thus, we don't allow the "danger" override in this
    // case.
    danger_overridable_ = false;

    int heading_string =
        SSLErrorClassification::IsUserClockInTheFuture(time_triggered_) ?
        IDS_SSL_V2_CLOCK_AHEAD_HEADING :
        IDS_SSL_V2_CLOCK_BEHIND_HEADING;

    load_time_data->SetString(
        "tabTitle",
        l10n_util::GetStringUTF16(IDS_SSL_V2_CLOCK_TITLE));
    load_time_data->SetString(
        "heading",
        l10n_util::GetStringUTF16(heading_string));
    load_time_data->SetString(
        "primaryParagraph",
        l10n_util::GetStringFUTF16(
            IDS_SSL_V2_CLOCK_PRIMARY_PARAGRAPH,
            url,
            base::TimeFormatFriendlyDateAndTime(time_triggered_)));

    load_time_data->SetString(
        "primaryButtonText",
        l10n_util::GetStringUTF16(IDS_SSL_V2_CLOCK_UPDATE_DATE_AND_TIME));
    load_time_data->SetString(
        "explanationParagraph",
        l10n_util::GetStringUTF16(IDS_SSL_V2_CLOCK_EXPLANATION));

    // The interstitial template expects this string, but we're not using it. So
    // we send a blank string for now.
    load_time_data->SetString("finalParagraph", std::string());
  } else {
    load_time_data->SetBoolean("bad_clock", false);

    load_time_data->SetString(
        "tabTitle", l10n_util::GetStringUTF16(IDS_SSL_V2_TITLE));
    load_time_data->SetString(
        "heading", l10n_util::GetStringUTF16(IDS_SSL_V2_HEADING));
    load_time_data->SetString(
        "primaryParagraph",
        l10n_util::GetStringFUTF16(IDS_SSL_V2_PRIMARY_PARAGRAPH, url));

    if (overridable_) {
      load_time_data->SetBoolean("overridable", true);

      SSLErrorInfo error_info =
          SSLErrorInfo::CreateError(
              SSLErrorInfo::NetErrorToErrorType(cert_error_),
              ssl_info_.cert.get(),
              request_url());
      load_time_data->SetString("explanationParagraph", error_info.details());
      load_time_data->SetString(
          "primaryButtonText",
          l10n_util::GetStringUTF16(IDS_SSL_OVERRIDABLE_SAFETY_BUTTON));
      load_time_data->SetString(
          "finalParagraph",
          l10n_util::GetStringFUTF16(IDS_SSL_OVERRIDABLE_PROCEED_PARAGRAPH,
                                   url));
    } else {
      load_time_data->SetBoolean("overridable", false);

      SSLErrorInfo::ErrorType type =
          SSLErrorInfo::NetErrorToErrorType(cert_error_);
      if (type == SSLErrorInfo::CERT_INVALID && SSLErrorClassification::
          MaybeWindowsLacksSHA256Support()) {
        load_time_data->SetString(
            "explanationParagraph",
            l10n_util::GetStringFUTF16(
                IDS_SSL_NONOVERRIDABLE_MORE_INVALID_SP3, url));
      } else {
        load_time_data->SetString("explanationParagraph",
                                 l10n_util::GetStringFUTF16(
                                     IDS_SSL_NONOVERRIDABLE_MORE, url));
      }
      load_time_data->SetString(
          "primaryButtonText",
          l10n_util::GetStringUTF16(IDS_SSL_RELOAD));
      // Customize the help link depending on the specific error type.
      // Only mark as HSTS if none of the more specific error types apply,
      // and use INVALID as a fallback if no other string is appropriate.
      load_time_data->SetInteger("errorType", type);
      int help_string = IDS_SSL_NONOVERRIDABLE_INVALID;
      switch (type) {
        case SSLErrorInfo::CERT_REVOKED:
          help_string = IDS_SSL_NONOVERRIDABLE_REVOKED;
          break;
        case SSLErrorInfo::CERT_PINNED_KEY_MISSING:
          help_string = IDS_SSL_NONOVERRIDABLE_PINNED;
          break;
        case SSLErrorInfo::CERT_INVALID:
          help_string = IDS_SSL_NONOVERRIDABLE_INVALID;
          break;
        default:
          if (strict_enforcement_)
            help_string = IDS_SSL_NONOVERRIDABLE_HSTS;
      }
      load_time_data->SetString(
          "finalParagraph", l10n_util::GetStringFUTF16(help_string, url));
    }
  }

  // Set debugging information at the bottom of the warning.
  load_time_data->SetString(
      "subject", ssl_info_.cert->subject().GetDisplayName());
  load_time_data->SetString(
      "issuer", ssl_info_.cert->issuer().GetDisplayName());
  load_time_data->SetString(
      "expirationDate",
      base::TimeFormatShortDate(ssl_info_.cert->valid_expiry()));
  load_time_data->SetString(
      "currentDate", base::TimeFormatShortDate(time_triggered_));
  std::vector<std::string> encoded_chain;
  ssl_info_.cert->GetPEMEncodedChain(
      &encoded_chain);
  load_time_data->SetString(
      "pem", JoinString(encoded_chain, std::string()));
}

void SSLBlockingPage::OverrideEntry(NavigationEntry* entry) {
  int cert_id = content::CertStore::GetInstance()->StoreCert(
      ssl_info_.cert.get(), web_contents()->GetRenderProcessHost()->GetID());
  DCHECK(cert_id);

  entry->GetSSL().security_style =
      content::SECURITY_STYLE_AUTHENTICATION_BROKEN;
  entry->GetSSL().cert_id = cert_id;
  entry->GetSSL().cert_status = ssl_info_.cert_status;
  entry->GetSSL().security_bits = ssl_info_.security_bits;
}

// This handles the commands sent from the interstitial JavaScript.
// DO NOT reorder or change this logic without also changing the JavaScript!
void SSLBlockingPage::CommandReceived(const std::string& command) {
  int cmd = 0;
  bool retval = base::StringToInt(command, &cmd);
  DCHECK(retval);
  switch (cmd) {
    case CMD_DONT_PROCEED: {
      interstitial_page()->DontProceed();
      break;
    }
    case CMD_PROCEED: {
      if (danger_overridable_) {
        interstitial_page()->Proceed();
      }
      break;
    }
    case CMD_SHOW_MORE_SECTION: {
      metrics_helper_->RecordUserInteraction(
          SecurityInterstitialMetricsHelper::SHOW_ADVANCED);
      break;
    }
    case CMD_OPEN_HELP_CENTER: {
      metrics_helper_->RecordUserInteraction(
          SecurityInterstitialMetricsHelper::SHOW_LEARN_MORE);
      content::NavigationController::LoadURLParams help_page_params(
          google_util::AppendGoogleLocaleParam(
              GURL(kHelpURL), g_browser_process->GetApplicationLocale()));
      web_contents()->GetController().LoadURLWithParams(help_page_params);
      break;
    }
    case CMD_RELOAD: {
      metrics_helper_->RecordUserInteraction(
          SecurityInterstitialMetricsHelper::RELOAD);
      // The interstitial can't refresh itself.
      web_contents()->GetController().Reload(true);
      break;
    }
    case CMD_OPEN_DATE_SETTINGS: {
      metrics_helper_->RecordUserInteraction(
          SecurityInterstitialMetricsHelper::OPEN_TIME_SETTINGS);
      LaunchDateAndTimeSettings();
      break;
    }
    case CMD_OPEN_DIAGNOSTIC:
      // Google doesn't currently have a transparency report for SSL.
    case CMD_DO_REPORT:
    case CMD_DONT_REPORT:
    case CMD_OPEN_REPORTING_PRIVACY:
      // Chrome doesn't currently do Extended Reporting for SSL.
      NOTREACHED() << "Unexpected command: " << command;
  }
}

void SSLBlockingPage::OverrideRendererPrefs(
      content::RendererPreferences* prefs) {
  Profile* profile = Profile::FromBrowserContext(
      web_contents()->GetBrowserContext());
  renderer_preferences_util::UpdateFromSystemSettings(
      prefs, profile, web_contents());
}

void SSLBlockingPage::OnProceed() {
  metrics_helper_->RecordUserDecision(
      SecurityInterstitialMetricsHelper::PROCEED);
  RecordSSLExpirationPageEventState(
      expired_but_previously_allowed_, true, overridable_);
  // Accepting the certificate resumes the loading of the page.
  NotifyAllowCertificate();
}

void SSLBlockingPage::OnDontProceed() {
  metrics_helper_->RecordUserDecision(
      SecurityInterstitialMetricsHelper::DONT_PROCEED);
  RecordSSLExpirationPageEventState(
      expired_but_previously_allowed_, false, overridable_);
  NotifyDenyCertificate();
}

void SSLBlockingPage::NotifyDenyCertificate() {
  // It's possible that callback_ may not exist if the user clicks "Proceed"
  // followed by pressing the back button before the interstitial is hidden.
  // In that case the certificate will still be treated as allowed.
  if (callback_.is_null())
    return;

  callback_.Run(false);
  callback_.Reset();
}

void SSLBlockingPage::NotifyAllowCertificate() {
  DCHECK(!callback_.is_null());

  callback_.Run(true);
  callback_.Reset();
}

std::string SSLBlockingPage::GetUmaHistogramPrefix() const {
  switch (interstitial_reason_) {
    case SSL_REASON_SSL:
      if (overridable_)
        return "ssl_overridable";
      else
        return "ssl_nonoverridable";
    case SSL_REASON_BAD_CLOCK:
      return "bad_clock";
  }
  NOTREACHED();
  return std::string();
}

std::string SSLBlockingPage::GetSamplingEventName() const {
  std::string event_name(kEventNameBase);
  if (overridable_)
    event_name.append(kEventOverridable);
  else
    event_name.append(kEventNotOverridable);
  event_name.append(net::ErrorToString(cert_error_));
  return event_name;
}

// static
bool SSLBlockingPage::IsOptionsOverridable(int options_mask) {
  return (options_mask & SSLBlockingPage::OVERRIDABLE) &&
         !(options_mask & SSLBlockingPage::STRICT_ENFORCEMENT);
}


text:
import { Directive, ElementRef } from '@angular/core';

@Directive({
  selector: '[gridStackDirective]'
})
export class GridStackDirective {

  constructor(private el: ElementRef) {
  }

}


text:
/* jshint node: true */
'use strict';

const expect = require('chai').expect;
const fs = require('fs');
const path = require('path');
const Registry = require('ember-cli-preprocess-registry');
const HTMLBarsInlinePrecompilePlugin = require.resolve('babel-plugin-htmlbars-inline-precompile');
const hashForDep = require('hash-for-dep');
const pluginHashForDep = hashForDep(path.resolve(__dirname, './fixtures'));
const InlinePrecompile = require('../');
const defaultsDeep = require('ember-cli-lodash-subset').defaultsDeep;

describe('canParallelize()', function() {
  it('returns true for 0 plugins', function() {
    const pluginWrappers = [];
    expect(InlinePrecompile.canParallelize(pluginWrappers)).to.eql(true);
  });

  it('returns true for 1+ plugins with "parallelBabel" property', function() {
    const pluginWrappers1 = [
      { parallelBabel: 'something' }
    ];
    const pluginWrappers2 = [
      { parallelBabel: 'something' },
      { parallelBabel: 'something else' },
    ];
    expect(InlinePrecompile.canParallelize(pluginWrappers1)).to.eql(true);
    expect(InlinePrecompile.canParallelize(pluginWrappers2)).to.eql(true);
  });

  it('returns false for 1+ plugins without "parallelBabel" property', function() {
    const pluginWrappers1 = [
      { name: 'something' }
    ];
    const pluginWrappers2 = [
      { name: 'something' },
      { name: 'something else' },
    ];
    expect(InlinePrecompile.canParallelize(pluginWrappers1)).to.eql(false);
    expect(InlinePrecompile.canParallelize(pluginWrappers2)).to.eql(false);
  });

  it('returns false for mix of plugins with & without "parallelBabel" property', function() {
    const pluginWrappersMix = [
      { name: 'something', parallelBabel: 'ok' },
      { name: 'something else' },
    ];
    expect(InlinePrecompile.canParallelize(pluginWrappersMix)).to.eql(false);
  });
});

describe('getParallelConfig()', function() {
  it('returns the "parallelBabel" property of the plugins', function() {
    const pluginWrappers = [
      { parallelBabel: { requireFile: 'some/file' } },
      { parallelBabel: { requireFile: 'another/file' } },
    ];
    const expected = [
      { requireFile: 'some/file'},
      { requireFile: 'another/file' },
    ];
    expect(InlinePrecompile.getParallelConfig(pluginWrappers)).to.eql(expected);
  });
});

describe('included()', function() {
  let parent;
  let registry;
  let expectedRequireFilePath = path.resolve(__dirname, '../lib/require-from-worker');
  let expectedTemplateCompilerPath = path.resolve(__dirname, '../node_modules/ember-source/dist/ember-template-compiler.js');
  if (!fs.existsSync(expectedTemplateCompilerPath)) {
    expectedTemplateCompilerPath = path.resolve(__dirname, '../bower_components/ember/ember-template-compiler.js');
  }
  let templateCompilerContents = fs.readFileSync(`${expectedTemplateCompilerPath}`, { encoding: 'utf-8' });
  let testBaseDir = () => path.resolve(__dirname, '..');
  let FixtureBaseDir = () => path.resolve(__dirname, './fixtures');
  let configuredPlugins;
  let dependentParallelInfo = {
    requireFile: 'some/file/path',
    buildUsing: 'whatever',
    params: {}
  };
  let parallelPlugin = {
    name: 'some-parallel-plugin',
    plugin: 'some object',
    baseDir: FixtureBaseDir,
    parallelBabel: dependentParallelInfo,
  };
  let nonParallelPlugin = {
    name: 'some-regular-plugin',
    plugin: 'some object',
    baseDir: FixtureBaseDir,
  };
  let parallelBabelInfo0Plugin = {
    requireFile: expectedRequireFilePath,
    buildUsing: 'build',
    params: {
      templateCompilerPath: expectedTemplateCompilerPath,
      parallelConfig: []
    }
  };
  let parallelBabelInfo1Plugin = {
    requireFile: expectedRequireFilePath,
    buildUsing: 'build',
    params: {
      templateCompilerPath: expectedTemplateCompilerPath,
      parallelConfig: [ dependentParallelInfo ]
    }
  };

  beforeEach(function() {
    // mocks and settings for testing
    registry = new Registry();
    parent = { options: { babel: { plugins: [] } } };
    InlinePrecompile.setupPreprocessorRegistry('parent', registry);
    InlinePrecompile._super = {
      included: { apply() {} }
    };
    InlinePrecompile.project = {
      findAddonByName(addon) {
        return {
          'ember-cli-htmlbars': { inlinePrecompilerRegistered: false },
          'ember-source': { absolutePaths: { templateCompiler: expectedTemplateCompilerPath }},
        }[addon];
      },
      config() {
        return {
          'ember-cli-htmlbars': { templateCompilerPath: undefined }
        };
      },
      root: __dirname,
    };
    InlinePrecompile.parent = parent;
    InlinePrecompile._registeredWithBabel = false;
  });

  describe('0 plugins', function() {
    beforeEach(function() {
      // no plugins registered
      InlinePrecompile.included();
      configuredPlugins = parent.options.babel.plugins;
    });

    it('should have _parallelBabel object', function() {
      expect(configuredPlugins.length).to.eql(1);
      expect(typeof configuredPlugins[0]._parallelBabel).to.eql('object');
      let _parallelBabel = configuredPlugins[0]._parallelBabel;
      expect(_parallelBabel.requireFile).to.eql(expectedRequireFilePath);
      expect(_parallelBabel.buildUsing).to.eql('build');
      expect(typeof _parallelBabel.params).to.eql('object');
      expect(_parallelBabel.params.parallelConfig).to.eql([]);
      expect(_parallelBabel.params.templateCompilerPath).to.eql(expectedTemplateCompilerPath);
    });

    it('should have baseDir()', function() {
      expect(configuredPlugins.length).to.eql(1);
      expect(typeof configuredPlugins[0].baseDir).to.eql('function');
      expect(configuredPlugins[0].baseDir()).to.eql(testBaseDir());
    });

    it('should have cacheKey()', function() {
      let expectedCacheKey = [templateCompilerContents, JSON.stringify(parallelBabelInfo0Plugin)].join('|');
      expect(configuredPlugins.length).to.eql(1);
      expect(typeof configuredPlugins[0].cacheKey).to.eql('function');
      let cacheKey = configuredPlugins[0].cacheKey();
      expect(cacheKey.length).to.eql(expectedCacheKey.length, 'cacheKey is the correct length');
      expect(cacheKey).to.equal(expectedCacheKey);
    });
  });

  describe('1 parallel plugin', function() {
    beforeEach(function() {
      registry.add('htmlbars-ast-plugin', parallelPlugin);
      InlinePrecompile.included();
      configuredPlugins = parent.options.babel.plugins;
    });

    it('should have _parallelBabel object', function() {
      expect(configuredPlugins.length).to.eql(1);
      expect(typeof configuredPlugins[0]._parallelBabel).to.eql('object');
      let _parallelBabel = configuredPlugins[0]._parallelBabel;
      expect(_parallelBabel.requireFile).to.eql(expectedRequireFilePath);
      expect(_parallelBabel.buildUsing).to.eql('build');
      expect(typeof _parallelBabel.params).to.eql('object');
      expect(_parallelBabel.params.parallelConfig).to.eql([ dependentParallelInfo ]);
      expect(_parallelBabel.params.templateCompilerPath).to.eql(expectedTemplateCompilerPath);
    });

    it('should have baseDir()', function() {
      expect(configuredPlugins.length).to.eql(1);
      expect(typeof configuredPlugins[0].baseDir).to.eql('function');
      expect(configuredPlugins[0].baseDir()).to.eql(testBaseDir());
    });

    it('should have cacheKey()', function() {
      let expectedCacheKey = [templateCompilerContents, JSON.stringify(parallelBabelInfo1Plugin)].concat(pluginHashForDep).join('|');
      expect(configuredPlugins.length).to.eql(1);
      expect(typeof configuredPlugins[0].cacheKey).to.eql('function');
      let cacheKey = configuredPlugins[0].cacheKey();
      expect(cacheKey.length).to.eql(expectedCacheKey.length, 'cacheKey is the correct length');
      expect(cacheKey).to.equal(expectedCacheKey);
    });
  });

  describe('1 non-parallel plugin', function() {
    beforeEach(function() {
      registry.add('htmlbars-ast-plugin', nonParallelPlugin);
      InlinePrecompile.included();
      configuredPlugins = parent.options.babel.plugins;
    });

    it('should not have _parallelBabel object', function() {
      expect(configuredPlugins.length).to.eql(1);
      expect(configuredPlugins[0]._parallelBabel).to.eql(undefined);
    });

    it('should have plugin object', function() {
      let expectedCacheKey = [templateCompilerContents].concat([pluginHashForDep]).join('|');
      expect(Array.isArray(configuredPlugins[0])).to.eql(true);
      expect(configuredPlugins[0].length).to.eql(2);
      let pluginObject = configuredPlugins[0][0];
      expect(pluginObject).to.eql(HTMLBarsInlinePrecompilePlugin);
      let pluginParams = configuredPlugins[0][1];
      expect(typeof pluginParams.precompile).to.eql('function');
      expect(typeof pluginParams.precompile.baseDir).to.eql('function');
      expect(pluginParams.precompile.baseDir()).to.eql(testBaseDir());
      expect(typeof pluginParams.precompile.cacheKey).to.eql('function');
      let cacheKey = pluginParams.precompile.cacheKey();
      expect(cacheKey.length).to.equal(expectedCacheKey.length);
      expect(cacheKey).to.equal(expectedCacheKey);
    });
  });

  describe('mix of parallel & non-parallel plugins', function() {
    beforeEach(function() {
      registry.add('htmlbars-ast-plugin', parallelPlugin);
      registry.add('htmlbars-ast-plugin', nonParallelPlugin);
      InlinePrecompile.included();
      configuredPlugins = parent.options.babel.plugins;
    });

    it('should not have _parallelBabel object', function() {
      expect(configuredPlugins.length).to.eql(1);
      expect(configuredPlugins[0]._parallelBabel).to.eql(undefined);
    });

    it('should have plugin object', function() {
      let expectedCacheKey = [templateCompilerContents].concat([pluginHashForDep, pluginHashForDep]).join('|');
      expect(Array.isArray(configuredPlugins[0])).to.eql(true);
      expect(configuredPlugins[0].length).to.eql(2);
      let pluginObject = configuredPlugins[0][0];
      expect(pluginObject).to.eql(HTMLBarsInlinePrecompilePlugin);
      let pluginParams = configuredPlugins[0][1];
      expect(typeof pluginParams.precompile).to.eql('function');
      expect(typeof pluginParams.precompile.baseDir).to.eql('function');
      expect(pluginParams.precompile.baseDir()).to.eql(testBaseDir());
      expect(typeof pluginParams.precompile.cacheKey).to.eql('function');
      let cacheKey = pluginParams.precompile.cacheKey();
      expect(cacheKey.length).to.equal(expectedCacheKey.length);
      expect(cacheKey).to.equal(expectedCacheKey);
    });
  });

  describe('different instances of inline precompile for the same parent', function() {
    it('should have only 1 inlinePrecompile registered for parallel babel', function() {
      let InlinePrecompile1  = defaultsDeep( {}, require('../'))
      let InlinePrecompile2  = defaultsDeep( {}, require('../'))
      parent = { options: { babel: { plugins: [] } } };
      InlinePrecompile1.parent = parent;
      InlinePrecompile2.parent = parent;

      InlinePrecompile1.included();
      configuredPlugins = parent.options.babel.plugins;
      expect(configuredPlugins.length).to.eql(1);
      InlinePrecompile2.included();
      configuredPlugins = parent.options.babel.plugins;
      expect(configuredPlugins.length).to.eql(1);
    });

    it('should have only 1 inlinePrecompile registered for non parallel babel', function() {
      registry.add('htmlbars-ast-plugin', nonParallelPlugin);
      let InlinePrecompile1  = defaultsDeep( {}, require('../'))
      let InlinePrecompile2  = defaultsDeep( {}, require('../'))
      parent = { options: { babel: { plugins: [] } } };
      InlinePrecompile1.parent = parent;
      InlinePrecompile2.parent = parent;

      InlinePrecompile1.included();
      configuredPlugins = parent.options.babel.plugins;
      expect(configuredPlugins.length).to.eql(1);
      InlinePrecompile2.included();
      configuredPlugins = parent.options.babel.plugins;
      expect(configuredPlugins.length).to.eql(1);
    });

  });
});


text:
'use strict';
require('../common');
const assert = require('assert');
const child_process = require('child_process');

const p = child_process.spawn(process.execPath, [
  '-e',
  'vm = require("vm");' +
      'context = vm.createContext({});' +
      'try { vm.runInContext("throw new Error(\'boo\')", context); } ' +
      'catch (e) { console.log(e.message); }'
]);

p.stderr.on('data', function(data) {
  assert.fail(`Unexpected stderr data: ${data}`);
});

let output = '';

p.stdout.on('data', function(data) {
  output += data;
});

process.on('exit', function() {
  assert.strictEqual(output.replace(/[\r\n]+/g, ''), 'boo');
});


text:
<?php

namespace Sylius\Bundle\FixturesBundle\DataFixtures\ORM;

use Doctrine\Common\Persistence\ObjectManager;
use Sylius\Bundle\FixturesBundle\DataFixtures\DataFixture;
use Sylius\Component\Addressing\Model\CountryInterface;
use Symfony\Component\Intl\Intl;

/**
 * Default country fixtures.
 *
 * @author Paweł Jędrzejewski <pawel@sylius.org>
 */
class LoadCountriesData extends DataFixture
{
    private $states = array(
        'AL' => 'Alabama',
        'AK' => 'Alaska',
        'AZ' => 'Arizona',
        'AR' => 'Arkansas',
        'CA' => 'California',
        'CO' => 'Colorado',
        'CT' => 'Connecticut',
        'DE' => 'Delaware',
        'DC' => 'District Of Columbia',
        'FL' => 'Florida',
        'GA' => 'Georgia',
        'HI' => 'Hawaii',
        'ID' => 'Idaho',
        'IL' => 'Illinois',
        'IN' => 'Indiana',
        'IA' => 'Iowa',
        'KS' => 'Kansas',
        'KY' => 'Kentucky',
        'LA' => 'Louisiana',
        'ME' => 'Maine',
        'MD' => 'Maryland',
        'MA' => 'Massachusetts',
        'MI' => 'Michigan',
        'MN' => 'Minnesota',
        'MS' => 'Mississippi',
        'MO' => 'Missouri',
        'MT' => 'Montana',
        'NE' => 'Nebraska',
        'NV' => 'Nevada',
        'NH' => 'New Hampshire',
        'NJ' => 'New Jersey',
        'NM' => 'New Mexico',
        'NY' => 'New York',
        'NC' => 'North Carolina',
        'ND' => 'North Dakota',
        'OH' => 'Ohio',
        'OK' => 'Oklahoma',
        'OR' => 'Oregon',
        'PA' => 'Pennsylvania',
        'RI' => 'Rhode Island',
        'SC' => 'South Carolina',
        'SD' => 'South Dakota',
        'TN' => 'Tennessee',
        'TX' => 'Texas',
        'UT' => 'Utah',
        'VT' => 'Vermont',
        'VA' => 'Virginia',
        'WA' => 'Washington',
        'WV' => 'West Virginia',
        'WI' => 'Wisconsin',
        'WY' => 'Wyoming'
    );

    /**
     * {@inheritdoc}
     */
    public function load(ObjectManager $manager)
    {
        $countryRepository = $this->getCountryRepository();
        $countries = Intl::getRegionBundle()->getCountryNames($this->defaultLocale);

        if (Intl::isExtensionLoaded()) {
            $localisedCountries = array('es_ES' => Intl::getRegionBundle()->getCountryNames('es_ES'));
        } else {
            $localisedCountries = array();
        }

        foreach ($countries as $isoName => $name) {
            $country = $countryRepository->createNew();

            $country->setCurrentLocale($this->defaultLocale);
            $country->setName($name);

            foreach ($localisedCountries as $locale => $translatedCountries) {
                $country->setCurrentLocale($locale);
                $country->setName($translatedCountries[$isoName]);
            }

            $country->setIsoName($isoName);

            if ('US' === $isoName) {
                $this->addUsStates($country);
            }

            $manager->persist($country);

            $this->setReference('Sylius.Country.'.$isoName, $country);
        }

        $manager->flush();
    }

    /**
     * {@inheritdoc}
     */
    public function getOrder()
    {
        return 1;
    }

    /**
     * Adds all US states as provinces to given country.
     *
     * @param CountryInterface $country
     */
    protected function addUsStates(CountryInterface $country)
    {
        $provinceRepository = $this->getProvinceRepository();

        foreach ($this->states as $isoName => $name) {
            $province = $provinceRepository->createNew()
                ->setName($name)
                ->setIsoName($isoName)
            ;
            $country->addProvince($province);

            $this->setReference('Sylius.Province.'.$isoName, $province);
        }
    }
}


text:
from rest_framework import permissions
from rest_framework.permissions import BasePermission
from django.core.exceptions import ObjectDoesNotExist
from django.contrib.auth.models import Group

def group_owner(request):
    group_name = request.resolver_match.kwargs.get('group_name')

    try:
        group = Group.objects.get(name=group_name)
    except ObjectDoesNotExist:
        pass
    else:
        if request.user == group.groupmeta.owner:
            return True

    return False

def group_admin(request):
    group_name = request.resolver_match.kwargs.get('group_name')

    try:
        group = Group.objects.get(name=group_name)
    except ObjectDoesNotExist:
        pass
    else:
        if request.user == group.groupmeta.owner:
            return True
        elif request.user in group.groupmeta.admins.all():
            return True

    return False

def group_member(request):
    group_name = request.resolver_match.kwargs.get('group_name')

    if request.user.groups.filter(name=group_name).exists():
        return True

    return False

class IsGroupMember(BasePermission):

    def has_permission(self, request, view):
        return group_member(request)

class IsGroupMemberOrPublicReadOnly(BasePermission):

    def has_permission(self, request, view):
        if group_member(request):
            return True
        elif request.method in permissions.SAFE_METHODS:
            return True

        return False

class IsGroupAdmin(BasePermission):

    def has_permission(self, request, view):
        if group_member(request) and group_admin(request):
            return True

        return False

class IsGroupAdminOrMemberReadOnly(BasePermission):

    def has_permission(self, request, view):
        if group_member(request):
            if group_admin(request):
                return True
            elif request.method in permissions.SAFE_METHODS:
                return True

        return False

class IsGroupAdminOrMemberAddMethod(BasePermission):

    def has_permission(self, request, view):
        if group_member(request):
            if group_admin(request):
                return True
            elif request.method == 'POST':
                return True

        return False

class IsGroupOwner(BasePermission):

    def has_permission(self, request, view):
        if group_member(request) and group_owner(request):
            return True

        return False

class IsGroupOwnerOrMemberReadOnly(BasePermission):

    def has_permission(self, request, view):
        if group_member(request):
            if group_owner(request):
                return True
            elif request.method in permissions.SAFE_METHODS:
                return True

        return False

class IsGroupOwnerOrPublicReadOnly(BasePermission):

    def has_permission(self, request, view):
        if group_member(request) and group_owner(request):
            return True
        elif request.method in permissions.SAFE_METHODS:
            return True

        return False


text:
'use strict';

var AMQPError = require('./amqp_error'),
    DeliveryStates = require('./delivery_state'),
    Source = require('./source_target').Source,
    Target = require('./source_target').Target,
    Message = require('./message');

var knownTypes = [
  AMQPError, Source, Target, DeliveryStates.Accepted,
  DeliveryStates.Received, DeliveryStates.Rejected, DeliveryStates.Released,
  Message.Header, Message.DeliveryAnnotations, Message.Annotations,
  Message.Properties, Message.ApplicationProperties, Message.Footer,
  Message.Data, Message.AMQPSequence, Message.AMQPValue
];

function convertType(describedType) {
  var descriptorStr = describedType.descriptor.toString();
  var _len = knownTypes.length;
  for (var _i = 0; _i < _len; ++_i) {
    if (knownTypes[_i].prototype.Descriptor.name.toString() === descriptorStr ||
        knownTypes[_i].prototype.Descriptor.code.toString() === descriptorStr) {
      return knownTypes[_i].fromDescribedType(describedType);
    }
  }

  return undefined;
}

module.exports = convertType;


text:
package org.swellrt.beta.client.platform.web.editor.caret.view;

import org.swellrt.beta.client.platform.web.editor.caret.CaretView;
import org.swellrt.beta.client.platform.web.editor.caret.CaretViewFactory;

public final class LegacyCaretViewFactory implements CaretViewFactory {

  public static final LegacyCaretViewFactory instance = new LegacyCaretViewFactory();

  @Override
  public CaretView exec() {
    return new LegacyCaretView();
  }

}


text:
require 'pry'
module SupportEngine
  module Api
    module V1
      class TicketsController < ApiController
        before_filter :validate_captcha, only: :create
        respond_to :json

        def create

          ticket = Ticket.new(params[:ticket])
          ticket.state = TicketStates.open
          ticket.priority = TicketPriority.normal

          if ticket.save
            render json: { ticket: ticket, message: t("support_engine.widget.message") },
                   status: :created, location: api_v1_ticket_url(ticket)
          else
            render json: ticket.errors, status: :unprocessable_entity
          end
        end

        def index
          if params[:q].present?
            query = params[:q].split(" ").join("%")
            tickets = Ticket.where("title LIKE ?", "%#{query}%")
          else
            tickets = Ticket
          end

          ticket = ticket.offset(10*params[:p].to_i) if params[:p].to_i > 0

          render json: { tickets: tickets.limit(10) }
        end

        def validate_captcha
          if params[:confirmation].present?
            render json: { captcha: "Error" }, status: :unprocessable_entity
            return
          end
        end
      end
    end
  end
end


text:
package com.jakewharton.rxbinding.widget;

import android.widget.SearchView;
import rx.Observable;
import rx.Subscriber;
import rx.android.MainThreadSubscription;

import static rx.android.MainThreadSubscription.verifyMainThread;

final class SearchViewQueryTextChangeEventsOnSubscribe
    implements Observable.OnSubscribe<SearchViewQueryTextEvent> {
  final SearchView view;

  SearchViewQueryTextChangeEventsOnSubscribe(SearchView view) {
    this.view = view;
  }

  @Override public void call(final Subscriber<? super SearchViewQueryTextEvent> subscriber) {
    verifyMainThread();

    SearchView.OnQueryTextListener watcher = new SearchView.OnQueryTextListener() {
      @Override public boolean onQueryTextChange(String s) {
        if (!subscriber.isUnsubscribed()) {
          subscriber.onNext(SearchViewQueryTextEvent.create(view, s, false));
          return true;
        }
        return false;
      }

      @Override public boolean onQueryTextSubmit(String query) {
        if (!subscriber.isUnsubscribed()) {
          subscriber.onNext(SearchViewQueryTextEvent.create(view, view.getQuery(), true));
          return true;
        }
        return false;
      }
    };

    view.setOnQueryTextListener(watcher);

    subscriber.add(new MainThreadSubscription() {
      @Override protected void onUnsubscribe() {
        view.setOnQueryTextListener(null);
      }
    });

    // Emit initial value.
    subscriber.onNext(SearchViewQueryTextEvent.create(view, view.getQuery(), false));
  }
}


text:
package main

import "github.com/fiorix/freegeoip/apiserver"

func main() {
	apiserver.Run()
}


text:
package org.apache.beam.runners.spark;

import org.apache.beam.sdk.annotations.Experimental;
import org.apache.beam.sdk.options.Default;
import org.apache.beam.sdk.options.Description;
import org.apache.beam.sdk.options.PortablePipelineOptions;

/** Pipeline options specific to the Spark portable runner running a streaming job. */
@Experimental
public interface SparkPortableStreamingPipelineOptions
    extends SparkPipelineOptions, PortablePipelineOptions {
  @Description(
      "Timeout for Spark portable streaming, in milliseconds."
          + "Default (-1L) is infinity, i.e. no timeout.")
  @Default.Long(-1L)
  Long getStreamingTimeoutMs();

  void setStreamingTimeoutMs(Long value);
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Crocodile Real-Time Communications Library Test Suite</title>

  <link rel="stylesheet" href="../libs/qunit/qunit.css" media="screen">

    lame test markup
    normal test markup
    awesome test markup


text:
import types
import itkBase

not_loaded = 'not loaded'

class LazyITKModule(types.ModuleType):

    """Subclass of ModuleType that implements a custom __getattribute__ method
    to allow lazy-loading of attributes from ITK sub-modules."""

    def __init__(self, name, lazy_attributes):
        types.ModuleType.__init__(self, name)
        for k, v in lazy_attributes.items():
            itkBase.lazy_attributes.setdefault(k,set()).update(v)
        self.__belong_lazy_attributes = dict( (k,v[0]) for k,v in lazy_attributes.items() if len(v) > 0 )
        for k in lazy_attributes:
            setattr(self, k, not_loaded)

    def __getattribute__(self, attr):
        value = types.ModuleType.__getattribute__(self, attr)
        if value is not_loaded:
            module = self.__belong_lazy_attributes[attr]
            namespace = {}
            itkBase.LoadModule(module, namespace)
            for k, v in namespace.items():
                setattr(self, k, v)
            value = namespace[attr]
        return value