text:
var YouTyping = function (element, settings) {
	var youTyping = this;
	var screen = settings.screen;

	/******************* properties *******************/

	this.noteState = {
		WAITING: 0,
		HITTING: 1,
		CLEARED: 2,
		HITTINGFAILED: 3,
		FAILED: 4
	};

	this.itemType = {
		LINE: 0,
		LONGLINE: 1,
		NOTE: 2,
		LYRIC: 3,
		STOP: 4
	};

	// default settings
	this.settings = {
		zeroEstimateSamples: 16, // integer
		videoId: 'fQ_m5VLhqNg',
		dataFile: 'data.utx',
		tableFile: 'convert/romaji.xml',
		width: 1120, // pixel
		height: 630, // pixel
		judges: [ // millisecond
		{
			name: 'perfect',
			from: -50,
			to: 50,
			weight: 1.0
		},
		{
			name: 'great',
			from: -70,
			to: 70,
			weight: 0.5
		},
		{
			name: 'good',
			from: -100,
			to: 100,
			weight: 0.25
		},
		{
			name: 'bad',
			from: -Infinity,
			to: 150,
			weight: 0.0
		}
		],
		breakCombo: 'bad', // judgement name
		failureSuspension: 100, // millisecond
		initial: false, // boolean
		mercy: true, // boolean
		mercyBorder: 13.5, // stroke per second
		correction: 0, // millisecond
		controlledCorrection: 0, // millisecond
		offset: 0, // second
		videoStop: 0, // second
		volume: 100, // percent
		playbackQuality: 'default' // string
	};

	// override default settings
	for (var param in settings) {
		if (settings.hasOwnProperty(param)) {
			if (this.settings[param] === undefined) {
				this.settings[param] = settings[param];
			} else if (typeof this.settings[param] === 'number') {
				this.settings[param] = parseFloat(settings[param], 10);
			} else if (typeof this.settings[param] === 'string') {
				this.settings[param] = settings[param];
			} else if (typeof this.settings[param] === 'boolean') {
				this.settings[param] = Boolean(settings[param]);
			}
		}
	}

	// roll data
	this.dataXML = null;
	this.roll = null;

	// YouTube Iframe Player
	this.player = null;

	// YouTyping.now
	Object.defineProperty(this, 'now', {
		get: function () {
			// note: this is most frequently called property in YouTyping.
			// In chrome, Date.now is faster than performance.now,
			// but Firefox is not.
			// Came from http://jsperf.com/new-date-vs-date-now-vs-performance-now/21
			return window.performance.now();
		}
	});

	// key-input conversion table
	this.table = [];

	/******************* Internal variables *******************/

	var gameEndFlag = false;

	/******************* Internal functions *******************/

	var setupPlayerDeferred;
	var setupPlayer = function (callback) {
		setupPlayerDeferred = $.Deferred();
		logTrace('Setting Player Up...');

		var APITag = document.createElement('script');
		APITag.src = 'https://www.youtube.com/iframe_api';
		var firstScript = document.getElementsByTagName('script')[0];
		firstScript.parentNode.insertBefore(APITag, firstScript);

		return setupPlayerDeferred.promise();
	};

	// callback function used by YouTube IFrame Player API. must be global
	window.onYouTubeIframeAPIReady = function () {
		var settings = youTyping.settings;

		logTrace('Player API is Ready.');

		// try to hide advertisement if sandbox parameter is 'true' or not defined in URI query
		if (getParameterByName('sandbox') === 'true') {
			this.DOM.player.setAttribute('sandbox', 'allow-same-origin allow-scripts');
		}

		youTyping.player = new YT.Player('youtyping-player', {
			height: settings.height,
			width: settings.width,
			videoId: settings.videoId,
			playerVars: {
				rel: 0,
				start: settings.offset,
				// Wishing the best effort of hiding any information except for the video
				controls: 0,
				showinfo: 0,
				modestbranding: 1,
				// thanks http://stackoverflow.com/questions/6826386/
				wmode: 'opaque'
			},
			events: {
				onReady: onPlayerReady,
				onStateChange: onPlayerStateChange,
				onError: onPlayerError
			}
		});
	};

	var onPlayerReady = function (event) {
		logTrace('Player is Ready.');

		youTyping.player.setVolume(youTyping.settings.volume);
		youTyping.player.setPlaybackQuality(youTyping.settings.playbackQuality);
		// play and immediately pause video to make playerState unstarted or paused.
		// this is required to make video seekable even in inactive.
		youTyping.player.playVideo();
		youTyping.player.pauseVideo();

		setupPlayerDeferred.resolve();
	};

	var onPlayerStateChange = function (event) {
		youTyping.dispatchEvent('playerstatechange', event);

		switch (event.data) {
		case YT.PlayerState.ENDED:
			logTrace('Player Ended.');
			break;
		case YT.PlayerState.PLAYING:
			logTrace('Player Started.');
			// reset zero time samples
			if (youTyping.isPlayingGame) {
				youTyping.estimateSamples = [];
			}
			break;
		case YT.PlayerState.PAUSED:
			logTrace('Player Paused.');
			break;
		case YT.PlayerState.BUFFERING:
			logTrace('Player Buffering.');
			break;
		case YT.PlayerState.CUED:
			logTrace('Player Cued.');
			break;
		}
	};

	var onPlayerError = function (event) {
		// from https://developers.google.com/youtube/iframe_api_reference
		switch (event.data) {
		case 2:
			logTrace(
'ERROR: The request contains an invalid parameter value.\
 For example, this error occurs if you specify a video ID that does not have 11 characters,\
 or if the video ID contains invalid characters,\
 such as exclamation points or asterisks.');
			break;
		case 5:
			logTrace(
'ERROR: The requested content cannot be played in an HTML5 player\
 or another error related to the HTML5 player has occurred.');
			break;
		case 100:
			logTrace(
'ERROR: The video requested was not found.\
 This error occurs when a video has been removed (for any reason)\
 or has been marked as private.');
			break;
		case 101:
			logTrace(
'ERROR: The owner of the requested video does not allow it\
 to be played in embedded players.');
			break;
		case 150:
			logTrace(
'ERROR: The owner of the requested video does not allow it\
 to be played in embedded players.');
			break;
		}
		setupPlayerDeferred.reject();
	};

	var loadXMLDeferred;
	var loadDataXML = function () {
		// Initialize deferred
		loadXMLDeferred = $.Deferred();

		$.ajax({
			url: youTyping.settings.dataFile,
			type: 'get',
			datatype: 'xml',
			timeout: 10000,
			success: function (data, textStatus, jqXHR) {
				youTyping.dataXML = $(data).find('data').first();

				initializeRoll();

				logTrace('Loaded XML File.');

				loadXMLDeferred.resolve();
			},
			error: function (jqXHR, textStatus, errorThrown) {
				logTrace('ERROR: XML File Loading Failed: ' + errorThrown);
				loadXMLDeferred.reject();
			}
		});

		return loadXMLDeferred.promise();
	};

	// initialize roll data for when loading and resetting
	var initializeRoll = function () {
		var items = youTyping.dataXML.find('roll > item');

		// parse XML and store into YouTyping.roll
		youTyping.roll = [];

		var lastNote = null;
		var virtualCombo = 0;
		var previousNote = null;

		$(items).each(function () {
			var tempItem = {
				// convert to millisecond
				time: parseFloat($(this).attr('time')) * 1000,
				type: $(this).attr('type').mapsTo({
					line: youTyping.itemType.LINE,
					longline: youTyping.itemType.LONGLINE,
					note: youTyping.itemType.NOTE,
					lyric: youTyping.itemType.LYRIC,
					stop: youTyping.itemType.STOP
				}),
				romaji: '',
				remainingRomaji: '',
				receivedRomaji: ''
			};

			if (tempItem.type === null) {
				logTrace('ERROR: Unknown item type ' + $(this).attr('type'));
				loadXMLDeferred.reject();
				return;
			}

			if ($(this).has('text')) {
				         tempItem.text =
				tempItem.remainingText = $(this).children('text').text();
			}

			// calculate time to the next note
			if (previousNote !== null && (
					tempItem.type === youTyping.itemType.NOTE
					|| tempItem.type === youTyping.itemType.STOP
				)
			) {
				previousNote.duration = tempItem.time - previousNote.time;
			}

			if (tempItem.type === youTyping.itemType.NOTE) {
				tempItem.state = youTyping.noteState.WAITING;
				tempItem.judgement = null;
				lastNote = tempItem;

				if (virtualCombo < 50) {
					virtualCombo++;
				}

				youTyping.totalCombo += virtualCombo;

				previousNote = tempItem;
			}

			if (tempItem.type === youTyping.itemType.STOP) {
				previousNote = null;
			}

			youTyping.roll.push(tempItem);
		});

		youTyping.lastNote = lastNote;

		youTyping.nextLyricIndex = findNextLyric(-1);
	};

	var loadTableDeferred;
	var loadTable = function () {
		// initialize deferred
		loadTableDeferred = $.Deferred();

		$.ajax({
			url: youTyping.settings.tableFile,
			type: 'get',
			datatype: 'xml',
			timeout: 10000,
			success: function (data, textStatus, jqXHR) {
				try {
					youTyping.table = [];

					$(data).find('table').find('rule').each(function (index) {
						youTyping.table.push({
							before: $(this).attr('before'),
							after: $(this).attr('after'),
							next: $(this).attr('next') || '',
							priority: $(this).attr('priority') || 0,
							strokePerCharacter:
								$(this).attr('next') ?
								($(this).attr('before').length - 1) / $(this).attr('after').length :
								$(this).attr('before').length / $(this).attr('after').length
						});

						if ($(this).attr('next')) {
							if ($(this).attr('next').length !== 1) {
								throw 'Rule ' + index + ': next string must be one character';
							}
						}
					});

					// romanization prefers rules by following priorities order:
					// 1. priority is high
					// 2. 'after' string is long
					// 3. strokes per character is short

					// table clone and sort
					youTyping.romanizationTable = $.extend(true, [], youTyping.table);
					youTyping.romanizationTable.sort(function (a, b) {
						if (a.priority !== b.priority) {
							return b.priority - a.priority;
						} else if (a.after.length !== b.after.length) {
							return b.after.length - a.after.length;
						} else if (a.strokePerCharacter !== b.strokePerCharacter) {
							return a.strokePerCharacter - b.strokePerCharacter;
						} else {
							return 0;
						}
					});

					logTrace('Loaded Table File.');
				} catch (error) {
					logTrace('ERROR: Table File Parsing Failed: ' + error);
					loadTableDeferred.reject();
					return;
				}

				loadTableDeferred.resolve();
			},
			error: function (jqXHR, textStatus, errorThrown) {
				logTrace('ERROR: Table File Loading Failed: ' + errorThrown);
				loadTableDeferred.reject();
			}
		});

		return loadTableDeferred.promise();
	};

	// evaluate weight of each notes and compute scores of each notes
	var calculateWeight = function () {
		var firstNote = true;
		var totalWeight = 0;
		youTyping.roll.forEach(function (item, index) {
			// romanize
			if (item.type === youTyping.itemType.LYRIC) {
				firstNote = true;
			} else if (item.type === youTyping.itemType.NOTE && firstNote) {
				var result = romanizeNotes(index, item.text, '');

				if (result === false) {
					throw new Error('Note ' + item.text + ' cannot be romanized');
				}

				firstNote = false;
			}

			if (item.type === youTyping.itemType.NOTE) {
				// calculate and sum weights
				item.weight = item.romaji.length;

				// duplicate romaji
				item.remainingRomaji = item.romaji;

				// calculate density
				item.density = item.romaji.length / item.duration * 1000;

				if (youTyping.settings.mercy && item.density >= youTyping.settings.mercyBorder) {
					item.mercy = Math.floor(youTyping.settings.mercyBorder * item.duration / 1000);

					if (item.mercy === item.romaji.length) {
						item.mercy--;
					}

					if (item.mercy === 0) {
						if (item.romaji.length === 1) {
							item.mercy = false;
						} else {
							item.mercy = 1;
						}
					}
				} else {
					item.mercy = false;
				}

				if (item.mercy !== false) {
					item.weight = item.mercy;
				}

				totalWeight += item.weight;
			}
		});

		youTyping.totalWeight = totalWeight;
	};

	// romanize notes from specified index to lyric end
	// @param prefix: limit romanization to start with specified characters
	// if romanization succeeded and note.text is fully satisfied, this returns true.
	// if romanization failed, this returns false.
	// if romanization succeeded but text remains, this returns currently converted
	// romaji at all.
	var romanizeNotes = function (index, remainingString, prefix) {
		var note = youTyping.roll[index];

		assert(note.type === youTyping.itemType.NOTE);

		// inspection
		var leftString = '';
		var result;
		var found = youTyping.romanizationTable.some(function (rule) {
			if (
				startsWith(remainingString, rule.after) && (
					!prefix
					|| startsWith(rule.before, prefix)
					|| startsWith(prefix, rule.before)
				)
			) {
				var followingString = remainingString.slice(rule.after.length);

				var remainingPrefix;
				if (!prefix) {
					remainingPrefix = rule.before;
				} else if (rule.before.length >= prefix.length) {
					remainingPrefix = rule.before;
				} else {
					remainingPrefix = prefix;
				}
				remainingPrefix = remainingPrefix.slice(rule.before.length - rule.next.length);

				// if text doesn't remains
				if (followingString === '') {
					var nextNoteIndex = findNextNote(index);

					// if next note doesn't exist
					if (nextNoteIndex === null) {
						// if prefix remains, it can never be satisfied.
						if (remainingPrefix) {
							return false;
						} else {
							// if note is satisfied
							if (remainingString === note.text) {
								note.romaji = rule.before.slice(0, rule.next ? -1 : undefined);
								note.remainingRomaji = note.romaji;
							} else {
								leftString = rule.before.slice(0, rule.next ? -1 : undefined);
							}
							return true;
						}
					}
					// if next note exists
					else {
						var nextNote = youTyping.roll[nextNoteIndex];
						result = romanizeNotes(nextNoteIndex, nextNote.text, remainingPrefix);

						// note must be satisfied or failed
						assert(typeof result === 'boolean');

						if (result) {
							// if note is satisfied
							if (remainingString === note.text) {
								note.romaji = rule.before.slice(0, rule.next ? -1 : undefined);
								note.remainingRomaji = note.romaji;
							} else {
								leftString = rule.before.slice(0, rule.next ? -1 : undefined);
							}
							return true;
						} else {
							return false;
						}
					}
				}
				// if text remains
				else {
					result = romanizeNotes(index, followingString, remainingPrefix);

					// result mustn't be satisfied
					assert(result !== true);

					// if romanization failed
					if (result === false) {
						return false;
					}
					// if note is satisfied
					else if (remainingString === note.text) {
						note.romaji = rule.before.slice(0, rule.next ? -1 : undefined) + result;
						note.remainingRomaji = note.romaji;
					}
					// if note isn't satisfied
					else {
						leftString = rule.before.slice(0, rule.next ? -1 : undefined) + result;
					}

					return true;
				}
			} else {
				return false;
			}
		});

		if (!found) {
			return false;
		} else {
			if (leftString) {
				return leftString;
			} else {
				return true;
			}
		}
	};

	// return next valid note
	var findNextNote = function (noteIndex) {
		var nextNote = null;

		for (var i = noteIndex + 1; i < youTyping.roll.length; i++) {
			var item = youTyping.roll[i];
			if (item.type === youTyping.itemType.STOP) {
				nextNote = null;
				break;
			}
			if (item.type === youTyping.itemType.NOTE) {
				nextNote = i;
				break;
			}
		}

		return nextNote;
	};

	// return next lyric
	var findNextLyric = function (itemIndex) {
		var nextLyric = null;

		for (var i = itemIndex + 1; i < youTyping.roll.length; i++) {
			var item = youTyping.roll[i];
			if (item.type === youTyping.itemType.LYRIC) {
				nextLyric = i;
				break;
			}
		}

		return nextLyric;
	};

	// game loop
	var gameLoop = function () {
		// calculate `ZeroTime`

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

		# What's `ZeroTime` and `ZeroCall`?

		The current time taken from YouTube API by `getCurrentTime()`
		is resoluted very roughly (about 0.2s) with a great range of errors (about 0.05s).

		It's so fatal for music game like YouTyping. So we introduced idea that calibrates
		correct playing time by taking average of measuring. That's `ZeroTime`.

		YouTyping loops to get current playing time from API (to `gotCurrentTime`)
		with enough interval time (10ms) to detect when the `getCurrentTime()` time
		jumped up to another value. And each time `gotCurrentTime` jumped (nameed `ZeroCall`),
		YouTyping assumes the time to be correct and counts backward to estimate
		when this video started, so the time is nameed `ZeroTime`. Then the current playing time
		of video will be calculated by `ZeroTime` and current time taken from browser clock
		(very highly resoluted as <1ms).

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

		var now = youTyping.now;
		var gotCurrentTime = youTyping.player.getCurrentTime();
		var gotPlayerState = youTyping.player.getPlayerState();

		if (gotPlayerState === YT.PlayerState.PLAYING) {
			if (youTyping.currentTime !== gotCurrentTime
			    && gotCurrentTime > youTyping.settings.offset) { // if Current Time jumped
				youTyping.currentTime = gotCurrentTime;
				youTyping.estimatedZero = now - youTyping.currentTime * 1000;

				// Estimated zero time is stored in estimatesamples and
				// we assume that correct zero time is average of recent
				// `zeroEstimateSamples` items of samples
				// because it contains great ranges of error.
				// We also introduced `zeroTimePad` to supress a sudden change of zeroTime.
				// It contains correct zero time and sudden-change-supressed zero time
				// will be stored in `zeroTime`.
				youTyping.estimateSamples.push(youTyping.estimatedZero);
				if (youTyping.estimateSamples.length > youTyping.settings.zeroEstimateSamples) {
					youTyping.estimateSamples.shift();
				}
				// just go hack :)
				var estimatedSum = youTyping.estimateSamples.reduce(function (previous, current) {
					return previous + current;
				});

				// `zeroTimePad` is actual estimated ZeroTime and real displayed ZeroTime is
				// modested into `zeroTime`.
				youTyping.zeroTimePad = estimatedSum / youTyping.estimateSamples.length
				                        + youTyping.correction;

				// stop video when the time exceeded
				if (youTyping.settings.videoStop !== 0
				    && gotCurrentTime > youTyping.settings.videoStop) {
					youTyping.player.stopVideo();
				}

				youTyping.zeroCallFPS++;
			}
			// if player is playing, set youTyping.time according to zero time,
			// against the case when player is stopping.
			youTyping.time = now - youTyping.zeroTime;
			// pad zero time on every frames
			youTyping.zeroTime = (youTyping.zeroTime - youTyping.zeroTimePad) * 0.9
			                     + youTyping.zeroTimePad;
		} else if (gotPlayerState === YT.PlayerState.ENDED) {
			// if video ended and game is still playing, zeroTime is fixed. nothing to do here.
		} else {
			// if player is stopping, we're waiting for starting video.
			// set zero time according to youTyping.time, against the case when player is playing.
			youTyping.zeroTime = youTyping.zeroTimePad
			                   = now - youTyping.settings.offset * 1000
			                     + youTyping.correction - youTyping.time;
		}

		// mark past notes as failed
		var time = youTyping.time;
		var previousLiveNote = null;
		var previousLiveNoteIndex = null;
		youTyping.roll.forEach(function (note, index) {
			// if it's note and passed
			if (note.type === youTyping.itemType.NOTE
			    && note.time + youTyping.settings.failureSuspension < time) {
				// and if the note is live
				if (note.state === youTyping.noteState.WAITING
				 || note.state === youTyping.noteState.HITTING) {
					// and if previous live note exists
					if (previousLiveNote) {
						// mark it failed
						markFailed(previousLiveNote);

						if (previousLiveNoteIndex === youTyping.currentNoteIndex) {
							youTyping.currentNoteIndex = null;
							youTyping.inputBuffer = '';
						}
					}

					previousLiveNote = note;
					previousLiveNoteIndex = index;
				}
			} else if (note.type === youTyping.itemType.LYRIC && note.time < time) {
				// update current lyric index
				if (youTyping.nextLyricIndex !== null
				    && youTyping.nextLyricIndex <= index) {
					youTyping.currentLyricIndex = index;
					youTyping.nextLyricIndex = findNextLyric(index);

					youTyping.dispatchEvent('lyricchange');
				}
			}
			// if order stop marks
			else if (note.type === youTyping.itemType.STOP && note.time < time) {
				// cancel current lyric
				if (youTyping.currentLyricIndex !== null
				    && youTyping.currentLyricIndex < index) {
					youTyping.currentLyricIndex = null;
					youTyping.dispatchEvent('lyricchange');
				}
				// and if previous live note exists
				if (previousLiveNote) {
					// mark it failed
					markFailed(previousLiveNote);

					if (previousLiveNoteIndex === youTyping.currentNoteIndex) {
						youTyping.currentNoteIndex = null;
						youTyping.inputBuffer = '';
					}
				}

				previousLiveNote = null;
				previousLiveNoteIndex = null;
			}
		});

		// end game
		if (gameEndFlag) {
			gameEndFlag = false;
			endGame();
		}
	};

	// mark as failed
	var markFailed = function (note) {
		if (note.state === youTyping.noteState.WAITING) {
			note.state = youTyping.noteState.FAILED;
			note.judgement = 'neglect';
			youTyping.scorebook.neglect++;
		} else if (note.state === youTyping.noteState.HITTING) {
			note.state = youTyping.noteState.HITTINGFAILED;
			youTyping.scorebook.failed[note.judgement]++;
		}

		if (youTyping.lastNote.state !== youTyping.noteState.WAITING &&
		    youTyping.lastNote.state !== youTyping.noteState.HITTING) {
			gameEndFlag = true;
		}

		youTyping.combo = 0;
	};

	var endGame = function () {
		youTyping.dispatchEvent('gameend');
	};

	var getLastKeyHit = function () {
		if (youTyping.replay.length === 0) {
			return null;
		} else {
			return youTyping.replay[youTyping.replay.length - 1];
		}
	};

	var updateScore = function () {
		var scoredWeight = 0;

		youTyping.roll.forEach(function (item) {
			if (item.type === youTyping.itemType.NOTE) {
				if (item.judgement) {
					var weight = null;

					youTyping.settings.judges.forEach(function (judge) {
						if (judge.name === item.judgement) {
							weight = judge.weight;
						}
					});

					if (weight !== null) {
						if (item.state === youTyping.noteState.CLEARED) {
							scoredWeight += item.weight * weight;
						} else {
							scoredWeight += item.weight * weight * 0.5;
						}
					}
				}
			}
		});

		youTyping.score = Math.floor(
			70000 * scoredWeight / youTyping.totalWeight
			+ 30000 * youTyping.scoredCombo / youTyping.totalCombo
		) * 10;
	};

	/******************* Exposed Methods *******************/

	this.play = function () {
		youTyping.player.playVideo();
		youTyping.player.seekTo(youTyping.settings.offset);

		youTyping.isPlayingGame = true;
		youTyping.gameLoopId = setInterval(gameLoop, 10);

		setTimeout(function () {
			// if still buffering after 3 seconds
			if (youTyping.player.getPlayerState() === YT.PlayerState.BUFFERING) {
				// seek again... fix problems in long video
				youTyping.player.seekTo(youTyping.settings.offset);
			}
		}, 3000);
	};

	// hit key
	// TODO: make HitEvent interface
	this.hit = function (key, time, forceHit) {
		if (!time) {
			time = youTyping.now - youTyping.zeroTime;
		}

		// check hit-ability of note by passed key.
		// return false when un-hit-able, and info about new note when hit-able
		var preHitNote = function (noteIndex, hitKey, remainingText) {
			var note = youTyping.roll[noteIndex];
			var newInputBuffer = '';

			if (noteIndex === youTyping.currentNoteIndex) {
				newInputBuffer = youTyping.inputBuffer + key;
			} else { // discard input buffer if not hitting current note
				newInputBuffer = key;
			}

			hitKey = hitKey || key;
			remainingText = remainingText || note.remainingText;

			var matchingRules = youTyping.table.filter(function (rule) {
				// currently YouTyping assumes no character in lyric cannnot be input as
				// single character. (e.g. 'きゃ' is also inputtable as 'ki lya' in romaji mode)
				// so YouTyping spares no effort to find special combination of
				// rules that can generate ramaining text, but it deserves consideration to
				// prevent evel behavior of breaking conversion table input.
				if (!startsWith(rule.before, newInputBuffer)) {
					return false;
				}
				if (!startsWith(remainingText, rule.after)) {
					return false;
				}

				// if rule has next character and not yet satisfied
				if (rule.next && newInputBuffer.length < rule.before.length) {
					// check for hittability of next string by next character.

					var nextNoteIndex;
					var nextNoteInfo;

					// if text remains
					if (remainingText.length > rule.after.length) {
						// try to hit current note
						var remainingString = remainingText.slice(rule.after.length);
						nextNoteInfo = preHitNote(noteIndex, rule.next, remainingString);

						// if note is still hittable, return true.
						if (nextNoteInfo) {
							return true;
						} else {
							return false;
						}
					}
					// else if next note exists
					else if ((nextNoteIndex = findNextNote(noteIndex)) !== null) {
						// try to hit next note
						nextNoteInfo = preHitNote(nextNoteIndex, rule.next);

						// if next note is hittable, return true.
						if (nextNoteInfo) {
							return true;
						} else {
							return false;
						}
					} else { // if next note doesn't exist
						return false;
					}
				}

				return true;
			});

			if (matchingRules.length === 0) { // if no rule matches
				return false;
			} else { // if any rule matches
				var newNoteInfo = {
					noteIndex: noteIndex,
					forcedHit: null
				};

				// take the rule of minimum length (for some comforts)
				var minimumLength = Infinity;
				var minimumRule = null;
				matchingRules.forEach(function (rule) {
					if (rule.before.length < minimumLength) {
						minimumLength = rule.before.length;
						minimumRule = rule;
					}
				});

				newNoteInfo.appliedRule = minimumRule;

				if (youTyping.settings.initial) {
					newNoteInfo.remainingText = '';
					newNoteInfo.inputBuffer = '';
				}
				// if new input buffer equals selected rule, the rule is satisfied, and then
				// rule.after are taken from remaining text.
				// this can be done by just comparing their length.
				else if (newInputBuffer.length === minimumRule.before.length) {
					newNoteInfo.remainingText = remainingText.substr(minimumRule.after.length);
					newNoteInfo.inputBuffer = '';

					if (minimumRule.next) {
						// https://github.com/hakatashi/YouTyping/wiki/Forced-hit
						newNoteInfo.forcedHit = minimumRule.next;
					}
				} else {
					newNoteInfo.remainingText = remainingText;
					newNoteInfo.inputBuffer = newInputBuffer;
				}

				return newNoteInfo;
			}
		};

		// hit note by passed key
		var hitNote = function (newNoteInfo) {
			var note = youTyping.roll[newNoteInfo.noteIndex];

			// update current note index
			youTyping.currentNoteIndex = newNoteInfo.noteIndex;

			// record romaji and regenerate romanizations
			note.receivedRomaji += key;
			if (note.remainingRomaji.slice(0, 1) !== key) {
				romanizeNotes(newNoteInfo.noteIndex, note.text, note.receivedRomaji);
				note.remainingRomaji = note.romaji.slice(note.receivedRomaji.length);
			} else {
				note.remainingRomaji = note.remainingRomaji.slice(1);
			}

			if (newNoteInfo.remainingText === '' || (
				note.mercy !== false
				&& note.receivedRomaji.length >= note.mercy
			)) {
				note.state = youTyping.noteState.CLEARED;
				note.remainingText = '';
				youTyping.inputBuffer = '';
				youTyping.currentNoteIndex = null;

				// record in scorebook
				youTyping.scorebook.cleared[note.judgement]++;
			} else {
				note.state = youTyping.noteState.HITTING;
				note.remainingText = newNoteInfo.remainingText;
				youTyping.inputBuffer = newNoteInfo.inputBuffer;
			}

			// mark all the previous note failed
			youTyping.roll.forEach(function (item, index) {
				if (item.type === youTyping.itemType.NOTE && item.time < note.time) {
					if (item.state === youTyping.noteState.WAITING
					    || item.state === youTyping.noteState.HITTING) {
						markFailed(item);
					}
				}
			});

			// force hit
			if (newNoteInfo.forcedHit) {
				youTyping.hit(newNoteInfo.forcedHit, time, true);
			}

			// if last note is cleared, let's end game
			if (youTyping.lastNote.state !== youTyping.noteState.WAITING &&
			    youTyping.lastNote.state !== youTyping.noteState.HITTING &&
			    youTyping.lastNote.state !== youTyping.noteState.MERCIFIED) {
				gameEndFlag = true;
			}
		};

		// key hit must be single stroke
		if (key.length !== 1) {
			return;
		}

		// key hit mustn't fire before last key hit
		var lastKeyHit = getLastKeyHit();
		if (lastKeyHit && time < lastKeyHit.time) {
			return;
		}

		// record key hit to replay
		youTyping.replay.push({
			time: time,
			key: key
		});

		// if currently hitting some note, try to hit it to complete
		if (youTyping.currentNoteIndex !== null) {
			var newNoteInfo = preHitNote(youTyping.currentNoteIndex);

			if (newNoteInfo) { // if current note is hit-able
				hitNote(newNoteInfo);
				updateScore();
				return;
			}
		}

		// search for nearest note that matches currently passed key rule
		var worstJudge = youTyping.settings.judges[youTyping.settings.judges.length - 1];

		var nearestNote = null;
		var nearestNewNote = null;
		var nearestDistance = Infinity;
		youTyping.roll.forEach(function (item, index) {
			if (item.type === youTyping.itemType.NOTE) {
				var distance = item.time - time;

				if (
					(
						forceHit || (
							worstJudge.from <= distance
							&& distance <= worstJudge.to
						)
					)
					// Luckily `positive number` > null is always true :)
					&& index > youTyping.currentNoteIndex
					&& item.state === youTyping.noteState.WAITING
					&& Math.abs(distance) < Math.abs(nearestDistance)
				) {
					var newNoteInfo = preHitNote(index);

					if (newNoteInfo) {
						nearestNote = item;
						nearestNewNote = newNoteInfo;
						nearestDistance = distance;
					}
				}
			}
		});

		var distance = nearestDistance;

		if (nearestNote !== null) {
			// timing judgement
			var hitJudge = null;

			// TODO: Polyfill Array.prototype.some (IE<9)
			youTyping.settings.judges.some(function (judge) {
				if (judge.from <= distance && distance <= judge.to) {
					hitJudge = judge.name;
					return true;
				}
				return false;
			});

			// force hit
			if (forceHit && hitJudge === null) {
				// apply the most 'baaad' judge
				hitJudge = youTyping.judges[youTyping.judges.length - 1].name;
			}

			if (hitJudge !== null) {
				// if currently hitting other note now, it will be
				// marked as HITTINGFAILED
				if (youTyping.currentNoteIndex !== null) {
					var previousNote = youTyping.roll[youTyping.currentNoteIndex];
					markFailed(previousNote);
				}

				// update current note judgement
				nearestNote.judgement = hitJudge;

				// breaking combo
				// TODO: when hit judge is poor than break combo
				if (hitJudge === youTyping.settings.breakCombo) {
					youTyping.combo = 0;
				}

				// hit note
				// combo may be reset here
				hitNote(nearestNewNote);

				youTyping.combo++;

				// update max combo
				if (youTyping.combo > youTyping.maxCombo) {
					youTyping.maxCombo = youTyping.combo;
				}

				// score combo bonus
				if (youTyping.combo > 50) {
					youTyping.scoredCombo += 50;
				} else {
					youTyping.scoredCombo += youTyping.combo;
				}

				updateScore();

				// trigger judgement effect
				youTyping.dispatchEvent('judgement', {
					judgement: {
						distance: distance,
						judge: hitJudge,
						combo: youTyping.combo
					},
					noteIndex: nearestNewNote
				});
			}
		}
	};

	// abort currently playing game and restart YouTyping
	this.reset = function () {
		// stop game loop
		clearInterval(youTyping.gameLoopId);
		// re-initialize YouTyping
		youTyping.initialize();
		// and re-initialize roll
		initializeRoll();
		// and re-calculate weight
		calculateWeight();
		// also break the flag
		youTyping.isPlayingGame = false;

		// pause video
		youTyping.player.pauseVideo();
		// and seek to offset
		youTyping.player.seekTo(youTyping.settings.offset);
	};

	// get kana version of currently playing lyric
	this.getKanaLyric = function (lyricIndex) {
		if (typeof lyricIndex === 'undefined') {
			lyricIndex = youTyping.currentLyricIndex;
		}

		if (lyricIndex === null) {
			return null;
		}

		var kanaLyric = '';

		for (var i = lyricIndex + 1; i < youTyping.roll.length; i++) {
			if (youTyping.roll[i].type === youTyping.itemType.NOTE) {
				kanaLyric += youTyping.roll[i].text;
			} else if (
				youTyping.roll[i].type === youTyping.itemType.STOP ||
				youTyping.roll[i].type === youTyping.itemType.LYRIC
			) {
				break;
			}
		}

		return kanaLyric;
	};

	// Event listener pseudo-implementation

	// Available events:
	// [x] resourceready
	// [x] gameready
	// [x] playerstatechange
	// [ ] miss
	// [ ] hit
	// [x] judgement
	// [ ] noteclear
	// [x] lyricchange
	// [ ] scorechange
	// [ ] videoend
	// [x] gameend
	// [ ] error
	this.addEventListener = function (type, listener) {
		if (youTyping.events[type] === undefined) {
			youTyping.events[type] = [];
		}

		youTyping.events[type].push(listener);
	};

	this.removeEventListener = function (type, listener) {
		if (youTyping.events[type] === undefined) {
			youTyping.events[type] = [];
		}

		for (var i = youTyping.events[type].length - 1; i >= 0; i--) {
			if (youTyping.events[type][i] === listener) {
				youTyping.events[type].splice(i, 1);
			}
		}
	};

	// wow so dispatching very pseudo
	this.dispatchEvent = function (type, properties) {
		if (youTyping.events[type] === undefined) {
			youTyping.events[type] = [];
		}

		youTyping.events[type].forEach(function (listener) {
			listener.call(screen, properties);
		});
	};

	/******************* Initialization *******************/

	youTyping.totalWeight = 0;
	youTyping.totalCombo = 0;
	youTyping.events = {};

	this.initialize = function () {
		// ZeroTime calculation
		youTyping.zeroTime = 0;
		youTyping.zeroTimePad = 0;
		youTyping.currentTime = 0;
		youTyping.estimateSamples = [];
		youTyping.estimatedZero = 0; // exposed only for debugging
		youTyping.zeroCallFPS = 0; // exposed only for debugging

		// calculate correction
		youTyping.correction = youTyping.settings.correction
		                       + youTyping.settings.controlledCorrection
		                       + youTyping.settings.offset * 1000;
		// initialize zeroTime
		youTyping.zeroTimePad = youTyping.correction - youTyping.settings.offset * 1000;
		youTyping.zeroTime = youTyping.correction - youTyping.settings.offset * 1000;

		// time in roll
		youTyping.time = 0;

		// key input
		youTyping.currentNoteIndex = null;
		youTyping.inputBuffer = '';

		// lyrics
		youTyping.currentLyricIndex = null;
		youTyping.nextLyricIndex = null; // initialized in loadXML()

		// game state
		youTyping.isPlayingGame = false;

		// score and combo
		youTyping.combo = 0;
		youTyping.maxCombo = 0;
		youTyping.score = 0;
		youTyping.scoredCombo = 0;

		// replay and keypress manager
		youTyping.replay = [];

		// initialize scorebook
		youTyping.scorebook = {};
		youTyping.scorebook.failed = {};
		youTyping.scorebook.cleared = {};
		youTyping.scorebook.neglect = 0;
		youTyping.settings.judges.forEach(function (judge) {
			youTyping.scorebook.failed[judge.name] = 0;
			youTyping.scorebook.cleared[judge.name] = 0;
		});

		// internal
		gameEndFlag = false;
	};

	this.initialize();

	// Initialize asynchronously
	// http://stackoverflow.com/questions/22346345/
	$.when(
		$.when(
			loadDataXML(),
			loadTable()
		).done(
			calculateWeight,
			youTyping.dispatchEvent.bind(undefined, 'resourceready')
		),
		setupPlayer()
	).done(youTyping.dispatchEvent.bind(undefined, 'gameready'))
	.fail(function () {
		logTrace('ERROR: Initialization Failed...');
	});
};


text:
package org.wildfly.swarm.spi.api;

import java.util.List;

import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.container.LibraryContainer;
import org.jboss.shrinkwrap.api.spec.JavaArchive;

/**
 * Archive mix-in capable of supporting {@code addAllDependencies}
 *
 *
While not used directly, this interface is exposed through sub-classes
 * that support adding all dependencies.

 *
 *
It is a syntactic sugar for ShrinkWrap's own {@code addAsLibraries} along
 * with {@link ArtifactLookup#allArtifacts()}

 *
 * @author Bob McWhirter
 * @author Ken Finnigan
 * @see ArtifactLookup
 */
public interface DependenciesContainer<T extends Archive<T>> extends LibraryContainer<T>, MarkerContainer<T>, Archive<T> {

    /** Add all application dependencies to this deployment.
     *
     * @return this archive.
     */
    @SuppressWarnings("unchecked")
    default T addAllDependencies() throws Exception {
        // The actual dependencies are added in the runtime stage.
        // See RuntimeDeployer#deploy(...) for further details.

        // flag to instruct the container to add the missing deps upon deploy time
        addMarker("org.wildfly.swarm.allDependencies");
        return (T) this;
    }

    @SuppressWarnings("unchecked")
    // [hb] TODO: is this actually needed anymore? looks brittle to add swarm deps tp the deployment ...
    default T addAllDependencies(boolean includingWildFlySwarm) throws Exception {
        if (!includingWildFlySwarm) {
            return addAllDependencies();
        }

        if (!hasMarker("org.wildfly.swarm.allDependencies")) {
            List<JavaArchive> artifacts = ArtifactLookup.get().allArtifacts();
            addAsLibraries(artifacts);
            addMarker("org.wildfly.swarm.allDependencies");
        }

        return (T) this;

    }

    /**
     * Add a single Maven dependency into the Archive.
     * The following dependency formats are supported:
     *
     * groupId:artifactId
     * groupId:artifactId:version
     * groupId:artifactId:packaging:version
     * groupId:artifactId:packaging:version:classifier
     *
     * @param gav String coordinates of the Maven dependency
     * @return Archive instance
     * @throws Exception
     * @see ArtifactLookup#artifact(String)
     */
    @SuppressWarnings("unchecked")
    default T addDependency(String gav) throws Exception {
        addAsLibrary(ArtifactLookup.get().artifact(gav));
        return (T) this;
    }
}

redpajama_set_name: RedPajamaGithub


text:
use container::Container;
use vec::OwnedVector;
use option::{Option, Some, None};
use cell::Cell;
use unstable::sync::{UnsafeArc, LittleLock};
use rt::sched::SchedHandle;
use clone::Clone;

pub struct SleeperList {
    priv state: UnsafeArc<State>
}

struct State {
    count: uint,
    stack: ~[SchedHandle],
    lock: LittleLock
}

impl SleeperList {
    pub fn new() -> SleeperList {
        SleeperList {
            state: UnsafeArc::new(State {
                count: 0,
                stack: ~[],
                lock: LittleLock::new()
            })
        }
    }

    pub fn push(&mut self, handle: SchedHandle) {
        let handle = Cell::new(handle);
        unsafe {
            let state = self.state.get();
            do (*state).lock.lock {
                (*state).count += 1;
                (*state).stack.push(handle.take());
            }
        }
    }

    pub fn pop(&mut self) -> Option<SchedHandle> {
        unsafe {
            let state = self.state.get();
            do (*state).lock.lock {
                if !(*state).stack.is_empty() {
                    (*state).count -= 1;
                    Some((*state).stack.pop())
                } else {
                    None
                }
            }
        }
    }

    /// A pop that may sometimes miss enqueued elements, but is much faster
    /// to give up without doing any synchronization
    pub fn casual_pop(&mut self) -> Option<SchedHandle> {
        unsafe {
            let state = self.state.get();
            // NB: Unsynchronized check
            if (*state).count == 0 { return None; }
            do (*state).lock.lock {
                if !(*state).stack.is_empty() {
                    // NB: count is also protected by the lock
                    (*state).count -= 1;
                    Some((*state).stack.pop())
                } else {
                    None
                }
            }
        }
    }
}

impl Clone for SleeperList {
    fn clone(&self) -> SleeperList {
        SleeperList {
            state: self.state.clone()
        }
    }
}


text:
layout: default
---

{{ page.title }}

      {{ content }}


text:
#include "types/CreditSender.h"

CreditSender::CreditSender() {}

CreditSender::~CreditSender() {}


text:
import { validator, buildValidations } from 'ember-cp-validations';

export default buildValidations({
  password: [
    validator('presence', true),
    validator('length', {
      min: 8,
      max: 25
    })
  ],
  passwordConfirmation: validator('confirmation', {
    on: 'password'
  })
});


text:
"""
README
======
This file contains Python codes.
======
"""

""" Price a European option by the binomial tree model """
from StockOption import StockOption
import math
import numpy as np

class BinomialEuropeanOption(StockOption):

    def _setup_parameters_(self):
        """ Required calculations for the model """
        self.M = self.N + 1  # Number of terminal nodes of tree
        self.u = 1 + self.pu  # Expected value in the up state
        self.d = 1 - self.pd  # Expected value in the down state
        self.qu = (math.exp((self.r-self.div)*self.dt) -
                   self.d) / (self.u-self.d)
        self.qd = 1-self.qu

    def _initialize_stock_price_tree_(self):
        # Initialize terminal price nodes to zeros
        self.STs = np.zeros(self.M)

        # Calculate expected stock prices for each node
        for i in range(self.M):
            self.STs[i] = self.S0*(self.u**(self.N-i))*(self.d**i)

    def _initialize_payoffs_tree_(self):
        # Get payoffs when the option expires at terminal nodes
        payoffs = np.maximum(
            0, (self.STs-self.K) if self.is_call
            else (self.K-self.STs))

        return payoffs

    def _traverse_tree_(self, payoffs):
        # Starting from the time the option expires, traverse
        # backwards and calculate discounted payoffs at each node
        for i in range(self.N):
            payoffs = (payoffs[:-1] * self.qu +
                       payoffs[1:] * self.qd) * self.df

        return payoffs

    def __begin_tree_traversal__(self):
        payoffs = self._initialize_payoffs_tree_()
        return self._traverse_tree_(payoffs)

    def price(self):
        """ The pricing implementation """
        self._setup_parameters_()
        self._initialize_stock_price_tree_()
        payoffs = self.__begin_tree_traversal__()

        return payoffs[0] # Option value converges to first node

if __name__ == "__main__":
    from BinomialEuropeanOption import BinomialEuropeanOption
    eu_option = BinomialEuropeanOption(
        50, 50, 0.05, 0.5, 2,
        {"pu": 0.2, "pd": 0.2, "is_call": False})
    print eu_option.price()


text:
'use strict';

const workerpool = require('workerpool');
const Worker = require('./multi.js');
const logger = require('../logger.js');
const { Job } = require('../job.js');
const Client = require('../client.js');

const work = (config) => {
  if (config.logLevel !== undefined) {
    logger.level = config.logLevel;
  }

  if (config.setTmpdir) {
    process.env.TMPDIR = config.workdir;
  }

  const worker = new Worker(config);

  // This is necessary to ensure that when the parent process dies, that the
  // child processes in turn die as well
  process.on('disconnect', () => process.exit(0));

  process.on('SIGQUIT', () => worker.stop());

  return worker.run();
};

const fork = (config = {}, jobConfig = {}) => {
  const client = new Client(config);
  const job = new Job(client, jobConfig);

  job.disableFork();

  return job.process({
    allowPaths: true,
  });
};

workerpool.worker({
  work,
  fork,
});


text:
import React, {Component, PropTypes} from 'react';
import {connect} from 'react-redux';
import { push } from 'react-router-redux';
import {resetPassword} from 'redux/modules/auth';
import Helmet from 'react-helmet';
import Grid from 'react-bootstrap/lib/Grid';
import Row from 'react-bootstrap/lib/Row';
import Col from 'react-bootstrap/lib/Col';

@connect(
  state => ({user: state.auth.user}),
  {resetPassword, pushState: push})
export default class ResetPass extends Component {

  static propTypes = {
    user: PropTypes.object,
    resetPassword: PropTypes.func,
    pushState: PropTypes.func.isRequired
  }

  handleSubmit = (event) => {
    event.preventDefault();
    const email = this.refs.email;
    this.props.resetPassword(email.value);
    email.value = '';
    this.props.pushState('/');
  }
  render() {
    const styles = require('./ResetPass.scss');
    return (

        <Helmet title="Reset Password"/>
        <Grid className="container-fluid">
          <Row className="show-grid">
            <Col xs={18} sm={6} md={6} mdOffset={3}>

To Reset Password

Please enter your email address below and check your email to reset password

                  <form onSubmit={this.handleSubmit}>

                      Email
                      <input type="text" ref="email" className="form-control"/>

                    <Col xs={18} sm={12} md={12}>
                      <button className="btn btn-success" onClick={this.handleSubmit}>
                        Reset Password
                      </button>
                    </Col>
                  </form>

            </Col>
          </Row>
        </Grid>

    );
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using Fusion.Core.IniParser;
using System.IO;
using Fusion.Core;
using Fusion.Core.Mathematics;
using Fusion.Core.IniParser.Model;
using Fusion.Core.IniParser.Model.Formatting;
using Fusion.Core.Content;
using Fusion.Drivers.Graphics;

namespace Fusion.Engine.Graphics {

	/// <summary>
	/// Reprsents material.
	/// MaterialInstance???
	/// </summary>
	public partial class MaterialInstance : DisposableBase {

		const int MaxTextures = 16;

		ShaderResource[]	shaderResources;
		ConstantBuffer		constBufferParams;
		ConstantBuffer		constBufferUVMods;

		/// <summary>
		/// Gets material's constant buffer :
		/// </summary>
		internal ConstantBuffer ConstantBufferParameters {
			get {
				return constBufferParams;
			}
		}

		/// <summary>
		/// Gets material's constant buffer :
		/// </summary>
		internal ConstantBuffer ConstantBufferUVModifiers {
			get {
				return constBufferUVMods;
			}
		}

		internal readonly PipelineState GBufferRigid;
		internal readonly PipelineState GBufferSkinned;
		internal readonly PipelineState ShadowRigid;
		internal readonly PipelineState ShadowSkinned;

		/// <summary>
		///
		/// </summary>
		/// <param name="rs"></param>
		/// <param name="maxTextures"></param>
		internal MaterialInstance ( RenderSystem rs, ContentManager content, MaterialData parameters, IEnumerable<TextureMapBind> textureBinds, SurfaceFlags surfaceFlags )
		{
			if (rs==null) {
				throw new ArgumentNullException("rs");
			}

			if (textureBinds.Count()<0 || textureBinds.Count()>MaxTextures) {
				throw new ArgumentException("textureCount", "Must be less or equal to " + MaxTextures.ToString() );
			}

			//
			//	Pipeline states :
			//
			var factory	=	rs.SceneRenderer.Factory;

			var gbufferRigid	=	SurfaceFlags.GBUFFER | SurfaceFlags.RIGID	| surfaceFlags ;
			var gbufferSkinned	=	SurfaceFlags.GBUFFER | SurfaceFlags.SKINNED | surfaceFlags ;
			var shadowRigid		=	SurfaceFlags.SHADOW  | SurfaceFlags.RIGID	| surfaceFlags ;
			var shadowSkinned	=	SurfaceFlags.SHADOW  | SurfaceFlags.SKINNED | surfaceFlags ;

			GBufferRigid	=	factory[ (int)gbufferRigid ];
			GBufferSkinned	=	factory[ (int)gbufferSkinned ];

			ShadowRigid		=	factory[ (int)shadowRigid ];
			ShadowSkinned	=	factory[ (int)shadowSkinned ];

			//
			//	Textures :
			//
			var textures = textureBinds
				.Select( texBind => texBind.TextureMap.LoadTexture( content, texBind.FallbackPath ) );

			var uvMods = new Vector4[MaxTextures];

			textureBinds
				.Select( tb => tb.TextureMap )
				.Select( tm => new Vector4( tm.ScaleU, tm.ScaleV, tm.OffsetU, tm.OffsetV ) )
				.ToArray()
				.CopyTo( uvMods, 0 );

			shaderResources		=	textures.Select( tex => tex.Srv ).ToArray();

			//
			//	Constants :
			//
			constBufferParams	=	new ConstantBuffer( rs.Device, typeof(MaterialData) );
			constBufferParams.SetData( parameters );

			constBufferUVMods	=	new ConstantBuffer( rs.Device, typeof(Vector4), MaxTextures );
			constBufferUVMods.SetData( uvMods );
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="disposing"></param>
		protected override void Dispose ( bool disposing )
		{
			if (disposing) {
				SafeDispose( ref constBufferParams );
				SafeDispose( ref constBufferUVMods );
			}
			base.Dispose( disposing );
		}

		/// <summary>
		/// Sets materials textures
		/// </summary>
		/// <param name="device"></param>
		internal void SetTextures ( GraphicsDevice device )
		{
			for (int i=0; i<shaderResources.Length; i++) {
				device.PixelShaderResources[i] = shaderResources[i];
			}
		}
	}
}


text:
<?php

namespace SmsSender\Tests\Provider;

use SmsSender\Provider\SwisscomProvider;
use SmsSender\Tests\Provider\BaseProviderTest;
use SmsSender\Result\ResultInterface;

/**
 * Tests for SwisscomProvider, based on NexmioProvider tests
 */
class SwisscomProviderTest extends BaseProviderTest
{
    public function getProvider($adapter)
    {
        return new SwisscomProvider($adapter, 'clientId');
    }

    /**
     * @expectedException \SmsSender\Exception\InvalidCredentialsException
     * @expectedExceptionMessage No API credentials provided
     */
    public function testSendWithNullApiCredentials()
    {
        $adapter = $this->getMock('\SmsSender\HttpAdapter\HttpAdapterInterface');
        $provider = new SwisscomProvider($adapter, null);
        $provider->send('0642424242', 'foo!');
    }

    /**
     * @expectedException \SmsSender\Exception\InvalidArgumentException
     * @expectedExceptionMessage The originator parameter is required for this provider.
     */
    public function testSendWithNoOriginator()
    {
        $adapter = $this->getMock('\SmsSender\HttpAdapter\HttpAdapterInterface');
        $provider = $this->getProvider($adapter);
        $provider->send('0642424242', 'foo!');
    }

    public function testSend()
    {
        $provider = $this->getProvider($this->getMockAdapter());
        $result = $provider->send('0642424242', 'foo', 'originator');

        $this->assertNull($result['id']);
        $this->assertEquals(ResultInterface::STATUS_FAILED, $result['status']);
        $this->assertEquals('0642424242', $result['recipient']);
        $this->assertEquals('foo', $result['body']);
        $this->assertEquals('originator', $result['originator']);
    }

    public function testSendWithMockData()
    {
        $data = <<<EOF
{
"outboundSMSMessageRequest": {
    "address": [
      "tel:+41originator"
    ],
    "deliveryInfoList": {
      "deliveryInfo": [
        {
          "address": "tel:+41642424242",
          "deliveryStatus": "DeliveredToNetwork"
        }
      ],
      "resourceURL": ""
    },
    "senderAddress": "tel:+41originator",
    "outboundSMSTextMessage": {
      "message": "foo"
    },
    "clientCorrelator": "0A130A1B",
    "senderName": "originator",
    "resourceURL": ""
  }
}
EOF;
        $provider = $this->getProvider($this->getMockAdapter(null, $data));
        $result = $provider->send('0642424242', 'foo', 'originator');

        $this->assertEquals('0A130A1B', $result['id']);
        $this->assertEquals(ResultInterface::STATUS_SENT, $result['status']);
        $this->assertEquals('0642424242', $result['recipient']);
        $this->assertEquals('foo', $result['body']);
        $this->assertEquals('originator', $result['originator']);
    }

    /**
     * @dataProvider validRecipientProvider
     */
    public function testSendCleansRecipientNumber($recipient, $expectedRecipient, $internationalPrefix = null)
    {
        // setup the adapter
        $adapter = $this->getMock('\SmsSender\HttpAdapter\HttpAdapterInterface');
        $adapter
            ->expects($this->once())
            ->method('getContent')
            ->with(
                $this->anything(), // URL
                $this->equalTo('POST'), // method
                $this->anything(), // headers
                $this->callback(function ($data) use ($expectedRecipient) {
                    $data = json_decode($data, true);
                    $data = explode(':', $data['outboundSMSMessageRequest']['address'][0]);
                    $to = array_pop($data);

                    return $to === $expectedRecipient;
                })
            );

        // setup the provider
        if ($internationalPrefix === null) {
            $provider = new SwisscomProvider($adapter, 'key');
        } else {
            $provider = new SwisscomProvider($adapter, 'key', $internationalPrefix);
        }

        // launch the test
        $provider->send($recipient, 'foo', 'originator');
    }

    public function validRecipientProvider()
    {
        return array(
            array('0642424242', '+41642424242', null),
            array('0642424242', '+33642424242', '+33'),
            array('0642424242', '+44642424242', '+44'),
            array('+33642424242', '+33642424242', '+33'),
            array('+33642424242', '+33642424242', '+44'),
        );
    }
}

// vim: set softtabstop=4 tabstop=4 shiftwidth=4 autoindent:


text:
module.exports = function buildOwner(Ember, resolver) {
  var Owner = Ember.Object.extend(Ember._RegistryProxyMixin, Ember._ContainerProxyMixin);

  var namespace = Ember.Object.create({
    Resolver: {
      create: function() {
        return resolver;
      },
    },
  });

  var fallbackRegistry = Ember.Application.buildRegistry(namespace);
  var registry = new Ember.Registry({
    fallback: fallbackRegistry,
  });

  Ember.ApplicationInstance.setupRegistry(registry);

  var owner = Owner.create({
    __registry__: registry,
    __container__: null,
  });

  var container = registry.container({ owner: owner });
  owner.__container__ = container;

  return owner;
};


text:
#pragma once
#include <aws/personalize/Personalize_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace Personalize
{
namespace Model
{

  /**
   *
The metric to optimize during hyperparameter optimization (HPO).

   *
Amazon Personalize doesn't support configuring the hpoObjective
   * at this time.

See Also:
   AWS
   * API Reference

   */
  class AWS_PERSONALIZE_API HPOObjective
  {
  public:
    HPOObjective();
    HPOObjective(Aws::Utils::Json::JsonView jsonValue);
    HPOObjective& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The type of the metric. Valid values are Maximize and
     * Minimize.

     */
    inline const Aws::String& GetType() const{ return m_type; }

    /**
     *
The type of the metric. Valid values are Maximize and
     * Minimize.

     */
    inline bool TypeHasBeenSet() const { return m_typeHasBeenSet; }

    /**
     *
The type of the metric. Valid values are Maximize and
     * Minimize.

     */
    inline void SetType(const Aws::String& value) { m_typeHasBeenSet = true; m_type = value; }

    /**
     *
The type of the metric. Valid values are Maximize and
     * Minimize.

     */
    inline void SetType(Aws::String&& value) { m_typeHasBeenSet = true; m_type = std::move(value); }

    /**
     *
The type of the metric. Valid values are Maximize and
     * Minimize.

     */
    inline void SetType(const char* value) { m_typeHasBeenSet = true; m_type.assign(value); }

    /**
     *
The type of the metric. Valid values are Maximize and
     * Minimize.

     */
    inline HPOObjective& WithType(const Aws::String& value) { SetType(value); return *this;}

    /**
     *
The type of the metric. Valid values are Maximize and
     * Minimize.

     */
    inline HPOObjective& WithType(Aws::String&& value) { SetType(std::move(value)); return *this;}

    /**
     *
The type of the metric. Valid values are Maximize and
     * Minimize.

     */
    inline HPOObjective& WithType(const char* value) { SetType(value); return *this;}

    /**
     *
The name of the metric.

     */
    inline const Aws::String& GetMetricName() const{ return m_metricName; }

    /**
     *
The name of the metric.

     */
    inline bool MetricNameHasBeenSet() const { return m_metricNameHasBeenSet; }

    /**
     *
The name of the metric.

     */
    inline void SetMetricName(const Aws::String& value) { m_metricNameHasBeenSet = true; m_metricName = value; }

    /**
     *
The name of the metric.

     */
    inline void SetMetricName(Aws::String&& value) { m_metricNameHasBeenSet = true; m_metricName = std::move(value); }

    /**
     *
The name of the metric.

     */
    inline void SetMetricName(const char* value) { m_metricNameHasBeenSet = true; m_metricName.assign(value); }

    /**
     *
The name of the metric.

     */
    inline HPOObjective& WithMetricName(const Aws::String& value) { SetMetricName(value); return *this;}

    /**
     *
The name of the metric.

     */
    inline HPOObjective& WithMetricName(Aws::String&& value) { SetMetricName(std::move(value)); return *this;}

    /**
     *
The name of the metric.

     */
    inline HPOObjective& WithMetricName(const char* value) { SetMetricName(value); return *this;}

    /**
     *
A regular expression for finding the metric in the training job logs.

     */
    inline const Aws::String& GetMetricRegex() const{ return m_metricRegex; }

    /**
     *
A regular expression for finding the metric in the training job logs.

     */
    inline bool MetricRegexHasBeenSet() const { return m_metricRegexHasBeenSet; }

    /**
     *
A regular expression for finding the metric in the training job logs.

     */
    inline void SetMetricRegex(const Aws::String& value) { m_metricRegexHasBeenSet = true; m_metricRegex = value; }

    /**
     *
A regular expression for finding the metric in the training job logs.

     */
    inline void SetMetricRegex(Aws::String&& value) { m_metricRegexHasBeenSet = true; m_metricRegex = std::move(value); }

    /**
     *
A regular expression for finding the metric in the training job logs.

     */
    inline void SetMetricRegex(const char* value) { m_metricRegexHasBeenSet = true; m_metricRegex.assign(value); }

    /**
     *
A regular expression for finding the metric in the training job logs.

     */
    inline HPOObjective& WithMetricRegex(const Aws::String& value) { SetMetricRegex(value); return *this;}

    /**
     *
A regular expression for finding the metric in the training job logs.

     */
    inline HPOObjective& WithMetricRegex(Aws::String&& value) { SetMetricRegex(std::move(value)); return *this;}

    /**
     *
A regular expression for finding the metric in the training job logs.

     */
    inline HPOObjective& WithMetricRegex(const char* value) { SetMetricRegex(value); return *this;}

  private:

    Aws::String m_type;
    bool m_typeHasBeenSet = false;

    Aws::String m_metricName;
    bool m_metricNameHasBeenSet = false;

    Aws::String m_metricRegex;
    bool m_metricRegexHasBeenSet = false;
  };

} // namespace Model
} // namespace Personalize
} // namespace Aws


text:
using Domain;
using Models;
using RegistroVirtual.Attributes;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace RegistroVirtual.Controllers
{
    [SessionAuthorize]
    public class StudentController : Controller
    {
        public ActionResult Index(string CardIdFilter, string FirstNameFilter, string LastNameFilter, bool success = false)
        {
            List<StudentModel> students = new List<StudentModel>();
            Student student = new Student();
            students = student.GetList().ToList();

            if (!string.IsNullOrEmpty(CardIdFilter))
            {
                students = students.Where(x => !string.IsNullOrEmpty(x.CardId) && x.CardId.ToLowerInvariant().Contains(CardIdFilter.ToLowerInvariant())).ToList();
            }

            if (!string.IsNullOrEmpty(FirstNameFilter))
            {
                students = students.Where(x => x.FirstName.ToLowerInvariant().Contains(FirstNameFilter.ToLowerInvariant())).ToList();
            }

            if (!string.IsNullOrEmpty(LastNameFilter))
            {
                students = students.Where(x => x.LastName.ToLowerInvariant().Contains(LastNameFilter.ToLowerInvariant())).ToList();
            }

            if (success)
            {
                ViewBag.SuccessMessage = "El estudiante se ha guardado de manera exitosa";
            }

            return View(students);
        }

        public ActionResult Create(string id, bool error = false)
        {
            StudentModel student = new StudentModel();
            List<SelectListItem> classOptions = new List<SelectListItem>();
            List<ClassModel> classes = new Class().GetClassesList().ToList();

            //Add default option
            classOptions.Add(new SelectListItem
            {
                Text = "-- Sin sección asociada --",
                Value = "0"
            });

            foreach (ClassModel @class in classes)
            {
                classOptions.Add(new SelectListItem
                {
                    Text = @class.Name,
                    Value = @class.Id.ToString()
                });
            }

            if (!string.IsNullOrEmpty(id))
            {
                Student studentDomain = new Student();
                student = studentDomain.Get(id);
            }

            student.Classes = classOptions;

            if (error)
            {
                ViewBag.ErrorMessage = "Debido a un error no se ha podido guardar el estudiante.";
            }

            return View(student);
        }

        public ActionResult ImportTask(bool success = false, bool error = false)
        {
            if (success)
            {
                ViewBag.SuccessMessage = "La importación de estudiantes se ha realizado de manera exitosa";
            }
            else if (error)
            {
                ViewBag.ErrorMessage = "Debido a un error no se ha podido realizar la importación de estudiantes. Valide que el archivo contiene la información y estructura correcta.";
            }

            return View();
        }

        public ActionResult Import()
        {
            bool result = false;

            if (Request.Files.Count > 0)
            {
                var importFile = Request.Files[0];

                if (importFile != null && importFile.ContentLength > 0)
                {
                    var fileName = Path.GetFileName(importFile.FileName);
                    var path = Path.Combine(Server.MapPath("~/Imports/"), fileName);
                    importFile.SaveAs(path);

                    ImportModel importModel = new ImportModel();
                    importModel.FilePath = path;
                    importModel.InstitutionId = ((UserModel)Session["User"]).InstitutionId.ToString();

                    Student student = new Student();
                    result = student.Import(importModel);
                }
            }

            if (result)
            {
                return RedirectToAction("ImportTask", new { success = true });
            }
            else
            {
                return RedirectToAction("ImportTask", new { error = true });
            }
        }

        public string DownloadImportTemplate()
        {
            return "/Content/documents/template.xls";
        }

        public ActionResult Save(StudentModel studentModel)
        {
            Student student = new Student();

            if (student.Save(studentModel))
            {
                return RedirectToAction("Index", new { success = true });
            }
            else
            {
                if (!studentModel.Id.Equals(0))
                {
                    return RedirectToAction("Create", new { id = studentModel.Id, error = true });
                }
                else
                {
                    return RedirectToAction("Create", new { error = true });
                }
            }
        }

    }
}


text:
const path = require('path')

module.exports = ['polyfill', 'ponyfill'].map(method => ({
  target: 'web',
  mode: 'none',
  entry: path.join(__dirname, `${method}.js`),
  output: {
    path: __dirname,
    filename: `test.${method}.js`
  },
  stats: 'none'
}))


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/cloud/deploy/v1/cloud_deploy.proto

namespace Google\Cloud\Deploy\V1;

use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;

/**
 * GetRolloutRequest is the request object used by `GetRollout`.
 *
 * Generated from protobuf message google.cloud.deploy.v1.GetRolloutRequest
 */
class GetRolloutRequest extends \Google\Protobuf\Internal\Message
{
    /**
     * Required. Name of the `Rollout`. Format must be
     * projects/{project_id}/locations/{location_name}/deliveryPipelines/{pipeline_name}/releases/{release_name}/rollouts/{rollout_name}.
     *
     * Generated from protobuf field string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = {
     */
    private $name = '';

    /**
     * Constructor.
     *
     * @param array $data {
     *     Optional. Data for populating the Message object.
     *
     *     @type string $name
     *           Required. Name of the `Rollout`. Format must be
     *           projects/{project_id}/locations/{location_name}/deliveryPipelines/{pipeline_name}/releases/{release_name}/rollouts/{rollout_name}.
     * }
     */
    public function __construct($data = NULL) {
        \GPBMetadata\Google\Cloud\Deploy\V1\CloudDeploy::initOnce();
        parent::__construct($data);
    }

    /**
     * Required. Name of the `Rollout`. Format must be
     * projects/{project_id}/locations/{location_name}/deliveryPipelines/{pipeline_name}/releases/{release_name}/rollouts/{rollout_name}.
     *
     * Generated from protobuf field string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = {
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Required. Name of the `Rollout`. Format must be
     * projects/{project_id}/locations/{location_name}/deliveryPipelines/{pipeline_name}/releases/{release_name}/rollouts/{rollout_name}.
     *
     * Generated from protobuf field string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = {
     * @param string $var
     * @return $this
     */
    public function setName($var)
    {
        GPBUtil::checkString($var, True);
        $this->name = $var;

        return $this;
    }

}


text:
<!DOCTYPE html>

  <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
    <meta charset="UTF-8">
    <title>title</title>
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <link rel="stylesheet" href="foundation/css/foundation.css">

<link href="js/noUiSlider/nouislider.css" rel="stylesheet">
    <link rel="stylesheet" href="font-awesome/css/font-awesome.min.css">
   <link href="css/custom.css" rel="stylesheet">
   <link rel='shortcut icon' type='image/x-icon' href='icons/favicon.ico' />

  <title>New</title>

aaa
aaa
aaa

     <input type="range" class="rotated-text__inner">

     <input type="range" class="rotated-text__inner">

     <input type="range" class="rotated-text__inner">

 Default Button

Add slider
add HTML

<input id="bt1" value="OK">

Click the button below to change the input field to an input button.

<button onclick="myFunction2()">Change input into button</button>

Internet Explorer 8 and earlier does not support the setAttribute method.

A DIV element

<button onclick="myFunction()">Try it</button>


text:
package org.wso2.carbon.siddhi.editor.core.util.designview.beans.configs;

import java.util.Arrays;

/**
 * Represents Code segment of a Siddhi element in a Siddhi app, which is generated as a config
 */
public class ElementCodeSegment implements Comparable<ElementCodeSegment> {
    private int[] queryContextStartIndex;
    private int[] queryContextEndIndex;

    public ElementCodeSegment(int[] queryContextStartIndex, int[] queryContextEndIndex) {
        this.queryContextStartIndex = new int[]{queryContextStartIndex[0], queryContextStartIndex[1]};
        this.queryContextEndIndex = new int[]{queryContextEndIndex[0], queryContextEndIndex[1]};
    }

    public int[] getQueryContextStartIndex() {
        return new int[]{queryContextStartIndex[0], queryContextStartIndex[1]};
    }

    public void setQueryContextStartIndex(int[] queryContextStartIndex) {
        this.queryContextStartIndex = new int[]{queryContextStartIndex[0], queryContextStartIndex[1]};
    }

    public int[] getQueryContextEndIndex() {
        return new int[]{queryContextEndIndex[0], queryContextEndIndex[1]};
    }

    public void setQueryContextEndIndex(int[] queryContextEndIndex) {
        this.queryContextEndIndex = new int[]{queryContextEndIndex[0], queryContextEndIndex[1]};
    }

    public int getStartLine() {
        return queryContextStartIndex[0];
    }

    public int getStartColumn() {
        return queryContextStartIndex[1];
    }

    public int getEndLine() {
        return queryContextEndIndex[0];
    }

    public int getEndColumn() {
        return queryContextEndIndex[1];
    }

    public boolean isValid() {
        if (getStartLine() == getEndLine()) {
            return (getEndColumn() - getStartColumn() > 0);
        }
        return (getEndLine() - getStartLine() > 0);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        ElementCodeSegment that = (ElementCodeSegment) o;
        return Arrays.equals(getQueryContextStartIndex(), that.getQueryContextStartIndex()) &&
                Arrays.equals(getQueryContextEndIndex(), that.getQueryContextEndIndex());
    }

    @Override
    public int hashCode() {
        int result = Arrays.hashCode(getQueryContextStartIndex());
        result = 31 * result + Arrays.hashCode(getQueryContextEndIndex());
        return result;
    }

    @Override
    public int compareTo(ElementCodeSegment elementCodeSegment) {
        if (getStartLine() > elementCodeSegment.getStartLine()) {
            return 1;
        } else if (getStartLine() == elementCodeSegment.getStartLine()) {
            if (getEndLine() == elementCodeSegment.getEndLine()) {
                if (getStartColumn() == elementCodeSegment.getStartColumn()) {
                    return Integer.compare(getEndColumn(), elementCodeSegment.getEndColumn());
                } else {
                    return Integer.compare(getStartColumn(), elementCodeSegment.getStartColumn());
                }
            } else {
                return Integer.compare(getEndLine(), elementCodeSegment.getEndLine());
            }
        } else {
            return -1;
        }
    }
}


text:
import 'timeago.js';
import Vue from 'vue';
import environmentItemComp from '~/environments/components/environment_item.vue';

describe('Environment item', () => {
  let EnvironmentItem;

  beforeEach(() => {
    EnvironmentItem = Vue.extend(environmentItemComp);
  });

  describe('When item is folder', () => {
    let mockItem;
    let component;

    beforeEach(() => {
      mockItem = {
        name: 'review',
        folderName: 'review',
        size: 3,
        isFolder: true,
        environment_path: 'url',
        log_path: 'url',
      };

      component = new EnvironmentItem({
        propsData: {
          model: mockItem,
          canReadEnvironment: true,
        },
      }).$mount();
    });

    it('should render folder icon and name', () => {
      expect(component.$el.querySelector('.folder-name').textContent).toContain(mockItem.name);
      expect(component.$el.querySelector('.folder-icon')).toBeDefined();
    });

    it('should render the number of children in a badge', () => {
      expect(component.$el.querySelector('.folder-name .badge').textContent).toContain(
        mockItem.size,
      );
    });
  });

  describe('when item is not folder', () => {
    let environment;
    let component;

    beforeEach(() => {
      environment = {
        name: 'production',
        size: 1,
        state: 'stopped',
        external_url: 'http://external.com',
        environment_type: null,
        last_deployment: {
          id: 66,
          iid: 6,
          sha: '500aabcb17c97bdcf2d0c410b70cb8556f0362dd',
          ref: {
            name: 'master',
            ref_url: 'root/ci-folders/tree/master',
          },
          tag: true,
          'last?': true,
          user: {
            name: 'Administrator',
            username: 'root',
            id: 1,
            state: 'active',
            avatar_url:
              'https://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=80\u0026d=identicon',
            web_url: 'http://localhost:3000/root',
          },
          commit: {
            id: '500aabcb17c97bdcf2d0c410b70cb8556f0362dd',
            short_id: '500aabcb',
            title: 'Update .gitlab-ci.yml',
            author_name: 'Administrator',
            author_email: 'admin@example.com',
            created_at: '2016-11-07T18:28:13.000+00:00',
            message: 'Update .gitlab-ci.yml',
            author: {
              name: 'Administrator',
              username: 'root',
              id: 1,
              state: 'active',
              avatar_url:
                'https://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=80\u0026d=identicon',
              web_url: 'http://localhost:3000/root',
            },
            commit_path: '/root/ci-folders/tree/500aabcb17c97bdcf2d0c410b70cb8556f0362dd',
          },
          deployable: {
            id: 1279,
            name: 'deploy',
            build_path: '/root/ci-folders/builds/1279',
            retry_path: '/root/ci-folders/builds/1279/retry',
            created_at: '2016-11-29T18:11:58.430Z',
            updated_at: '2016-11-29T18:11:58.430Z',
          },
          manual_actions: [
            {
              name: 'action',
              play_path: '/play',
            },
          ],
        },
        has_stop_action: true,
        environment_path: 'root/ci-folders/environments/31',
        log_path: 'root/ci-folders/environments/31/logs',
        created_at: '2016-11-07T11:11:16.525Z',
        updated_at: '2016-11-10T15:55:58.778Z',
      };

      component = new EnvironmentItem({
        propsData: {
          model: environment,
          canReadEnvironment: true,
        },
      }).$mount();
    });

    it('should render environment name', () => {
      expect(component.$el.querySelector('.environment-name').textContent).toContain(
        environment.name,
      );
    });

    describe('With deployment', () => {
      it('should render deployment internal id', () => {
        expect(component.$el.querySelector('.deployment-column span').textContent).toContain(
          environment.last_deployment.iid,
        );

        expect(component.$el.querySelector('.deployment-column span').textContent).toContain('#');
      });

      it('should render last deployment date', () => {
        const timeagoInstance = new timeago(); // eslint-disable-line
        const formatedDate = timeagoInstance.format(
          environment.last_deployment.deployable.created_at,
        );

        expect(
          component.$el.querySelector('.environment-created-date-timeago').textContent,
        ).toContain(formatedDate);
      });

      describe('With user information', () => {
        it('should render user avatar with link to profile', () => {
          expect(
            component.$el.querySelector('.js-deploy-user-container').getAttribute('href'),
          ).toEqual(environment.last_deployment.user.web_url);
        });
      });

      describe('With build url', () => {
        it('should link to build url provided', () => {
          expect(component.$el.querySelector('.build-link').getAttribute('href')).toEqual(
            environment.last_deployment.deployable.build_path,
          );
        });

        it('should render deployable name and id', () => {
          expect(component.$el.querySelector('.build-link').getAttribute('href')).toEqual(
            environment.last_deployment.deployable.build_path,
          );
        });
      });

      describe('With commit information', () => {
        it('should render commit component', () => {
          expect(component.$el.querySelector('.js-commit-component')).toBeDefined();
        });
      });
    });

    describe('With manual actions', () => {
      it('should render actions component', () => {
        expect(component.$el.querySelector('.js-manual-actions-container')).toBeDefined();
      });
    });

    describe('With external URL', () => {
      it('should render external url component', () => {
        expect(component.$el.querySelector('.js-external-url-container')).toBeDefined();
      });
    });

    describe('With stop action', () => {
      it('should render stop action component', () => {
        expect(component.$el.querySelector('.js-stop-component-container')).toBeDefined();
      });
    });

    describe('With retry action', () => {
      it('should render rollback component', () => {
        expect(component.$el.querySelector('.js-rollback-component-container')).toBeDefined();
      });
    });
  });
});


text:
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using GoldenEye.Events.External;
using MediatR;

namespace GoldenEye.Events;

public class EventBus: IEventBus
{
    private readonly IMediator mediator;
    private readonly IExternalEventProducer externalEventProducer;

    public EventBus(
        IMediator mediator,
        IExternalEventProducer externalEventProducer
    )
    {
        this.mediator = mediator ?? throw new ArgumentNullException(nameof(mediator));
        this.externalEventProducer = externalEventProducer?? throw new ArgumentNullException(nameof(externalEventProducer));
    }

    public async Task Publish<TEvent>(TEvent @event, CancellationToken cancellationToken = default)
        where TEvent: IEvent
    {
        await mediator.Publish(@event, cancellationToken);

        if (@event is IExternalEvent externalEvent)
        {
            await externalEventProducer.Publish(externalEvent, cancellationToken);
        }
    }

    public async Task Publish(CancellationToken cancellationToken, params IEvent[] events)
    {
        foreach (var @event in events)
        {
            await Publish(@event, cancellationToken);
        }
    }

    public Task PublishParallel(CancellationToken cancellationToken, params IEvent[] events)
    {
        var tasks = events.Select(@event => Publish(@event, cancellationToken)).ToList();

        return Task.WhenAll(tasks);
    }
}


text:
import qs from 'query-string';

// AMP-related utils separate to isolate AMP HTML Authors copyright notice.

/**
 * Decodes an AMP Linker parameter. Code sampled from
 * https://github.com/ampproject/amphtml. AMP Linker has a particular pattern
 * and it's important that we carefully decode it the same way the AMP Project
 * does on AMP pages. Throws an error if there is invalid input.
 * @param param The AMP Linker encoded param.
 */
function decodeAmpLinkerParam(value: string, atob: any): string {
    const base64UrlDecodeSubs = { '-': '+', '_': '/', '.': '=' };

    function stringToBytes(str) {
        const bytes = new Uint8Array(str.length);
        for (let i = 0; i < str.length; i++) {
            const charCode = str.charCodeAt(i);
            if (charCode > 255) {
                throw new Error('Characters must be in range [0,255]');
            }
            bytes[i] = charCode;
        }
        return bytes;
    }

    function base64UrlDecodeToBytes(str) {
        const encoded = atob(str.replace(/[-_.]/g, (ch) => base64UrlDecodeSubs[ch]));
        return stringToBytes(encoded);
    }

    function bytesToString(bytes) {
        // Intentionally avoids String.fromCharCode.apply so we don't suffer a
        // stack overflow. #10495, https://jsperf.com/bytesToString-2
        const array = new Array(bytes.length);
        for (let i = 0; i < bytes.length; i++) {
            array[i] = String.fromCharCode(bytes[i]);
        }
        return array.join('');
    }

    function utf8Decode(bytes) {
        if (typeof TextDecoder !== 'undefined') {
            return new TextDecoder('utf-8').decode(bytes);
        }
        const asciiString = bytesToString(new Uint8Array(bytes.buffer || bytes));
        return decodeURIComponent(escape(asciiString));
    }

    const bytes = base64UrlDecodeToBytes(value);
    return utf8Decode(bytes);
}

/**
 * Parses a visitor ID from an AMP Linker value. AMP Linker is used to pass the
 * visitor ID from AMP pages on domains other than the GroupBy customer's
 * domain to non-AMP pages on the GroupBy customer's domain. Returns null if no
 * visitor ID is present in an AMP Linker value in any query string params.
 * @param document The DOM document.
 */
export function visitorIdFromAmpLinker(document: Document): string | null {
    if (!document || !document.location || !document.location.search) {
        return null;
    }

    const qParams = qs.parse(document.location.search);

    if (!qParams.gbi) {
        return null;
    }

    const split = qParams.gbi.split('*');

    if (split.length !== 4 || split[3].length === 0) {
        return null;
    }

    const encodedVisitorId = split[3];

    try {
        return decodeAmpLinkerParam(encodedVisitorId, atob);
    } catch (_) {
        return null;
    }
}


text:
package com.springmvc.utils;

public class JSONUtils {

	public void forTesting() {
		System.out.println("hello world");
	}
}


text:
'use strict';

const path = require('path');
const childProcess = require('child_process');

function findChangedFiles(cwd) {
  return new Promise((resolve, reject) => {
    const args = ['ls-files', '--other', '--modified', '--exclude-standard'];
    const child = childProcess.spawn('git', args, {cwd});

    let stdout = '';
    let stderr = '';
    child.stdout.on('data', data => stdout += data);
    child.stderr.on('data', data => stderr += data);
    child.on('close', code => {
      if (code === 0) {
        stdout = stdout.trim();
        if (stdout === '') {
          resolve([]);
        } else {
          resolve(stdout.split('\n').map(
            changedPath => path.resolve(cwd, changedPath)
          ));
        }
      } else {
        reject(code + ': ' + stderr);
      }
    });
  });
}

function isGitRepository(cwd) {
  return new Promise(resolve => {
    let stdout = '';
    const options = ['rev-parse', '--show-toplevel'];
    const child = childProcess.spawn('git', options, {cwd});
    child.stdout.on('data', data => stdout += data);
    child.on('error', () => resolve(null));
    child.on('close', code => resolve(code === 0 ? stdout.trim() : null));
  });
}

exports.isGitRepository = isGitRepository;
exports.findChangedFiles = findChangedFiles;


text:
const Validator = require('./validator');
const { exists } = require('../jhipster/relationship-types');

const { JPA_DERIVED_IDENTIFIER } = require('../jhipster/relationship-options');
const { ONE_TO_ONE, MANY_TO_MANY, MANY_TO_ONE, ONE_TO_MANY } = require('../jhipster/relationship-types');

module.exports = class RelationshipValidator extends Validator {
  constructor() {
    super('relationship', ['from', 'to', 'type']);
  }

  validate(jdlRelationship, options = {}) {
    if (typeof options === 'boolean') {
      options = { skippedUserManagement: options };
    }
    const { skippedUserManagement, unidirectionalRelationships } = options;
    super.validate(jdlRelationship);
    checkType(jdlRelationship);
    checkInjectedFields(jdlRelationship);
    checkForValidUseOfJPaDerivedIdentifier(jdlRelationship);
    checkForRequiredReflexiveRelationship(jdlRelationship);
    checkForInvalidUseOfTheUserEntity(jdlRelationship, skippedUserManagement);
    checkRelationshipType(jdlRelationship, { skippedUserManagement, unidirectionalRelationships });
  }
};

function checkType(jdlRelationship) {
  if (!exists(jdlRelationship.type)) {
    throw new Error(`The relationship type '${jdlRelationship.type}' doesn't exist.`);
  }
}

function checkInjectedFields(jdlRelationship) {
  if (!(jdlRelationship.injectedFieldInFrom || jdlRelationship.injectedFieldInTo)) {
    throw new Error('At least one injected field is required.');
  }
}

function checkForValidUseOfJPaDerivedIdentifier(jdlRelationship) {
  if (jdlRelationship.type !== ONE_TO_ONE && jdlRelationship.hasGlobalOption(JPA_DERIVED_IDENTIFIER)) {
    throw new Error(`Only a ${ONE_TO_ONE} relationship can have the '${JPA_DERIVED_IDENTIFIER}' option.`);
  }
}

function checkForRequiredReflexiveRelationship(jdlRelationship) {
  if (
    jdlRelationship.from.toLowerCase() === jdlRelationship.to.toLowerCase() &&
    (jdlRelationship.isInjectedFieldInFromRequired || jdlRelationship.isInjectedFieldInToRequired)
  ) {
    throw new Error(`Required relationships to the same entity are not supported, for relationship from and to '${jdlRelationship.from}'.`);
  }
}

function checkForInvalidUseOfTheUserEntity(jdlRelationship, skippedUserManagementOption) {
  const userIsTheSourceAndTheDestination = isUserManagementEntity(jdlRelationship.from) && isUserManagementEntity(jdlRelationship.to);
  if (userIsTheSourceAndTheDestination && !skippedUserManagementOption) {
    throw new Error(
      'Having the source and the destination entities being user management entities (User, Authority) is forbidden unless the ' +
        "entity is not managed by JHipster (use the 'skipUserManagement' option)."
    );
  }
  checkForForbiddenUseOfUserAsSource(jdlRelationship, skippedUserManagementOption);
}

function checkForForbiddenUseOfUserAsSource(jdlRelationship, skippedUserManagementOption) {
  const theSourceIsUserManagement = isUserManagementEntity(jdlRelationship.from);
  if (theSourceIsUserManagement && !skippedUserManagementOption) {
    throw new Error(
      `Relationships from the ${jdlRelationship.from} entity is not supported in the declaration between '${jdlRelationship.from}' and ` +
        `'${jdlRelationship.to}'. You can have this by using the 'skipUserManagement' option.`
    );
  }
}

function checkRelationshipType(jdlRelationship, options) {
  const { skippedUserManagement, unidirectionalRelationships } = options;
  switch (jdlRelationship.type) {
    case ONE_TO_ONE:
      checkOneToOneRelationship(jdlRelationship);
      break;
    case MANY_TO_ONE:
      checkManyToOneRelationship(jdlRelationship, skippedUserManagement);
      break;
    case MANY_TO_MANY:
      checkManyToManyRelationship(jdlRelationship, unidirectionalRelationships);
      break;
    case ONE_TO_MANY:
      return;
    default:
      // never happens, ever.
      throw new Error(`This case shouldn't have happened with type ${jdlRelationship.type}.`);
  }
}

function checkOneToOneRelationship(jdlRelationship) {
  if (!jdlRelationship.injectedFieldInFrom) {
    throw new Error(
      `In the One-to-One relationship from ${jdlRelationship.from} to ${jdlRelationship.to}, ` +
        'the source entity must possess the destination, or you must invert the direction of the relationship.'
    );
  }
}

function checkManyToOneRelationship(jdlRelationship, skippedUserManagementOption) {
  const unidirectionalRelationship = !jdlRelationship.injectedFieldInFrom || !jdlRelationship.injectedFieldInTo;
  const userIsTheSourceEntity = isUserManagementEntity(jdlRelationship.from);
  const userIsTheDestinationEntity = isUserManagementEntity(jdlRelationship.to);
  const userHasTheInjectedField =
    (userIsTheSourceEntity && jdlRelationship.injectedFieldInFrom) || (userIsTheDestinationEntity && jdlRelationship.injectedFieldInTo);
  if (unidirectionalRelationship && userHasTheInjectedField && !skippedUserManagementOption) {
    throw new Error(
      `In the Many-to-One relationship from ${jdlRelationship.from} to ${jdlRelationship.to}, ` +
        'the User entity has the injected field without its management being skipped. ' +
        "To have such a relation, you should use the 'skipUserManagement' option."
    );
  }
}

function checkManyToManyRelationship(jdlRelationship, unidirectionalRelationships) {
  const destinationEntityIsTheUser = isUserManagementEntity(jdlRelationship.to);
  if (jdlRelationship.injectedFieldInFrom && !jdlRelationship.injectedFieldInTo && destinationEntityIsTheUser) {
    // This is a valid case: even though bidirectionality is required for MtM relationships, having the destination
    // entity being the User is possible.
    return;
  }
  const unidirectionalRelationship = !jdlRelationship.injectedFieldInFrom || !jdlRelationship.injectedFieldInTo;
  if (unidirectionalRelationship && !unidirectionalRelationships) {
    const injectedFieldInSourceEntity = !jdlRelationship.injectedFieldInFrom ? 'not set' : `'${jdlRelationship.injectedFieldInFrom}'`;
    const injectedFieldInDestinationEntity = !jdlRelationship.injectedFieldInTo ? 'not set' : `'${jdlRelationship.injectedFieldInTo}'`;
    throw new Error(
      `In the Many-to-Many relationship from ${jdlRelationship.from} to ${jdlRelationship.to}, only ` +
        `bidirectionality is supported. The injected field in the source entity is ${injectedFieldInSourceEntity} ` +
        `and the injected field in the destination entity is ${injectedFieldInDestinationEntity}.`
    );
  }
}

function isUserManagementEntity(entityName) {
  return entityName.toLowerCase() === 'user' || entityName.toLowerCase() === 'authority';
}


text:
using System;
using System.Collections.Generic;
using AcklenAvenue.Commands;
using Machine.Specifications;
using Moq;
using SurgicorSpike.Domain.Application.Commands;
using SurgicorSpike.Domain.Entities;
using SurgicorSpike.Domain.Exceptions;
using SurgicorSpike.Domain.Services;
using SurgicorSpike.Domain.Validators;
using SurgicorSpike.Domain.ValueObjects;

using It = Machine.Specifications.It;

namespace SurgicorSpike.Domain.Specs.Validation
{
    public class when_validating_a_password_reset_command_with_non_existent_reset_token
    {
        static ICommandValidator<ResetPassword> _validator;
        static readonly EncryptedPassword EncryptedPassword = new EncryptedPassword("password");
        static readonly Guid ResetPasswordToken = Guid.NewGuid();
        static List<ValidationFailure> _expectedFailures;
        static Exception _exception;
        static IReadOnlyRepository _readOnlyRepo;

        Establish context =
            () =>
            {
                _readOnlyRepo = Mock.Of<IReadOnlyRepository>();
                _validator = new PassowrdResetValidator(_readOnlyRepo, Mock.Of<ITimeProvider>());

                _expectedFailures = new List<ValidationFailure>
                                    {
                                        new ValidationFailure(
                                            "ResetPasswordToken",
                                            ValidationFailureType.DoesNotExist)
                                    };

                Mock.Get(_readOnlyRepo).Setup(x => x.GetById<PasswordResetAuthorization>(ResetPasswordToken))
                    .Throws(new ItemNotFoundException<PasswordResetAuthorization>(ResetPasswordToken));
            };

        Because of =
            () => _exception = Catch.Exception(() =>
                _validator.Validate(new VisitorSession(),
                    new ResetPassword(ResetPasswordToken, EncryptedPassword)));

        It should_return_expected_failures =
            () => ((CommandValidationException) _exception).ValidationFailures.ShouldBeLike(_expectedFailures);
    }
}


text:
module Language.Jass.CAPI.JassType(
    CJassType
  ) where

import Foreign.Ptr
import Foreign.Storable
import Foreign.C.Types
import Foreign.C.String
import Language.Jass.JassType
import Language.Jass.JIT.Module
import Language.Jass.CAPI.JIT.Module
import Language.Jass.CAPI.Base
import qualified Data.HashMap.Strict as HM
import Control.Monad.Trans.Except
import Control.Monad.IO.Class

type CJassType = CInt

getTypeId :: JassType -> CJITModule -> Ptr CJassType -> IO CInt
getTypeId jt cjit retptr = withJITModuleRef cjit $ \(JITModule (_,typeMap) _) ->
  case HM.lookup jt typeMap of
    Nothing -> setLastError ("Cannot find id for type " ++ show jt) >> return 0
    Just tid -> poke retptr (fromIntegral tid) >> return 1

getTypeFromId :: CJITModule -> CJassType -> ExceptT String IO JassType
getTypeFromId cjit ctp = withJITModuleRefE cjit $ \(JITModule (typeMap,_) _) ->
  case HM.lookup (fromIntegral ctp) typeMap of
    Nothing -> throwE $ "Cannot find type by id " ++ show cjit
    Just jt -> return jt

cVoid :: CJITModule -> Ptr CJassType -> IO CInt
cVoid _ retptr = poke retptr 0 >> return 1
foreign export ccall "hjassVoid" cVoid :: CJITModule -> Ptr CJassType -> IO CInt

cInteger :: CJITModule -> Ptr CJassType -> IO CInt
cInteger = getTypeId JInteger
foreign export ccall "hjassInteger" cInteger :: CJITModule -> Ptr CJassType -> IO CInt

cReal :: CJITModule -> Ptr CJassType -> IO CInt
cReal = getTypeId JReal
foreign export ccall "hjassReal" cReal :: CJITModule -> Ptr CJassType -> IO CInt

cBoolean :: CJITModule -> Ptr CJassType -> IO CInt
cBoolean = getTypeId JBoolean
foreign export ccall "hjassBoolean" cBoolean :: CJITModule -> Ptr CJassType -> IO CInt

cString :: CJITModule -> Ptr CJassType -> IO CInt
cString = getTypeId JString
foreign export ccall "hjassString" cString :: CJITModule -> Ptr CJassType -> IO CInt

cHandle :: CJITModule -> Ptr CJassType -> IO CInt
cHandle = getTypeId JHandle
foreign export ccall "hjassHandle" cHandle :: CJITModule -> Ptr CJassType -> IO CInt

cCode :: CJITModule -> Ptr CJassType -> IO CInt
cCode = getTypeId JCode
foreign export ccall "hjassCode" cCode :: CJITModule -> Ptr CJassType -> IO CInt

cUserDefinedType :: CJITModule -> CString -> Ptr CJassType -> IO CInt
cUserDefinedType cjit cname retptr = do
  jt <- JUserDefined <$> peekCString cname
  getTypeId jt cjit retptr
foreign export ccall "hjassUserDefinedType" cUserDefinedType :: CJITModule -> CString -> Ptr CJassType -> IO CInt

cPrintType :: CJITModule -> CJassType -> Ptr CString -> IO CInt
cPrintType cjit cjt retptr = saveZeroBasedError $ do
  jt <- getTypeFromId cjit cjt
  liftIO $ poke retptr =<< newCString (show jt)
  return 1
foreign export ccall "hjassPrintType" cPrintType :: CJITModule -> CJassType -> Ptr CString -> IO CInt


text:
""" Strict rate-limiter.
"""

__author__ = 'marc@emailscrubbed.com (Marc Berhault)'

import logging
import math
import time

from functools import partial
from tornado.ioloop import IOLoop
from viewfinder.backend.base import counters

class RateLimiter(object):
  """Rate limiter allowing no more than the specified qps.
  The rate limiter keeps a count of "available requests" that can be issued right away.
  Any time ComputeBackoffSecs is called, 'available' is incremented by the qps * time_spent_since_last_call.

  This method strictly enforces rate limiting using a sliding window.
  """

  def __init__(self, qps, unavailable_qps=0.0, qps_counter=None, backoff_counter=None):
    """QPS is the number of desired queries per second. 'unavailable_qps' will be subtracted from 'qps'.
    If 'qps_counter' is not None, it is incremented when Add() is called.
    If 'backoff_counter' is not None, it is incremented by the backoff time in seconds when ComputeBackoffSecs is called
    """
    self._qps = qps
    self._unavailable_qps = unavailable_qps
    self._qps_counter = qps_counter
    self._backoff_counter = backoff_counter

    self.available = self._qps - self._unavailable_qps
    self.last_time = time.time()

  def _GetQPS(self):
    """Return the actual rate-limit we want to use."""
    return self._qps - self._unavailable_qps

  def _Recompute(self):
    """Add qps * time_spent to available."""
    now = time.time()
    delta = now - self.last_time
    # Add the qps freed up since the last call.
    limit = self._GetQPS()
    self.available += limit * delta
    # Make sure the available ops left is in [-qps, +qps].
    # The upper end is throttling (don't exceed the max speed even if we haven't sent anything in > 1s).
    # The lower end is to ensure that unexpected "big ops" don't cause us to pause for too long (eg: we may allow
    # a Scan with 1 op left, but it may finish with > 1 consumed capacity units).
    self.available = max(-limit, min(limit, self.available))
    self.last_time = now

  def Add(self, requests):
    """Specify the number of requests issued. Can be negative if correcting for a previous Add()."""
    self.available -= requests
    if self._qps_counter is not None:
      self._qps_counter.increment(requests)

  def SetQPS(self, new_qps):
    """Specify a new value for QPS. No need to verify ceilings on 'available', ComputeBackoffSecs will do that."""
    self.available += (new_qps - self._qps)
    self._qps = new_qps

  def SetUnavailableQPS(self, new_unavailable_qps):
    """Specify a new value for unavailable QPS. No need to verify ceilings on 'available',
    ComputeBackoffSecs will do that.
    """
    self.available -= (new_unavailable_qps - self._unavailable_qps)
    self._unavailable_qps = new_unavailable_qps

  def ComputeBackoffSecs(self):
    """Return the number of backoff seconds needed to remain within the desired qps. This should be called only if
    the backoff will be done. To check whether backoff is needed without performing it, call NeedsBackoff.
    """
    self._Recompute()
    if self.available >= 0.0:
      # We should technically be checking against 1.0 (since this would mean one request available), but this would
      # cause us to send nothing at all when dealing with very small numbers.
      return 0.0
    else:
      # Time to sleep until we reach positive. |available| / (qps - unavailable)
      # The -1 is to reach "available=1.0". The only exception is when we're between 0-1. Otherwise, we need the
      # offset to reach the desired rate.
      backoff = min(1.0, math.fabs((self.available - 1.0) / self._GetQPS()))
      if self._backoff_counter is not None:
        self._backoff_counter.increment(backoff)
      return backoff

  def NeedsBackoff(self):
    """Returns whether or not we will need to backoff. This does not increment the backoff counter."""
    self._Recompute()
    return self.available < 0.0