text:
<?php

namespace Fisharebest\Webtrees\Functions;

use Fisharebest\Webtrees\I18N;

/**
 * RTL Functions for use in the PDF/HTML reports
 */
class FunctionsRtl {
	const OPEN_PARENTHESES = '([{';

	const CLOSE_PARENTHESES = ')]}';

	const NUMBERS = '0123456789';

	const NUMBER_PREFIX = '+-'; // Treat these like numbers when at beginning or end of numeric strings

	const NUMBER_PUNCTUATION = '- ,.:/'; // Treat these like numbers when inside numeric strings

	const PUNCTUATION = ',.:;?!';

	/** @var string Were we previously processing LTR or RTL. */
	private static $previousState;

	/** @var string Are we currently processing LTR or RTL. */
	private static $currentState;

	/** @var string Text waiting to be processed. */
	private static $waitingText;

	/** @var string LTR text. */
	private static $startLTR;

	/** @var string LTR text. */
	private static $endLTR;

	/** @var string RTL text. */
	private static $startRTL;

	/** @var string RTL text. */
	private static $endRTL;

	/** @var int Offset into the text. */
	private static $lenStart;

	/** @var int Offset into the text. */
	private static $lenEnd;

	/** @var int Offset into the text. */
	private static $posSpanStart;

	/**
	 * This function strips  and  from the input string. It should be used for all
	 * text that has been passed through the PrintReady() function before that text is stored
	 * in the database. The database should NEVER contain these characters.
	 *
	 * @param  string $inputText The string from which the  and  characters should be stripped
	 *
	 * @return string The input string, with  and  stripped
	 */
	public static function stripLrmRlm($inputText) {
		return str_replace(array(WT_UTF8_LRM, WT_UTF8_RLM, WT_UTF8_LRO, WT_UTF8_RLO, WT_UTF8_LRE, WT_UTF8_RLE, WT_UTF8_PDF, "", "", "&LRM;", "&RLM;"), "", $inputText);
	}

	/**
	 * This function encapsulates all texts in the input with  and
	 * according to the directionality specified.
	 *
	 * @param string $inputText Raw input
	 * @param string $direction Directionality (LTR, BOTH, RTL) default BOTH
	 * @param string $class Additional text to insert into output  (such as 'class="yyy"')
	 *
	 * @return string The string with all texts encapsulated as required
	 */
	public static function spanLtrRtl($inputText, $direction = 'BOTH', $class = '') {
		if ($inputText == '') {
			// Nothing to do
			return '';
		}

		$workingText = str_replace("\n", '
', $inputText);
		$workingText = str_replace(array('
', ''), '
', $workingText); // Reposition some incorrectly placed line breaks
		$workingText = self::stripLrmRlm($workingText); // Get rid of any existing UTF8 control codes

		// $nothing  = ''; // Zero Width Non-Joiner  (not sure whether this is still needed to work around a TCPDF bug)
		$nothing = '';

		self::$startLTR = '<LTR>'; // This will become '' at the end
		self::$endLTR   = '</LTR>'; // This will become '' at the end
		self::$startRTL = '<RTL>'; // This will become '' at the end
		self::$endRTL   = '</RTL>'; // This will become '' at the end
		self::$lenStart = strlen(self::$startLTR); // RTL version MUST have same length
		self::$lenEnd   = strlen(self::$endLTR); // RTL version MUST have same length

		self::$previousState = '';
		self::$currentState  = strtoupper(I18N::direction());
		$numberState         = false; // Set when we're inside a numeric string
		$result              = '';
		self::$waitingText   = '';
		$openParDirection    = array();

		self::beginCurrentSpan($result);

		while ($workingText != '') {
			$charArray     = self::getChar($workingText, 0); // Get the next ASCII or UTF-8 character
			$currentLetter = $charArray['letter'];
			$currentLen    = $charArray['length'];

			$openParIndex  = strpos(self::OPEN_PARENTHESES, $currentLetter); // Which opening parenthesis is this?
			$closeParIndex = strpos(self::CLOSE_PARENTHESES, $currentLetter); // Which closing parenthesis is this?

			switch ($currentLetter) {
			case '<':
				// Assume this '<' starts an HTML element
				$endPos = strpos($workingText, '>'); // look for the terminating '>'
				if ($endPos === false) {
					$endPos = 0;
				}
				$currentLen += $endPos;
				$element = substr($workingText, 0, $currentLen);
				$temp    = strtolower(substr($element, 0, 3));
				if (strlen($element) < 7 && $temp == '<br') {
					if ($numberState) {
						$numberState = false;
						if (self::$currentState == 'RTL') {
							self::$waitingText .= WT_UTF8_PDF;
						}
					}
					self::breakCurrentSpan($result);
				} elseif (self::$waitingText == '') {
					$result .= $element;
				} else {
					self::$waitingText .= $element;
				}
				$workingText = substr($workingText, $currentLen);
				break;
			case '&':
				// Assume this '&' starts an HTML entity
				$endPos = strpos($workingText, ';'); // look for the terminating ';'
				if ($endPos === false) {
					$endPos = 0;
				}
				$currentLen += $endPos;
				$entity = substr($workingText, 0, $currentLen);
				if (strtolower($entity) == ' ') {
					$entity .= ' '; // Ensure consistent case for this entity
				}
				if (self::$waitingText == '') {
					$result .= $entity;
				} else {
					self::$waitingText .= $entity;
				}
				$workingText = substr($workingText, $currentLen);
				break;
			case '{':
				if (substr($workingText, 1, 1) == '{') {
					// Assume this '{{' starts a TCPDF directive
					$endPos = strpos($workingText, '}}'); // look for the terminating '}}'
					if ($endPos === false) {
						$endPos = 0;
					}
					$currentLen        = $endPos + 2;
					$directive         = substr($workingText, 0, $currentLen);
					$workingText       = substr($workingText, $currentLen);
					$result            = $result . self::$waitingText . $directive;
					self::$waitingText = '';
					break;
				}
			default:
				// Look for strings of numbers with optional leading or trailing + or -
				// and with optional embedded numeric punctuation
				if ($numberState) {
					// If we're inside a numeric string, look for reasons to end it
					$offset    = 0; // Be sure to look at the current character first
					$charArray = self::getChar($workingText . "\n", $offset);
					if (strpos(self::NUMBERS, $charArray['letter']) === false) {
						// This is not a digit. Is it numeric punctuation?
						if (substr($workingText . "\n", $offset, 6) == ' ') {
							$offset += 6; // This could be numeric punctuation
						} elseif (strpos(self::NUMBER_PUNCTUATION, $charArray['letter']) !== false) {
							$offset += $charArray['length']; // This could be numeric punctuation
						}
						// If the next character is a digit, the current character is numeric punctuation
						$charArray = self::getChar($workingText . "\n", $offset);
						if (strpos(self::NUMBERS, $charArray['letter']) === false) {
							// This is not a digit. End the run of digits and punctuation.
							$numberState = false;
							if (self::$currentState == 'RTL') {
								if (strpos(self::NUMBER_PREFIX, $currentLetter) === false) {
									$currentLetter = WT_UTF8_PDF . $currentLetter;
								} else {
									$currentLetter = $currentLetter . WT_UTF8_PDF; // Include a trailing + or - in the run
								}
							}
						}
					}
				} else {
					// If we're outside a numeric string, look for reasons to start it
					if (strpos(self::NUMBER_PREFIX, $currentLetter) !== false) {
						// This might be a number lead-in
						$offset   = $currentLen;
						$nextChar = substr($workingText . "\n", $offset, 1);
						if (strpos(self::NUMBERS, $nextChar) !== false) {
							$numberState = true; // We found a digit: the lead-in is therefore numeric
							if (self::$currentState == 'RTL') {
								$currentLetter = WT_UTF8_LRE . $currentLetter;
							}
						}
					} elseif (strpos(self::NUMBERS, $currentLetter) !== false) {
						$numberState = true; // The current letter is a digit
						if (self::$currentState == 'RTL') {
							$currentLetter = WT_UTF8_LRE . $currentLetter;
						}
					}
				}

				// Determine the directionality of the current UTF-8 character
				$newState = self::$currentState;
				while (true) {
					if (I18N::scriptDirection(I18N::textScript($currentLetter)) === 'rtl') {
						if (self::$currentState == '') {
							$newState = 'RTL';
							break;
						}

						if (self::$currentState == 'RTL') {
							break;
						}
						// Switch to RTL only if this isn't a solitary RTL letter
						$tempText = substr($workingText, $currentLen);
						while ($tempText != '') {
							$nextCharArray = self::getChar($tempText, 0);
							$nextLetter    = $nextCharArray['letter'];
							$nextLen       = $nextCharArray['length'];
							$tempText      = substr($tempText, $nextLen);

							if (I18N::scriptDirection(I18N::textScript($nextLetter)) === 'rtl') {
								$newState = 'RTL';
								break 2;
							}

							if (strpos(self::PUNCTUATION, $nextLetter) !== false || strpos(self::OPEN_PARENTHESES, $nextLetter) !== false) {
								$newState = 'RTL';
								break 2;
							}

							if ($nextLetter === ' ') {
								break;
							}
							$nextLetter .= substr($tempText . "\n", 0, 5);
							if ($nextLetter === ' ') {
								break;
							}
						}
						// This is a solitary RTL letter : wrap it in UTF8 control codes to force LTR directionality
						$currentLetter = WT_UTF8_LRO . $currentLetter . WT_UTF8_PDF;
						$newState      = 'LTR';
						break;
					}
					if (($currentLen != 1) || ($currentLetter >= 'A' && $currentLetter <= 'Z') || ($currentLetter >= 'a' && $currentLetter <= 'z')) {
						// Since it's neither Hebrew nor Arabic, this UTF-8 character or ASCII letter must be LTR
						$newState = 'LTR';
						break;
					}
					if ($closeParIndex !== false) {
						// This closing parenthesis has to inherit the matching opening parenthesis' directionality
						if (!empty($openParDirection[$closeParIndex]) && $openParDirection[$closeParIndex] != '?') {
							$newState = $openParDirection[$closeParIndex];
						}
						$openParDirection[$closeParIndex] = '';
						break;
					}
					if ($openParIndex !== false) {
						// Opening parentheses always inherit the following directionality
						self::$waitingText .= $currentLetter;
						$workingText = substr($workingText, $currentLen);
						while (true) {
							if ($workingText === '') {
								break;
							}
							if (substr($workingText, 0, 1) === ' ') {
								// Spaces following this left parenthesis inherit the following directionality too
								self::$waitingText .= ' ';
								$workingText = substr($workingText, 1);
								continue;
							}
							if (substr($workingText, 0, 6) === ' ') {
								// Spaces following this left parenthesis inherit the following directionality too
								self::$waitingText .= ' ';
								$workingText = substr($workingText, 6);
								continue;
							}
							break;
						}
						$openParDirection[$openParIndex] = '?';
						break 2; // double break because we're waiting for more information
					}

					// We have a digit or a "normal" special character.
					//
					// When this character is not at the start of the input string, it inherits the preceding directionality;
					// at the start of the input string, it assumes the following directionality.
					//
					// Exceptions to this rule will be handled later during final clean-up.
					//
					self::$waitingText .= $currentLetter;
					$workingText = substr($workingText, $currentLen);
					if (self::$currentState != '') {
						$result .= self::$waitingText;
						self::$waitingText = '';
					}
					break 2; // double break because we're waiting for more information
				}
				if ($newState != self::$currentState) {
					// A direction change has occurred
					self::finishCurrentSpan($result, false);
					self::$previousState = self::$currentState;
					self::$currentState  = $newState;
					self::beginCurrentSpan($result);
				}
				self::$waitingText .= $currentLetter;
				$workingText = substr($workingText, $currentLen);
				$result .= self::$waitingText;
				self::$waitingText = '';

				foreach ($openParDirection as $index => $value) {
					// Since we now know the proper direction, remember it for all waiting opening parentheses
					if ($value === '?') {
						$openParDirection[$index] = self::$currentState;
					}
				}

				break;
			}
		}

		// We're done. Finish last  if necessary
		if ($numberState) {
			if (self::$waitingText === '') {
				if (self::$currentState === 'RTL') {
					$result .= WT_UTF8_PDF;
				}
			} else {
				if (self::$currentState === 'RTL') {
					self::$waitingText .= WT_UTF8_PDF;
				}
			}
		}
		self::finishCurrentSpan($result, true);

		// Get rid of any waiting text
		if (self::$waitingText != '') {
			if (I18N::direction() === 'rtl' && self::$currentState === 'LTR') {
				$result .= self::$startRTL;
				$result .= self::$waitingText;
				$result .= self::$endRTL;
			} else {
				$result .= self::$startLTR;
				$result .= self::$waitingText;
				$result .= self::$endLTR;
			}
			self::$waitingText = '';
		}

		// Lastly, do some more cleanups

		// Move leading RTL numeric strings to following LTR text
		// (this happens when the page direction is RTL and the original text begins with a number and is followed by LTR text)
		while (substr($result, 0, self::$lenStart + 3) === self::$startRTL . WT_UTF8_LRE) {
			$spanEnd = strpos($result, self::$endRTL . self::$startLTR);
			if ($spanEnd === false) {
				break;
			}
			$textSpan = self::stripLrmRlm(substr($result, self::$lenStart + 3, $spanEnd - self::$lenStart - 3));
			if (I18N::scriptDirection(I18N::textScript($textSpan)) === 'rtl') {
				break;
			}
			$result = self::$startLTR . substr($result, self::$lenStart, $spanEnd - self::$lenStart) . substr($result, $spanEnd + self::$lenStart + self::$lenEnd);
			break;
		}

		// On RTL pages, put trailing "." in RTL numeric strings into its own RTL span
		if (I18N::direction() === 'rtl') {
			$result = str_replace(WT_UTF8_PDF . '.' . self::$endRTL, WT_UTF8_PDF . self::$endRTL . self::$startRTL . '.' . self::$endRTL, $result);
		}

		// Trim trailing blanks preceding
 in LTR text
		while (self::$previousState != 'RTL') {
			if (strpos($result, ' <LTRbr>') !== false) {
				$result = str_replace(' <LTRbr>', '<LTRbr>', $result);
				continue;
			}
			if (strpos($result, ' <LTRbr>') !== false) {
				$result = str_replace(' <LTRbr>', '<LTRbr>', $result);
				continue;
			}
			if (strpos($result, '
') !== false) {
				$result = str_replace('
', '
', $result);
				continue;
			}
			if (strpos($result, '
') !== false) {
				$result = str_replace('
', '
', $result);
				continue;
			}
			break; // Neither space nor   : we're done
		}

		// Trim trailing blanks preceding
 in RTL text
		while (true) {
			if (strpos($result, ' <RTLbr>') !== false) {
				$result = str_replace(' <RTLbr>', '<RTLbr>', $result);
				continue;
			}
			if (strpos($result, ' <RTLbr>') !== false) {
				$result = str_replace(' <RTLbr>', '<RTLbr>', $result);
				continue;
			}
			break; // Neither space nor   : we're done
		}

		// Convert '<LTRbr>' and '<RTLbr /'
		$result = str_replace(array('<LTRbr>', '<RTLbr>'), array(self::$endLTR . '
' . self::$startLTR, self::$endRTL . '
' . self::$startRTL), $result);

		// Include leading indeterminate directional text in whatever follows
		if (substr($result . "\n", 0, self::$lenStart) != self::$startLTR && substr($result . "\n", 0, self::$lenStart) != self::$startRTL && substr($result . "\n", 0, 6) != '
') {
			$leadingText = '';
			while (true) {
				if ($result == '') {
					$result = $leadingText;
					break;
				}
				if (substr($result . "\n", 0, self::$lenStart) != self::$startLTR && substr($result . "\n", 0, self::$lenStart) != self::$startRTL) {
					$leadingText .= substr($result, 0, 1);
					$result = substr($result, 1);
					continue;
				}
				$result = substr($result, 0, self::$lenStart) . $leadingText . substr($result, self::$lenStart);
				break;
			}
		}

		// Include solitary "-" and "+" in surrounding RTL text
		$result = str_replace(array(self::$endRTL . self::$startLTR . '-' . self::$endLTR . self::$startRTL, self::$endRTL . self::$startLTR . '-' . self::$endLTR . self::$startRTL), array('-', '+'), $result);

		// Remove empty spans
		$result = str_replace(array(self::$startLTR . self::$endLTR, self::$startRTL . self::$endRTL), '', $result);

		// Finally, correct '<LTR>', '</LTR>', '<RTL>', and '</RTL>'
		switch ($direction) {
		case 'BOTH':
		case 'both':
			// LTR text:  text
			// RTL text:  text
			$sLTR = '' . $nothing;
			$eLTR = $nothing . '';
			$sRTL = '' . $nothing;
			$eRTL = $nothing . '';
			break;
		case 'LTR':
		case 'ltr':
			// LTR text:  text
			// RTL text: text
			$sLTR = '' . $nothing;
			$eLTR = $nothing . '';
			$sRTL = '';
			$eRTL = '';
			break;
		case 'RTL':
		case 'rtl':
		default:
			// LTR text: text
			// RTL text:  text
			$sLTR = '';
			$eLTR = '';
			$sRTL = '' . $nothing;
			$eRTL = $nothing . '';
			break;
		}
		$result = str_replace(array(self::$startLTR, self::$endLTR, self::$startRTL, self::$endRTL), array($sLTR, $eLTR, $sRTL, $eRTL), $result);

		return $result;
	}

	/**
	 * Wrap words that have an asterisk suffix in  and  tags.
	 * This should underline starred names to show the preferred name.
	 *
	 * @param string $textSpan
	 * @param string $direction
	 *
	 * @return string
	 */
	public static function starredName($textSpan, $direction) {
		// To avoid a TCPDF bug that mixes up the word order, insert those  and  tags
		// only when page and span directions are identical.
		if ($direction === strtoupper(I18N::direction())) {
			while (true) {
				$starPos = strpos($textSpan, '*');
				if ($starPos === false) {
					break;
				}
				$trailingText = substr($textSpan, $starPos + 1);
				$textSpan     = substr($textSpan, 0, $starPos);
				$wordStart    = strrpos($textSpan, ' '); // Find the start of the word
				if ($wordStart !== false) {
					$leadingText = substr($textSpan, 0, $wordStart + 1);
					$wordText    = substr($textSpan, $wordStart + 1);
				} else {
					$leadingText = '';
					$wordText    = $textSpan;
				}
				$textSpan = $leadingText . '' . $wordText . '' . $trailingText;
			}
			$textSpan = preg_replace('~(.*)~', '\1', $textSpan);
			// The   is a work-around for a TCPDF bug eating blanks.
			$textSpan = str_replace(array(' ', ' '), array(' ', ' '), $textSpan);
		} else {
			// Text and page directions differ:  remove the  and
			$textSpan = preg_replace('~(.*)\*~', '\1', $textSpan);
			$textSpan = preg_replace('~(.*)~', '\1', $textSpan);
		}

		return $textSpan;
	}

	/**
	 * Get the next character from an input string
	 *
	 * @param string $text
	 * @param string $offset
	 *
	 * @return array
	 */
	public static function getChar($text, $offset) {

		if ($text == '') {
			return array('letter' => '', 'length' => 0);
		}

		$char   = substr($text, $offset, 1);
		$length = 1;
		if ((ord($char) & 0xE0) == 0xC0) {
			$length = 2;
		}
		if ((ord($char) & 0xF0) == 0xE0) {
			$length = 3;
		}
		if ((ord($char) & 0xF8) == 0xF0) {
			$length = 4;
		}
		$letter = substr($text, $offset, $length);

		return array('letter' => $letter, 'length' => $length);
	}

	/**
	 * Insert
 into current span
	 *
	 * @param string $result
	 */
	public static function breakCurrentSpan(&$result) {
		// Interrupt the current span, insert that
, and then continue the current span
		$result .= self::$waitingText;
		self::$waitingText = '';

		$breakString = '<' . self::$currentState . 'br>';
		$result .= $breakString;

		return;
	}

	/**
	 * Begin current span
	 *
	 * @param string $result
	 */
	public static function beginCurrentSpan(&$result) {
		if (self::$currentState == 'LTR') {
			$result .= self::$startLTR;
		}
		if (self::$currentState == 'RTL') {
			$result .= self::$startRTL;
		}

		self::$posSpanStart = strlen($result);
	}

	/**
	 * Finish current span
	 *
	 * @param string $result
	 * @param bool $theEnd
	 */
	public static function finishCurrentSpan(&$result, $theEnd = false) {
		$textSpan = substr($result, self::$posSpanStart);
		$result   = substr($result, 0, self::$posSpanStart);

		// Get rid of empty spans, so that our check for presence of RTL will work
		$result = str_replace(array(self::$startLTR . self::$endLTR, self::$startRTL . self::$endRTL), '', $result);

		// Look for numeric strings that are times (hh:mm:ss). These have to be separated from surrounding numbers.
		$tempResult = '';
		while ($textSpan != '') {
			$posColon = strpos($textSpan, ':');
			if ($posColon === false) {
				break;
			} // No more possible time strings
			$posLRE = strpos($textSpan, WT_UTF8_LRE);
			if ($posLRE === false) {
				break;
			} // No more numeric strings
			$posPDF = strpos($textSpan, WT_UTF8_PDF, $posLRE);
			if ($posPDF === false) {
				break;
			} // No more numeric strings

			$tempResult .= substr($textSpan, 0, $posLRE + 3); // Copy everything preceding the numeric string
			$numericString = substr($textSpan, $posLRE + 3, $posPDF - $posLRE); // Separate the entire numeric string
			$textSpan      = substr($textSpan, $posPDF + 3);
			$posColon      = strpos($numericString, ':');
			if ($posColon === false) {
				// Nothing that looks like a time here
				$tempResult .= $numericString;
				continue;
			}
			$posBlank = strpos($numericString . ' ', ' ');
			$posNbsp  = strpos($numericString . ' ', ' ');
			if ($posBlank < $posNbsp) {
				$posSeparator    = $posBlank;
				$lengthSeparator = 1;
			} else {
				$posSeparator    = $posNbsp;
				$lengthSeparator = 6;
			}
			if ($posColon > $posSeparator) {
				// We have a time string preceded by a blank: Exclude that blank from the numeric string
				$tempResult .= substr($numericString, 0, $posSeparator);
				$tempResult .= WT_UTF8_PDF;
				$tempResult .= substr($numericString, $posSeparator, $lengthSeparator);
				$tempResult .= WT_UTF8_LRE;
				$numericString = substr($numericString, $posSeparator + $lengthSeparator);
			}

			$posBlank = strpos($numericString, ' ');
			$posNbsp  = strpos($numericString, ' ');
			if ($posBlank === false && $posNbsp === false) {
				// The time string isn't followed by a blank
				$textSpan = $numericString . $textSpan;
				continue;
			}

			// We have a time string followed by a blank: Exclude that blank from the numeric string
			if ($posBlank === false) {
				$posSeparator    = $posNbsp;
				$lengthSeparator = 6;
			} elseif ($posNbsp === false) {
				$posSeparator    = $posBlank;
				$lengthSeparator = 1;
			} elseif ($posBlank < $posNbsp) {
				$posSeparator    = $posBlank;
				$lengthSeparator = 1;
			} else {
				$posSeparator    = $posNbsp;
				$lengthSeparator = 6;
			}
			$tempResult .= substr($numericString, 0, $posSeparator);
			$tempResult .= WT_UTF8_PDF;
			$tempResult .= substr($numericString, $posSeparator, $lengthSeparator);
			$posSeparator += $lengthSeparator;
			$numericString = substr($numericString, $posSeparator);
			$textSpan      = WT_UTF8_LRE . $numericString . $textSpan;
		}
		$textSpan       = $tempResult . $textSpan;
		$trailingBlanks = '';
		$trailingBreaks = '';

		/* ****************************** LTR text handling ******************************** */

		if (self::$currentState === 'LTR') {
			// Move trailing numeric strings to the following RTL text. Include any blanks preceding or following the numeric text too.
			if (I18N::direction() === 'rtl' && self::$previousState === 'RTL' && !$theEnd) {
				$trailingString = '';
				$savedSpan      = $textSpan;
				while ($textSpan !== '') {
					// Look for trailing spaces and tentatively move them
					if (substr($textSpan, -1) === ' ') {
						$trailingString = ' ' . $trailingString;
						$textSpan       = substr($textSpan, 0, -1);
						continue;
					}
					if (substr($textSpan, -6) === ' ') {
						$trailingString = ' ' . $trailingString;
						$textSpan       = substr($textSpan, 0, -1);
						continue;
					}
					if (substr($textSpan, -3) !== WT_UTF8_PDF) {
						// There is no trailing numeric string
						$textSpan = $savedSpan;
						break;
					}

					// We have a numeric string
					$posStartNumber = strrpos($textSpan, WT_UTF8_LRE);
					if ($posStartNumber === false) {
						$posStartNumber = 0;
					}
					$trailingString = substr($textSpan, $posStartNumber, strlen($textSpan) - $posStartNumber) . $trailingString;
					$textSpan       = substr($textSpan, 0, $posStartNumber);

					// Look for more spaces and move them too
					while ($textSpan != '') {
						if (substr($textSpan, -1) == ' ') {
							$trailingString = ' ' . $trailingString;
							$textSpan       = substr($textSpan, 0, -1);
							continue;
						}
						if (substr($textSpan, -6) == ' ') {
							$trailingString = ' ' . $trailingString;
							$textSpan       = substr($textSpan, 0, -1);
							continue;
						}
						break;
					}

					self::$waitingText = $trailingString . self::$waitingText;
					break;
				}
			}

			$savedSpan = $textSpan;
			// Move any trailing
, optionally preceded or followed by blanks, outside this LTR span
			while ($textSpan != '') {
				if (substr($textSpan, -1) == ' ') {
					$trailingBlanks = ' ' . $trailingBlanks;
					$textSpan       = substr($textSpan, 0, -1);
					continue;
				}
				if (substr('......' . $textSpan, -6) == ' ') {
					$trailingBlanks = ' ' . $trailingBlanks;
					$textSpan       = substr($textSpan, 0, -6);
					continue;
				}
				break;
			}
			while (substr($textSpan, -9) == '<LTRbr>') {
				$trailingBreaks = '
' . $trailingBreaks; // Plain
 because it's outside a span
				$textSpan       = substr($textSpan, 0, -9);
			}
			if ($trailingBreaks != '') {
				while ($textSpan != '') {
					if (substr($textSpan, -1) == ' ') {
						$trailingBreaks = ' ' . $trailingBreaks;
						$textSpan       = substr($textSpan, 0, -1);
						continue;
					}
					if (substr('......' . $textSpan, -6) == ' ') {
						$trailingBreaks = ' ' . $trailingBreaks;
						$textSpan       = substr($textSpan, 0, -6);
						continue;
					}
					break;
				}
				self::$waitingText = $trailingBlanks . self::$waitingText; // Put those trailing blanks inside the following span
			} else {
				$textSpan = $savedSpan;
			}

			$trailingBlanks      = '';
			$trailingPunctuation = '';
			$trailingID          = '';
			$trailingSeparator   = '';
			$leadingSeparator    = '';
			while (I18N::direction() === 'rtl') {
				if (strpos($result, self::$startRTL) !== false) {
					// Remove trailing blanks for inclusion in a separate LTR span
					while ($textSpan != '') {
						if (substr($textSpan, -1) === ' ') {
							$trailingBlanks = ' ' . $trailingBlanks;
							$textSpan       = substr($textSpan, 0, -1);
							continue;
						}
						if (substr($textSpan, -6) === ' ') {
							$trailingBlanks = ' ' . $trailingBlanks;
							$textSpan       = substr($textSpan, 0, -1);
							continue;
						}
						break;
					}

					// Remove trailing punctuation for inclusion in a separate LTR span
					if ($textSpan == '') {
						$trailingChar = "\n";
					} else {
						$trailingChar = substr($textSpan, -1);
					}
					if (strpos(self::PUNCTUATION, $trailingChar) !== false) {
						$trailingPunctuation = $trailingChar;
						$textSpan            = substr($textSpan, 0, -1);
					}
				}

				// Remove trailing ID numbers that look like "(xnnn)" for inclusion in a separate LTR span
				while (true) {
					if (substr($textSpan, -1) != ')') {
						break;
					} // There is no trailing ')'
					$posLeftParen = strrpos($textSpan, '(');
					if ($posLeftParen === false) {
						break;
					} // There is no leading '('
					$temp = self::stripLrmRlm(substr($textSpan, $posLeftParen)); // Get rid of UTF8 control codes

					// If the parenthesized text doesn't look like an ID number,
					// we don't want to touch it.
					// This check won't work if somebody uses ID numbers with an unusual format.
					$offset    = 1;
					$charArray = self::getChar($temp, $offset); // Get 1st character of parenthesized text
					if (strpos(self::NUMBERS, $charArray['letter']) !== false) {
						break;
					}
					$offset += $charArray['length']; // Point at 2nd character of parenthesized text
					if (strpos(self::NUMBERS, substr($temp, $offset, 1)) === false) {
						break;
					}
					// 1st character of parenthesized text is alpha, 2nd character is a digit; last has to be a digit too
					if (strpos(self::NUMBERS, substr($temp, -2, 1)) === false) {
						break;
					}

					$trailingID = substr($textSpan, $posLeftParen);
					$textSpan   = substr($textSpan, 0, $posLeftParen);
					break;
				}

				// Look for " - " or blank preceding the ID number and remove it for inclusion in a separate LTR span
				if ($trailingID != '') {
					while ($textSpan != '') {
						if (substr($textSpan, -1) == ' ') {
							$trailingSeparator = ' ' . $trailingSeparator;
							$textSpan          = substr($textSpan, 0, -1);
							continue;
						}
						if (substr($textSpan, -6) == ' ') {
							$trailingSeparator = ' ' . $trailingSeparator;
							$textSpan          = substr($textSpan, 0, -6);
							continue;
						}
						if (substr($textSpan, -1) == '-') {
							$trailingSeparator = '-' . $trailingSeparator;
							$textSpan          = substr($textSpan, 0, -1);
							continue;
						}
						break;
					}
				}

				// Look for " - " preceding the text and remove it for inclusion in a separate LTR span
				$foundSeparator = false;
				$savedSpan      = $textSpan;
				while ($textSpan != '') {
					if (substr($textSpan, 0, 1) == ' ') {
						$leadingSeparator = ' ' . $leadingSeparator;
						$textSpan         = substr($textSpan, 1);
						continue;
					}
					if (substr($textSpan, 0, 6) == ' ') {
						$leadingSeparator = ' ' . $leadingSeparator;
						$textSpan         = substr($textSpan, 6);
						continue;
					}
					if (substr($textSpan, 0, 1) == '-') {
						$leadingSeparator = '-' . $leadingSeparator;
						$textSpan         = substr($textSpan, 1);
						$foundSeparator   = true;
						continue;
					}
					break;
				}
				if (!$foundSeparator) {
					$textSpan         = $savedSpan;
					$leadingSeparator = '';
				}
				break;
			}

			// We're done: finish the span
			$textSpan = self::starredName($textSpan, 'LTR'); // Wrap starred name in  and  tags
			while (true) {
				// Remove blanks that precede <LTRbr>
				if (strpos($textSpan, ' <LTRbr>') !== false) {
					$textSpan = str_replace(' <LTRbr>', '<LTRbr>', $textSpan);
					continue;
				}
				if (strpos($textSpan, ' <LTRbr>') !== false) {
					$textSpan = str_replace(' <LTRbr>', '<LTRbr>', $textSpan);
					continue;
				}
				break;
			}
			if ($leadingSeparator != '') {
				$result = $result . self::$startLTR . $leadingSeparator . self::$endLTR;
			}
			$result = $result . $textSpan . self::$endLTR;
			if ($trailingSeparator != '') {
				$result = $result . self::$startLTR . $trailingSeparator . self::$endLTR;
			}
			if ($trailingID != '') {
				$result = $result . self::$startLTR . $trailingID . self::$endLTR;
			}
			if ($trailingPunctuation != '') {
				$result = $result . self::$startLTR . $trailingPunctuation . self::$endLTR;
			}
			if ($trailingBlanks != '') {
				$result = $result . self::$startLTR . $trailingBlanks . self::$endLTR;
			}
		}

		/* ****************************** RTL text handling ******************************** */

		if (self::$currentState == 'RTL') {
			$savedSpan = $textSpan;

			// Move any trailing
, optionally followed by blanks, outside this RTL span
			while ($textSpan != '') {
				if (substr($textSpan, -1) == ' ') {
					$trailingBlanks = ' ' . $trailingBlanks;
					$textSpan       = substr($textSpan, 0, -1);
					continue;
				}
				if (substr('......' . $textSpan, -6) == ' ') {
					$trailingBlanks = ' ' . $trailingBlanks;
					$textSpan       = substr($textSpan, 0, -6);
					continue;
				}
				break;
			}
			while (substr($textSpan, -9) == '<RTLbr>') {
				$trailingBreaks = '
' . $trailingBreaks; // Plain
 because it's outside a span
				$textSpan       = substr($textSpan, 0, -9);
			}
			if ($trailingBreaks != '') {
				self::$waitingText = $trailingBlanks . self::$waitingText; // Put those trailing blanks inside the following span
			} else {
				$textSpan = $savedSpan;
			}

			// Move trailing numeric strings to the following LTR text. Include any blanks preceding or following the numeric text too.
			if (!$theEnd && I18N::direction() !== 'rtl') {
				$trailingString = '';
				$savedSpan      = $textSpan;
				while ($textSpan != '') {
					// Look for trailing spaces and tentatively move them
					if (substr($textSpan, -1) === ' ') {
						$trailingString = ' ' . $trailingString;
						$textSpan       = substr($textSpan, 0, -1);
						continue;
					}
					if (substr($textSpan, -6) === ' ') {
						$trailingString = ' ' . $trailingString;
						$textSpan       = substr($textSpan, 0, -1);
						continue;
					}
					if (substr($textSpan, -3) !== WT_UTF8_PDF) {
						// There is no trailing numeric string
						$textSpan = $savedSpan;
						break;
					}

					// We have a numeric string
					$posStartNumber = strrpos($textSpan, WT_UTF8_LRE);
					if ($posStartNumber === false) {
						$posStartNumber = 0;
					}
					$trailingString = substr($textSpan, $posStartNumber, strlen($textSpan) - $posStartNumber) . $trailingString;
					$textSpan       = substr($textSpan, 0, $posStartNumber);

					// Look for more spaces and move them too
					while ($textSpan != '') {
						if (substr($textSpan, -1) == ' ') {
							$trailingString = ' ' . $trailingString;
							$textSpan       = substr($textSpan, 0, -1);
							continue;
						}
						if (substr($textSpan, -6) == ' ') {
							$trailingString = ' ' . $trailingString;
							$textSpan       = substr($textSpan, 0, -1);
							continue;
						}
						break;
					}

					self::$waitingText = $trailingString . self::$waitingText;
					break;
				}
			}

			// Trailing " - " needs to be prefixed to the following span
			if (!$theEnd && substr('...' . $textSpan, -3) == ' - ') {
				$textSpan          = substr($textSpan, 0, -3);
				self::$waitingText = ' - ' . self::$waitingText;
			}

			while (I18N::direction() === 'rtl') {
				// Look for " - " preceding <RTLbr> and relocate it to the front of the string
				$posDashString = strpos($textSpan, ' - <RTLbr>');
				if ($posDashString === false) {
					break;
				}
				$posStringStart = strrpos(substr($textSpan, 0, $posDashString), '<RTLbr>');
				if ($posStringStart === false) {
					$posStringStart = 0;
				} else {
					$posStringStart += 9;
				} // Point to the first char following the last <RTLbr>

				$textSpan = substr($textSpan, 0, $posStringStart) . ' - ' . substr($textSpan, $posStringStart, $posDashString - $posStringStart) . substr($textSpan, $posDashString + 3);
			}

			// Strip leading spaces from the RTL text
			$countLeadingSpaces = 0;
			while ($textSpan != '') {
				if (substr($textSpan, 0, 1) == ' ') {
					$countLeadingSpaces++;
					$textSpan = substr($textSpan, 1);
					continue;
				}
				if (substr($textSpan, 0, 6) == ' ') {
					$countLeadingSpaces++;
					$textSpan = substr($textSpan, 6);
					continue;
				}
				break;
			}

			// Strip trailing spaces from the RTL text
			$countTrailingSpaces = 0;
			while ($textSpan != '') {
				if (substr($textSpan, -1) == ' ') {
					$countTrailingSpaces++;
					$textSpan = substr($textSpan, 0, -1);
					continue;
				}
				if (substr($textSpan, -6) == ' ') {
					$countTrailingSpaces++;
					$textSpan = substr($textSpan, 0, -6);
					continue;
				}
				break;
			}

			// Look for trailing " -", reverse it, and relocate it to the front of the string
			if (substr($textSpan, -2) === ' -') {
				$posDashString  = strlen($textSpan) - 2;
				$posStringStart = strrpos(substr($textSpan, 0, $posDashString), '<RTLbr>');
				if ($posStringStart === false) {
					$posStringStart = 0;
				} else {
					$posStringStart += 9;
				} // Point to the first char following the last <RTLbr>

				$textSpan = substr($textSpan, 0, $posStringStart) . '- ' . substr($textSpan, $posStringStart, $posDashString - $posStringStart) . substr($textSpan, $posDashString + 2);
			}

			if ($countLeadingSpaces != 0) {
				$newLength = strlen($textSpan) + $countLeadingSpaces;
				$textSpan  = str_pad($textSpan, $newLength, ' ', (I18N::direction() === 'rtl' ? STR_PAD_LEFT : STR_PAD_RIGHT));
			}
			if ($countTrailingSpaces != 0) {
				if (I18N::direction() === 'ltr') {
					if ($trailingBreaks === '') {
						// Move trailing RTL spaces to front of following LTR span
						$newLength         = strlen(self::$waitingText) + $countTrailingSpaces;
						self::$waitingText = str_pad(self::$waitingText, $newLength, ' ', STR_PAD_LEFT);
					}
				} else {
					$newLength = strlen($textSpan) + $countTrailingSpaces;
					$textSpan  = str_pad($textSpan, $newLength, ' ', STR_PAD_RIGHT);
				}
			}

			// We're done: finish the span
			$textSpan = self::starredName($textSpan, 'RTL'); // Wrap starred name in  and  tags
			$result   = $result . $textSpan . self::$endRTL;
		}

		if (self::$currentState != 'LTR' && self::$currentState != 'RTL') {
			$result = $result . $textSpan;
		}

		$result .= $trailingBreaks; // Get rid of any waiting

		return;
	}

	/**
	 * Wrap text, similar to the PHP wordwrap() function.
	 *
	 * @param string $string
	 * @param int $width
	 * @param string $sep
	 * @param bool $cut
	 *
	 * @return string
	 */
	public static function utf8WordWrap($string, $width = 75, $sep = "\n", $cut = false) {
		$out = '';
		while ($string) {
			if (mb_strlen($string) <= $width) {
				// Do not wrap any text that is less than the output area.
				$out .= $string;
				$string = '';
			} else {
				$sub1 = mb_substr($string, 0, $width + 1);
				if (mb_substr($string, mb_strlen($sub1) - 1, 1) == ' ') {
					// include words that end by a space immediately after the area.
					$sub = $sub1;
				} else {
					$sub = mb_substr($string, 0, $width);
				}
				$spacepos = strrpos($sub, ' ');
				if ($spacepos === false) {
					// No space on line?
					if ($cut) {
						$out .= $sub . $sep;
						$string = mb_substr($string, mb_strlen($sub));
					} else {
						$spacepos = strpos($string, ' ');
						if ($spacepos === false) {
							$out .= $string;
							$string = '';
						} else {
							$out .= substr($string, 0, $spacepos) . $sep;
							$string = substr($string, $spacepos + 1);
						}
					}
				} else {
					// Split at space;
					$out .= substr($string, 0, $spacepos) . $sep;
					$string = substr($string, $spacepos + 1);
				}
			}
		}

		return $out;
	}
}


text:
package com.home.giraffe.objects.Jive;

public enum JiveVerbTypes {
    JiveUnsupported,

    JiveReplied,
    JiveCommented,

    JiveCreated,
    JiveCorrectAnswerSet,
    JiveModified,

    JiveLiked,

    JivePromoted,

    JiveCompleted,

    JiveJoined, JiveInstalled, JiveVoted, JiveProjectCompleted, JiveBookmarked // TODO
}

redpajama_set_name: RedPajamaGithub


text:
'use strict';

// HBase Query Builder - Microservice
//

var seneca = require('seneca')();
var debug = require('debug')('hbase_query_builder');
var HBaseQueryBuilder = require('./hbase_query_builder');

// FIXME, usare callback con init per attendere che il servizio abbia completato il setup
var qb = new HBaseQueryBuilder({seneca: seneca});

qb.init(function(err){
	debug(err);
  seneca.listen({host: 'localhost', port: 3050});
  console.log('Hbase Query Builder listening on ', 'localhost', 3050);
});

// export seneca for mocha
module.exports.seneca = seneca;


text:
package com.b2international.index.es.client;

import static com.google.common.base.Preconditions.checkState;

import java.io.IOException;
import java.net.InetSocketAddress;

import org.elasticsearch.action.bulk.BulkProcessor;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.search.ClearScrollRequest;
import org.elasticsearch.action.search.ClearScrollResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchScrollRequest;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.reindex.BulkByScrollResponse;
import org.elasticsearch.script.Script;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.b2international.index.Activator;
import com.b2international.index.es.EsClientConfiguration;
import com.b2international.index.es.client.http.EsHttpClient;
import com.b2international.index.es.client.tcp.EsTcpClient;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.cache.RemovalNotification;
import com.google.common.net.HostAndPort;
import com.google.common.util.concurrent.UncheckedExecutionException;

/**
 * @since 6.11
 */
public interface EsClient extends AutoCloseable {

	Logger LOG = LoggerFactory.getLogger("elastic-snowowl");

	IndicesClient indices();

	ClusterClient cluster();

	GetResponse get(GetRequest req) throws IOException;

	SearchResponse search(SearchRequest req) throws IOException;

	SearchResponse scroll(SearchScrollRequest req) throws IOException;

	ClearScrollResponse clearScroll(ClearScrollRequest req) throws IOException;

	BulkProcessor.Builder bulk(BulkProcessor.Listener listener);

	BulkByScrollResponse updateByQuery(String index, String type, int batchSize, Script script, int numberOfSlices, QueryBuilder query) throws IOException;

	BulkByScrollResponse deleteByQuery(String index, String type, int batchSize, int numberOfSlices, QueryBuilder query) throws IOException;

	static EsClient create(final EsClientConfiguration configuration) {
		return ClientPool.create(configuration);
	}

	static void closeAll() {
		ClientPool.closeAll();
	}

	/**
	 * @since 6.11
	 */
	final class ClientPool {

		private static final LoadingCache<EsClientConfiguration, EsClient> CLIENTS_BY_HOST = CacheBuilder.newBuilder()
				.removalListener(ClientPool::onRemove)
				.build(CacheLoader.from(ClientPool::onAdd));

		private ClientPool() {}

		static EsClient create(EsClientConfiguration configuration) {
			try {
				return CLIENTS_BY_HOST.getUnchecked(configuration);
			} catch (UncheckedExecutionException e) {
				if (e.getCause() instanceof RuntimeException) {
					throw (RuntimeException) e.getCause();
				} else {
					throw new RuntimeException(e.getCause());
				}
			}
		}

		static void closeAll() {
			CLIENTS_BY_HOST.invalidateAll();
			CLIENTS_BY_HOST.cleanUp();
		}

		@SuppressWarnings("resource")
		static EsClient onAdd(final EsClientConfiguration configuration) {
			LOG.info("Connecting to Elasticsearch cluster at '{}'{}, connect timeout: {} ms, socket timeout: {} ms.",
					configuration.getClusterUrl(),
					configuration.isProtected() ? " using basic authentication" : "",
					configuration.getConnectTimeout(),
					configuration.getSocketTimeout());

			if (configuration.isHttp()) {
				return new EsHttpClient(configuration);
			} else {
				checkState(configuration.isTcp(), "Only TCP and HTTP clients are supported");
				checkState(!configuration.isProtected(), "TCP connection scheme does not yet support security configuration. Consider switching to HTTP instead.");
				HostAndPort hostAndPort = HostAndPort.fromString(configuration.getClusterUrl().replaceAll(EsClientConfiguration.TCP_SCHEME, ""));
				Settings settings = Settings.builder()
				        .put("cluster.name", configuration.getClusterName())
				        .build();
				return new EsTcpClient(new PreBuiltTransportClient(settings)
						.addTransportAddress(new TransportAddress(new InetSocketAddress(hostAndPort.getHostText(), hostAndPort.getPort()))));
			}
		}

		static void onRemove(final RemovalNotification<EsClientConfiguration, EsClient> notification) {
			Activator.withTccl(() -> {
				closeClient(notification.getKey(), notification.getValue());
			});
		}

		static void closeClient(final EsClientConfiguration configuration, EsClient client) {
			try {
				client.close();
				LOG.info("Closed ES client connected to '{}'", configuration.getClusterUrl());
			} catch (final Exception e) {
				LOG.error("Unable to close ES client connected to '{}'", configuration.getClusterUrl(), e);
			}
		}

	}

}


text:
from datetime import datetime

from atomformat import Feed

from django.conf import settings
from django.core.urlresolvers import reverse
from django.shortcuts import get_object_or_404
from django.template.defaultfilters import linebreaks, escape, capfirst

from django.contrib.auth.models import User
from django.contrib.sites.models import Site

from friends.models import friend_set_for

from blog.models import Post

ITEMS_PER_FEED = getattr(settings, "PINAX_ITEMS_PER_FEED", 20)

class BasePostFeed(Feed):

    def item_id(self, post):
        return "http://%s%s" % (
            Site.objects.get_current().domain,
            post.get_absolute_url(),
        )

    def item_title(self, post):
        return post.title

    def item_updated(self, post):
        return post.updated_at

    def item_published(self, post):
        return post.created_at

    def item_content(self, post):
        return {"type": "html"}, linebreaks(escape(post.body))

    def item_links(self, post):
        return [{"href": self.item_id(post)}]

    def item_authors(self, post):
        return [{"name": post.author.username}]

class BlogFeedAll(BasePostFeed):

    def feed_id(self):
        return "http://%s/feeds/posts/all/" % Site.objects.get_current().domain

    def feed_title(self):
        return "Blog post feed for all users"

    def feed_updated(self):
        qs = Post.objects.all()
        # We return an arbitrary date if there are no results, because there
        # must be a feed_updated field as per the Atom specifications, however
        # there is no real data to go by, and an arbitrary date can be static.
        if qs.count() == 0:
            return datetime(year=2008, month=7, day=1)
        return qs.latest("created_at").created_at

    def feed_links(self):
        absolute_url = reverse("blog_list_all")
        complete_url = "http://%s%s" % (
            Site.objects.get_current().domain,
            absolute_url,
        )
        return ({"href": complete_url},)

    def items(self):
        return Post.objects.order_by("-created_at")[:ITEMS_PER_FEED]

class BlogFeedUser(BasePostFeed):

    def get_object(self, params):
        return get_object_or_404(User, username=params[0].lower())

    def feed_id(self, user):
        return "http://%s/feeds/posts/only/%s/" % (
            Site.objects.get_current().domain,
            user.username,
        )

    def feed_title(self, user):
        return "Blog post feed for user %s" % user.username

    def feed_updated(self, user):
        qs = Post.objects.filter(author=user)
        # We return an arbitrary date if there are no results, because there
        # must be a feed_updated field as per the Atom specifications, however
        # there is no real data to go by, and an arbitrary date can be static.
        if qs.count() == 0:
            return datetime(year=2008, month=7, day=1)
        return qs.latest("created_at").created_at

    def feed_links(self, user):
        absolute_url = reverse("blog_list_user", kwargs={
            "username": user.username
        })
        complete_url = "http://%s%s" % (
            Site.objects.get_current().domain,
            absolute_url,
        )
        return ({"href": complete_url},)

    def items(self, user):
        return Post.objects.filter(
            author = user
        ).order_by("-created_at")[:ITEMS_PER_FEED]


text: test to weather


text:
if (typeof module !== "undefined") {
  module.exports = ZeroClipboard;
} else {
  window.ZeroClipboard = ZeroClipboard;
}

})();


text: var dependencies={include:''};


text:
package info.naiv.lab.java.jmt.enumgen.maven.plugin;

import com.google.common.base.Objects;
import lombok.Builder;
import lombok.Value;

/**
 *
 * @author enlo
 */
@Builder
@Value
public class EnumEntry implements Comparable<EnumEntry> {

    public static EnumEntry forEnumSource(String name, String fieldName, String value, String comment) {
        return builder().name(name)
                .comment(comment)
                .fieldName(fieldName.toUpperCase().replaceAll("[\\.\\-]", "_"))
                .value(value)
                .build();
    }

    public static EnumEntry forProperties(String name, String value, String fieldPrefix) {
        return builder().name(name)
                .comment(value)
                .fieldName(Objects.firstNonNull(fieldPrefix, "")
                        + name.toUpperCase().replaceAll("[\\.\\-]", "_"))
                .value(name)
                .build();
    }

    String comment;
    String fieldName;
    String name;
    String value;

    @Override
    public int compareTo(EnumEntry o) {
        return name.compareTo(o.name);
    }

}


text:
@class AutofillPopupViewCocoa;
@class NSWindow;

namespace autofill {

class AutofillPopupViewDelegate;

class AutofillPopupViewCocoaDelegate {
 public:
  // Returns the bounds of the item at |index| in the popup, relative to
  // the top left of the popup.
  virtual gfx::Rect GetRowBounds(size_t index) = 0;

  // Gets the resource value for the given resource, returning -1 if the
  // resource isn't recognized.
  virtual int GetIconResourceID(const base::string16& resource_name) = 0;
};

// Mac implementation of the AutofillPopupView interface.
// Serves as a bridge to an instance of the Objective-C class which actually
// implements the view.
class AutofillPopupViewBridge : public AutofillPopupView,
                                public AutofillPopupViewCocoaDelegate {
 public:
  explicit AutofillPopupViewBridge(AutofillPopupController* controller);

  // AutofillPopupViewCocoaDelegate implementation.
  gfx::Rect GetRowBounds(size_t index) override;
  int GetIconResourceID(const base::string16& resource_name) override;

 private:
  ~AutofillPopupViewBridge() override;

  // AutofillPopupView implementation.
  void Hide() override;
  void Show() override;
  void InvalidateRow(size_t row) override;
  void UpdateBoundsAndRedrawPopup() override;

  // Set the initial bounds of the popup, including its placement.
  void SetInitialBounds();

  // The native Cocoa view.
  base::scoped_nsobject<AutofillPopupViewCocoa> view_;

  AutofillPopupController* controller_;  // Weak.

  DISALLOW_COPY_AND_ASSIGN(AutofillPopupViewBridge);
};

}  // namespace autofill

#endif  // CHROME_BROWSER_UI_COCOA_AUTOFILL_AUTOFILL_POPUP_VIEW_BRIDGE_H_


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="15dp"
    android:background="@drawable/background_card"
    android:gravity="center"
    android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_margin="30dp"
        android:text="Lunch Token"
        android:textSize="30sp"
        android:textStyle="bold" />

    <Button
        android:id="@+id/btn_token"
        android:layout_width="150dp"
        android:layout_height="50dp"
        android:layout_margin="30dp"
        android:background="#FFC712"
        android:text="Token"
        android:textSize="30sp"
        android:textStyle="bold" />

</LinearLayout>


text:
using UnityEngine;
using System.Collections;

public class Music : MonoBehaviour {

	public static Music instance = null;
	public AudioSource audioSource;
	public static bool soundOn = true;

	private Sprite on;
	private Sprite off;

	void Awake()
	{
		if (instance != null && instance != this) {
			Destroy (this.gameObject);
			return;
		} else {
			instance = this;
		}
		DontDestroyOnLoad(this.gameObject);

	}

	void Start () {

		audioSource = GetComponent<AudioSource> ();
		audioSource.Play ();

	}

	public static void PlayMusic()
	{
		if(instance != null)
		instance.audioSource.Play ();
	}

	public static void StopMusic()
	{
		if(instance != null)
			instance.audioSource.Stop ();
	}

	public static void ToggleMusic()
	{
		soundOn = !soundOn;
		if (soundOn)
			PlayMusic ();

		else
			StopMusic ();

	}

}


text:
module Rengine
  class WorkResult
    attr_reader :work_request
    attr_reader :error
    attr_reader :output
    def initialize(work_request,result)
      if result.is_a? Exception
        @error=result
      else
        @output=result
      end
      @work_request=work_request
    end
  end
end


text:
<?php

namespace Google\Service\Calendar;

class Colors extends \Google\Model
{
  protected $calendarType = ColorDefinition::class;
  protected $calendarDataType = 'map';
  protected $eventType = ColorDefinition::class;
  protected $eventDataType = 'map';
  /**
   * @var string
   */
  public $kind;
  /**
   * @var string
   */
  public $updated;

  /**
   * @param ColorDefinition[]
   */
  public function setCalendar($calendar)
  {
    $this->calendar = $calendar;
  }
  /**
   * @return ColorDefinition[]
   */
  public function getCalendar()
  {
    return $this->calendar;
  }
  /**
   * @param ColorDefinition[]
   */
  public function setEvent($event)
  {
    $this->event = $event;
  }
  /**
   * @return ColorDefinition[]
   */
  public function getEvent()
  {
    return $this->event;
  }
  /**
   * @param string
   */
  public function setKind($kind)
  {
    $this->kind = $kind;
  }
  /**
   * @return string
   */
  public function getKind()
  {
    return $this->kind;
  }
  /**
   * @param string
   */
  public function setUpdated($updated)
  {
    $this->updated = $updated;
  }
  /**
   * @return string
   */
  public function getUpdated()
  {
    return $this->updated;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(Colors::class, 'Google_Service_Calendar_Colors');


text:
hiqdev/yii2-asset-octicons changelog
------------------------------------

## Under development

- Added basics

## Development started 2015-09-09


text:
steal('can/event/namespace', 'can/test', 'steal-qunit', function () {
	module('can/event/namespace');

	test('Event with namespaces', function() {
		var node = can.extend({ name: 'root' }, can.event),
			count = 0;
			fn = function(ev) {
				++count;
			};

		count = 0;
		node.bind('action.namespace', fn);
		node.dispatch('action');
		equal(count, 1, 'Action with namespace fired');

		count = 0;
		node.dispatch('action');
		node.unbind('action.namespace', fn);
		node.dispatch('action');
		equal(count, 1, 'Action with namespace not fired after unbind');

		count = 0;
		node.bind('action.namespace', fn);
		node.dispatch('action');
		node.unbind('.namespace', fn);
		node.dispatch('action');
		equal(count, 1, 'Action unbound by namespace');
	});

	test('Events with multiple namespaces', function() {
		var node = can.extend({ name: 'root' }, can.event),
			count = 0;
			fn = function(ev) {
				++count;
			};

		count = 0;
		node.bind('action.namespace', fn);
		node.dispatch('action');
		node.unbind('.namespace', fn);
		node.dispatch('action');
		equal(count, 1, 'Action unbound by namespace');

		count = 0;
		node.bind('action.namespace.another.other', fn);
		node.dispatch('action');
		equal(count, 1, 'Action with multiple namespaces fired');
		node.unbind('.another', fn);
		node.dispatch('action');
		equal(count, 1, 'Any matching namespace should remove the event');
		node.bind('action.namespace.another.other', fn);
		node.unbind('action');
		node.dispatch('action');
		equal(count, 1, 'Normal event should remove listeners');

		count = 0;
		node.bind('action.namespace', fn);
		node.bind('other.namespace', fn);
		node.dispatch('action');
		node.dispatch('other');
		node.unbind('.namespace');
		node.dispatch('action');
		node.dispatch('action');
		node.dispatch('other');
		node.dispatch('other');
		equal(count, 2, 'Removing by namespace should remove all events assigned to it');

		count = 0;
		node.bind('action.namespace.another', fn);
		node.unbind('.namespace.other');
		node.dispatch('action');
		equal(count, 1, 'All namespaces much match when unbinding, if present');
	});
});


text:
class AddCreatorsToAccessPermissions < ActiveRecord::Migration
  def change
    add_column :access_permissions, :creator_id, :integer, :default => nil
  end
end


text:
gem build ghunit.gemspec
gem install ghunit


text:
<?php

/**
 * Sniff for methods that are required to call the parent method.
 *
 * @package WordPoints_Dev_Lib\PHPCS
 * @since 2.2.0
 */

use PHP_CodeSniffer\Sniffs\Sniff;
use PHP_CodeSniffer\Util\Tokens;

/**
 * Warns about methods not calling the parent method when they are supposed to.
 *
 * @since 2.2.0
 */
class WordPoints_Sniffs_PHP_RequiredParentMethodCallSniff implements Sniff {

	/**
	 * A list of methods whose parents are required to be called.
	 *
	 * @since 2.2.0
	 *
	 * @var string[]
	 */
	public $methods = array(
		'setUp'              => true,
		'tearDown'           => true,
		'setUpBeforeClass'   => true,
		'tearDownAfterClass' => true,
	);

	/**
	 * @since 2.2.0
	 */
	public function register() {
		return array( T_FUNCTION );
	}

	/**
	 * @since 2.0.0
	 */
	public function process( PHP_CodeSniffer\Files\File $phpcsFile, $stackPtr ) {

		$tokens = $phpcsFile->getTokens();
		$token  = $tokens[ $stackPtr ];

		// Skip function without body.
		if ( isset( $token['scope_opener'] ) === false ) {
			return;
		}

		// Get function name.
		$methodName = $phpcsFile->getDeclarationName( $stackPtr );

		// If this method isn't required to call it's parent, bail out.
		if ( ! isset( $this->methods[ $methodName ] ) ) {
			return;
		}

		$next = ++$token['scope_opener'];
		$end  = --$token['scope_closer'];

		for ( ; $next <= $end; ++$next ) {

			if ( T_PARENT !== $tokens[ $next ]['code'] ) {
				continue;
			}

			// Find next non empty token index, should be double colon.
			$next = $phpcsFile->findNext(
				Tokens::$emptyTokens
				, $next + 1
				, null
				, true
			);

			// Skip for invalid code.
			if ( false === $next || T_DOUBLE_COLON !== $tokens[ $next ]['code'] ) {
				continue;
			}

			// Find next non empty token index, should be the function name.
			$next = $phpcsFile->findNext(
				Tokens::$emptyTokens
				, $next + 1
				, null
				, true
			);

			// If this is the method we are looking for, we're done.
			if ( false !== $next && $tokens[ $next ]['content'] === $methodName ) {
				return;
			}
		}

		// We didn't find a call to the parent method.
		$phpcsFile->addError(
			'Missing call to parent::%s()'
			, $stackPtr
			, 'Missing'
			, $methodName
		);
	}
}

// EOF


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".packagehunter.PackageHunterMain"
    style="@style/AppTheme"
    android:background="?attr/nav_drawer_bg_color">

  <include
      android:id="@+id/toolbar"
      layout="@layout/toolbar_default" />

  <LinearLayout
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:layout_marginTop="?attr/actionBarSize"
      android:orientation="vertical" >

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/relative"
        android:elevation="4dp"
        android:translationZ="3dp">
      <LinearLayout
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:orientation="horizontal"
          android:background="?attr/colorAccent">
        <ImageView
            android:id="@+id/imgvw_icn"
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:layout_gravity="center"
            android:scaleType="fitCenter"
            android:layout_marginLeft="10dp" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:layout_marginBottom="14dp">
          <TextView
              android:id="@+id/txtvw_pkgname"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:layout_marginTop="6dp"
              android:background="@drawable/bg1_txt"
              tools:text="Package Name"
              android:layout_marginLeft="16dp"
              android:paddingLeft="3dp"
              android:paddingRight="3dp" />
          <TextView
              android:id="@+id/txtvw_vname"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:layout_marginTop="6dp"
              android:background="@drawable/bg2_txt"
              tools:text="0.0"
              android:layout_marginLeft="16dp"
              android:paddingRight="3dp"
              android:paddingLeft="3dp" />
          <TextView
              android:id="@+id/txtvw_vc"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:layout_marginTop="6dp"
              android:background="@drawable/bg3_txt"
              tools:text="10"
              android:layout_marginLeft="16dp"
              android:paddingLeft="3dp"
              android:paddingRight="3dp" />

          <TextView
              android:id="@+id/txtvw_firsttime"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:layout_marginTop="6dp"
              android:background="@drawable/bg3_txt"
              tools:text="10"
              android:layout_marginLeft="16dp"
              android:paddingLeft="3dp"
              android:paddingRight="3dp" />

          <TextView
              android:id="@+id/txtvw_lastupdated"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:layout_marginTop="6dp"
              android:background="@drawable/bg3_txt"
              tools:text="10"
              android:layout_marginLeft="16dp"
              android:paddingLeft="3dp"
              android:paddingRight="3dp" />
        </LinearLayout>
      </LinearLayout>
    </RelativeLayout>
    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv_detaillist"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="5dp" />

  </LinearLayout>
</RelativeLayout>


text:
using System;
using System.Collections.Generic;
using Newtonsoft.Json;

namespace PayStack.Net
{
    public class ListBanks
    {
        public class Datum
        {

            [JsonProperty("name")]
            public string Name { get; set; }

            [JsonProperty("slug")]
            public string Slug { get; set; }

            [JsonProperty("code")]
            public string Code { get; set; }

            [JsonProperty("longcode")]
            public string Longcode { get; set; }

            [JsonProperty("gateway")]
            public string Gateway { get; set; }

            [JsonProperty("active")]
            public bool Active { get; set; }

            [JsonProperty("is_deleted")]
            public object IsDeleted { get; set; }

            [JsonProperty("id")]
            public int Id { get; set; }

            [JsonProperty("createdAt")]
            public DateTime CreatedAt { get; set; }

            [JsonProperty("updatedAt")]
            public DateTime UpdatedAt { get; set; }
        }
    }

    public class ListBanksResponse : HasRawResponse, IApiResponse
    {

        [JsonProperty("status")]
        public bool Status { get; set; }

        [JsonProperty("message")]
        public string Message { get; set; }

        [JsonProperty("data")]
        public IList<ListBanks.Datum> Data { get; set; }
    }
}


text:
package org.apache.ivy.osgi.repo;

import java.net.URI;
import java.text.ParseException;
import java.util.Iterator;

import org.apache.ivy.osgi.core.BundleInfo;
import org.apache.ivy.osgi.core.ExecutionEnvironmentProfileProvider;
import org.apache.ivy.osgi.core.ManifestParser;
import org.apache.ivy.util.Message;

public class BundleRepoDescriptor extends RepoDescriptor {

    private String name;

    private Long lastModified;

    public BundleRepoDescriptor(URI baseUri, ExecutionEnvironmentProfileProvider profileProvider) {
        super(baseUri, profileProvider);
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setLastModified(Long lastModified) {
        this.lastModified = lastModified;
    }

    public Long getLastModified() {
        return lastModified;
    }

    public void populate(Iterator/* <ManifestAndLocation> */it) {
        while (it.hasNext()) {
            ManifestAndLocation manifestAndLocation = (ManifestAndLocation) it.next();
            try {
                BundleInfo bundleInfo = ManifestParser.parseManifest(manifestAndLocation
                        .getManifest());
                bundleInfo.setUri(manifestAndLocation.getUri());
                addBundle(bundleInfo);
            } catch (ParseException e) {
                Message.error("Rejected " + manifestAndLocation.getUri() + ": " + e.getMessage());
            }
        }
    }

}


text:
`LRCache` aims to provide a simple yet fast and scalable two-layer caching solution. It exposes only simple `Set` and `Get` functions that cache items in-memory in an `LRU-cache` implementation (using [golang-lru](https://github.com/hashicorp/golang-lru)). Hot items are fetched from the in-memory `LRU-cache`, while less-hot items that are evicted from `LRU-cache` are fetched from `Redis` (using [Redigo](https://github.com/garyburd/redigo)). This offers speed on one hand (hot items are grabbed from the in-memory `LRU-cache`) and scalability on the other hand (large data sets may be cached using a `Redis` server or cluster).

## Usage

Example (see [example/simple/main.go](https://github.com/streamrail/lrcache/blob/master/example/simple/main.go) for full runnable example): Set 10 elements in the cache. Since the `LRU-cache` size is set to 5 with a flag, we expect 5 elements in the `LRU-cache`, 5 evictions from `LRU-cache`, and 5 elements in `Redis`.

```go
func main() {
	cache, _ := lrcache.NewLRCache(*redisHost, *redisConnPoolSize, *redisPrefix, *lruSize)

	// set 10 elements in the cache. since the LRU size is set to 5,
	// we expect 5 elements in the lru, 5 evictions from lru, and 5 elements in redis
	for i := 0; i < 10; i++ {
		key := strconv.Itoa(i)
		value := i
		fmt.Printf("setting key %s with value %d. evicted stuff from cache? %v\n", key, value, cache.Set(key, value))
	}
	for i := 0; i < 10; i++ {
		result := cache.Get(strconv.Itoa(i))
		val, err := result.IntVal()
		if err == nil {
			if result.FromRedis() {
				fmt.Printf("value came from redis: %d\n", val)
			} else {
				fmt.Printf("value came from LRU: %d\n", val)
			}
		} else {
			fmt.Println(err.Error())
		}
	}
}

---- output ----
setting key 0 with value 0. evicted stuff from cache? false
setting key 1 with value 1. evicted stuff from cache? false
setting key 2 with value 2. evicted stuff from cache? false
setting key 3 with value 3. evicted stuff from cache? false
setting key 4 with value 4. evicted stuff from cache? false
setting key 5 with value 5. evicted stuff from cache? true
setting key 6 with value 6. evicted stuff from cache? true
setting key 7 with value 7. evicted stuff from cache? true
setting key 8 with value 8. evicted stuff from cache? true
setting key 9 with value 9. evicted stuff from cache? true
value came from redis: 0
value came from redis: 1
value came from redis: 2
value came from redis: 3
value came from redis: 4
value came from LRU: 5
value came from LRU: 6
value came from LRU: 7
value came from LRU: 8
value came from LRU: 9
```

## Using the cache with custom types (`interface` vs `gob`)

If you you know what type you have set in the cache, use the appropriate value getter (e.g. `Int32Val()`, `StringVal()`, etc.). Otherwise or if you have set your own custom type in the cache, you can get the raw value and parse it yourself. But, in this case, you would have to use the `FromRedis()` function (or the `IsGob()` function). This is because, before they could be stored on `Redis`, objects have to be  serialized to `gobs`, and when calling the `Get(key)` function, you do not know if the value was returned from the `LRU-cache` (where it is stored as an `interface` in memory) or from `Redis` (where it is stored as a gob) unless you call `FromRedis()`. Also, `LRCache` cannot perform the deserialization from `gob` to the custom `type` for you, since the `gob decoder` cannot decode a `gob` value to an `interface`.

Example: extract custom `type` from cache (see [example/custom_type/main.go](https://github.com/streamrail/lrcache/blob/master/example/custom_type/main.go) for full runnable example):

```go

type Person struct {
	Name string
	Age  int
}

func main() {
	cache, _ := lrcache.NewLRCache(*redisHost, *redisConnPoolSize, *redisPrefix, *lruSize)

	bob := &Person{Name: "Bob", Age: 21}
	sally := &Person{Name: "Alice", Age: 19}

	cache.Set("bob-key", bob)     // pushes bob-key to LRU
	cache.Set("alice-key", sally) // pushes bob-key out of LRU and into Redis, puts alice-key in LRU

	res1 := cache.Get("bob-key")
	res2 := cache.Get("alice-key")

	log.Println(ExtractCustomType(res1)) // from redis
	log.Println(ExtractCustomType(res2)) // from LRU

}

func ExtractCustomType(res *lrcache.LRCacheItem) (*Person, error) {
	if res.Error() != nil {
		return nil, res.Error()
	}
	if res.Value() == nil {
		return nil, nil
	}
	if !res.FromRedis() { // value from `LRU-cache`
		log.Printf("from LRU cache\n")
		if v, ok := res.Value().(*Person); ok {
			return v, nil
		} else {
			return nil, fmt.Errorf("result does not contain value *Person")
		}
	} else {
		log.Printf("from Redis cache\n")
		var decoded = new(Person)
		if gobVal, ok := res.Value().([]uint8); ok {
			dec := gob.NewDecoder(bytes.NewBuffer(gobVal))
			err := dec.Decode(decoded)
			if err != nil {
				return nil, err
			} else {
				return decoded, nil
			}
		} else {
			return nil, fmt.Errorf("expected result to contain gob but got other type")
		}
	}
}

---- output ----
from Redis cache:
&{Bob 21} <nil>
from LRU cache:
&{Alice 19} <nil>

```

## Pitfall when using `Set` with `LRCache`

When working with a "pure" `LRU-cache`, once an item gets evicted, you could not find that item in the cache anymore. This has thd downside of a cache miss, but it also has the upside of forcing you to re-insert the item into the `LRU-cache` in case you want it there. Re-insertions are common with `LRU-cache`. This constant re-insertion to the `LRU-cache` means that if an items was evicted in the past, yet suddenly it becomes a hot item that's been re-inserted and is now requested a lot, it will be returned from the in-memory `LRU-cache`.

In contrast, on `LRCache`, when you set an item with `Set`, there is more seldom a cache-miss because of an LRU eviction. If the `LRU-cache` evicted a cold item, that item may still be stored on the `Redis` cache and the `Get` method may be able to resolve it. This has the upside of good performance for all cache `Get` requests (there is never cache-miss as in the pure `LRU-cache` example above), however - the price we pay for this is that the in-memory `LRU-cache` component becomes less adaptive.

If an item that was evicted from `LRU-cache` is still returned from `Redis`, you won't need to re-insert the item to the in-memory `LRU-cache` (you can do it if you like, but `LRCache` won't do it for you). This means that an item that turned cold and got evicted from the `LRU-cache` may sometime in the future become hot again, yet it will still be returned from `Redis` (unless you explicitly call the `Set` method for this item) and not in-memory `LRU-cache` - until the item gets evicted from `Redis` as well.

## `Redis` config

For the reason depicted in the pitfall section, it is advised to use `LRCache` with `Redis` configured as an `LRU-cache` itself. Read more about [using Redis as an `LRU-Cache`](http://redis.io/topics/lru-cache) on the official `Redis` website.

This configuration works to guarantee that a cache-miss will be generated after an item is truly cold (i.e. not requested from neither the in-memory `LRU-cache` component nor the `Redis` component of `LRCache`).

## License
MIT (see [LICENSE](https://github.com/streamrail/lrcache/blob/master/LICENSE) file)


text:
<?php

require_once '../lib/Repository.php';

/**
 * Das UserRepository ist zuständig für alle Zugriffe auf die Tabelle "user".
 *
 * Die Ausführliche Dokumentation zu Repositories findest du in der Repository Klasse.
 */
class UserRepository extends Repository
{
    /**
     * Diese Variable wird von der Klasse Repository verwendet, um generische
     * Funktionen zur Verfügung zu stellen.
     */
    protected $tableName = 'user';

    /**
     * Erstellt einen neuen benutzer mit den gegebenen Werten.
     *
     * Das Passwort wird vor dem ausführen des Queries noch mit dem SHA1
     *  Algorythmus gehashed.
     *
     * @param $firstName Wert für die Spalte firstName
     * @param $lastName Wert für die Spalte lastName
     * @param $email Wert für die Spalte email
     * @param $password Wert für die Spalte password
     *
     * @throws Exception falls das Ausführen des Statements fehlschlägt
     */
    public function create($firstName, $lastName, $email)
    {
        $password = sha1($password);

        $query = "INSERT INTO $this->tableName (firstName, lastName, email) VALUES (?, ?, ?)";

        $statement = ConnectionHandler::getConnection()->prepare($query);
        $statement->bind_param('ssss', $firstName, $lastName, $email);

        if (!$statement->execute()) {
            throw new Exception($statement->error);
        }

        return $statement->insert_id;
    }
}


text:
package gov.hhs.fha.nhinc.fta;

import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.ejb.Stateless;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 *
 * @author dunnek
 */
@WebService()
@Stateless()
public class FTAService {
    private static Log log = LogFactory.getLog(FTAService.class);

    public FTAService() {
        log.info("FTA Service Starting.");
        this.start();
    }

    /**
     * Web service operation
     */
    @WebMethod(operationName = "start")
    public Boolean start() {
        boolean result = true;
        log.info("begin start()");
        try {
            FTATimer.startTimer();
        } catch (Exception ex) {
            result = false;
        }
        log.info("end start()");
        return result;
    }

    /**
     * Web service operation
     */
    @WebMethod(operationName = "stop")
    public Boolean stop() {
        FTATimer.stopTimer();

        return true;
    }

    @Override
    protected void finalize() throws Throwable {
        FTATimer.stopTimer();
        super.finalize(); // not necessary if extending Object.
    }
}


text:
require_rspec = if defined?(require_relative)
  lambda do |path|
    require_relative path
  end
else # for 1.8.7
  lambda do |path|
    require "rspec/#{path}"
  end
end

require 'set'
require 'time'
require 'rbconfig'

require_rspec['core/version']

require 'rspec/support/caller_filter'
require 'rspec/core/warnings'
require 'rspec/support/warnings'

require_rspec['core/flat_map']
require_rspec['core/filter_manager']
require_rspec['core/dsl']
require_rspec['core/reporter']

require_rspec['core/hooks']
require_rspec['core/memoized_helpers']
require_rspec['core/metadata']
require_rspec['core/pending']
require_rspec['core/formatters']
require_rspec['core/ordering']

require_rspec['core/world']
require_rspec['core/configuration']
require_rspec['core/option_parser']
require_rspec['core/configuration_options']
require_rspec['core/command_line']
require_rspec['core/runner']
require_rspec['core/example']
require_rspec['core/shared_example_group/collection']
require_rspec['core/shared_example_group']
require_rspec['core/example_group']

module RSpec
  autoload :SharedContext, 'rspec/core/shared_context'

  # @private
  def self.wants_to_quit
  # Used internally to determine what to do when a SIGINT is received
    world.wants_to_quit
  end

  # @private
  # Used internally to determine what to do when a SIGINT is received
  def self.wants_to_quit=(maybe)
    world.wants_to_quit=(maybe)
  end

  # @private
  # Internal container for global non-configuration data
  def self.world
    @world ||= RSpec::Core::World.new
  end

  # @private
  # Used internally to set the global object
  def self.world=(new_world)
    @world = new_world
  end

  # @private
  # Used internally to ensure examples get reloaded between multiple runs in
  # the same process.
  def self.reset
    @world = nil
    @configuration = nil
  end

  # Returns the global [Configuration](RSpec/Core/Configuration) object. While you
  # _can_ use this method to access the configuration, the more common
  # convention is to use [RSpec.configure](RSpec#configure-class_method).
  #
  # @example
  #     RSpec.configuration.drb_port = 1234
  # @see RSpec.configure
  # @see Core::Configuration
  def self.configuration
    if block_given?
      RSpec.warn_deprecation <<-WARNING

*****************************************************************
DEPRECATION WARNING

* RSpec.configuration with a block is deprecated and has no effect.
* please use RSpec.configure with a block instead.

Called from #{CallerFilter.first_non_rspec_line}
*****************************************************************

WARNING
    end
    @configuration ||= RSpec::Core::Configuration.new
  end

  # @private
  # Used internally to set the global object
  def self.configuration=(new_configuration)
    @configuration = new_configuration
  end

  # Yields the global configuration to a block.
  # @yield [Configuration] global configuration
  #
  # @example
  #     RSpec.configure do |config|
  #       config.add_formatter 'documentation'
  #     end
  # @see Core::Configuration
  def self.configure
    yield configuration if block_given?
  end

  # @private
  # Used internally to clear remaining groups when fail_fast is set
  def self.clear_remaining_example_groups
    world.example_groups.clear
  end

  # The example being executed.
  #
  # The primary audience for this method is library authors who need access
  # to the example currently being executed and also want to support all
  # versions of RSpec 2 and 3.
  #
  # @example
  #
  #     RSpec.configure do |c|
  #       # context.example is deprecated, but RSpec.current_example is not
  #       # available until RSpec 3.0.
  #       fetch_current_example = RSpec.respond_to?(:current_example) ?
  #         proc { RSpec.current_example } : proc { |context| context.example }
  #
  #       c.before(:each) do
  #         example = fetch_current_example.call(self)
  #
  #         # ...
  #       end
  #     end
  #
  def self.current_example
    Thread.current[:_rspec_current_example]
  end

  # Set the current example being executed.
  # @api private
  def self.current_example=(example)
    Thread.current[:_rspec_current_example] = example
  end

  # @private
  def self.windows_os?
    RbConfig::CONFIG['host_os'] =~ /cygwin|mswin|mingw|bccwin|wince|emx/
  end

  module Core
    # @private
    # This avoids issues with reporting time caused by examples that
    # change the value/meaning of Time.now without properly restoring
    # it.
    class Time
      class << self
        define_method(:now, &::Time.method(:now))
      end
    end

    # @private path to executable file
    def self.path_to_executable
      @path_to_executable ||= File.expand_path('../../../exe/rspec', __FILE__)
    end
  end

  MODULES_TO_AUTOLOAD = {
    :Matchers     => "rspec/expectations",
    :Expectations => "rspec/expectations",
    :Mocks        => "rspec/mocks"
  }

  def self.const_missing(name)
    # Load rspec-expectations when RSpec::Matchers is referenced. This allows
    # people to define custom matchers (using `RSpec::Matchers.define`) before
    # rspec-core has loaded rspec-expectations (since it delays the loading of
    # it to allow users to configure a different assertion/expectation
    # framework). `autoload` can't be used since it works with ruby's built-in
    # require (e.g. for files that are available relative to a load path dir),
    # but not with rubygems' extended require.
    #
    # As of rspec 2.14.1, we no longer require `rspec/mocks` and
    # `rspec/expectations` when `rspec` is required, so we want
    # to make them available as an autoload. For more info, see:
    require MODULES_TO_AUTOLOAD.fetch(name) { return super }
    ::RSpec.const_get(name)
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ Copyright 2015 Hippo Seven
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingLeft="@dimen/keyline_margin_horizontal"
    android:paddingRight="@dimen/keyline_margin_horizontal">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:gravity="center_vertical"
            android:textColor="?android:attr/textColorPrimary"
            android:textSize="@dimen/text_little_small"
            android:text="@string/forum_name"/>

        <EditText
            android:id="@+id/name"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="5"
            android:textColor="?android:attr/textColorPrimary"
            android:inputType="text"
            android:singleLine="true"
            android:imeOptions="actionNext"
            android:nextFocusDown="@+id/id"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:gravity="center_vertical"
            android:textColor="?android:attr/textColorPrimary"
            android:textSize="@dimen/text_little_small"
            android:text="@string/forum_id"/>

        <EditText
            android:id="@+id/id"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="5"
            android:textColor="?android:attr/textColorPrimary"
            android:inputType="text"
            android:singleLine="true"/>

    </LinearLayout>

</LinearLayout>


text:
namespace feather {

Status::Status(StatusCode code, const std::string& msg, int16_t posix_code) {
  assert(code != StatusCode::OK);
  const uint32_t size = msg.size();
  char* result = new char[size + 7];
  memcpy(result, &size, sizeof(size));
  result[4] = static_cast<char>(code);
  memcpy(result + 5, &posix_code, sizeof(posix_code));
  memcpy(result + 7, msg.c_str(), msg.size());
  state_ = result;
}

const char* Status::CopyState(const char* state) {
  uint32_t size;
  memcpy(&size, state, sizeof(size));
  char* result = new char[size + 7];
  memcpy(result, state, size + 7);
  return result;
}

std::string Status::ToString() const {
  std::string result(CodeAsString());
  if (state_ == NULL) {
    return result;
  }

  result.append(": ");

  uint32_t length;
  memcpy(&length, state_, sizeof(length));
  result.append(state_ + 7, length);
  int16_t posix = posix_code();
  if (posix != -1) {
    char buf[64];
    snprintf(buf, sizeof(buf), " (error %d)", posix);
    result.append(buf);
  }
  return result;
}

std::string Status::CodeAsString() const {
  if (state_ == NULL) {
    return "OK";
  }

  const char* type = NULL;
  switch (code()) {
    case StatusCode::OK:
      type = "OK";
      break;
    case StatusCode::OutOfMemory:
      type = "Out of memory";
      break;
    case StatusCode::KeyError:
      type = "Key error";
      break;
    case StatusCode::Invalid:
      type = "Invalid";
      break;
    case StatusCode::IOError:
      type = "IO error";
      break;
    case StatusCode::NotImplemented:
      type = "Not implemented";
      break;
  }
  return std::string(type);
}

int16_t Status::posix_code() const {
  if (state_ == NULL) {
    return 0;
  }
  int16_t posix_code;
  memcpy(&posix_code, state_ + 5, sizeof(posix_code));
  return posix_code;
}

} // namespace feather


text:
layout: post
title: CSS Design
category: Tech
---

When learning CSS I found myself asking what the heck is a class, an ID, and why should I care? In this blog post I am going to expalin the difference between ID's, Classes, and when you should use each.

A class is a group of elements that are the same or similar. The most important thing to remember about classes is that they are not unique. This means that you can use the same class on multiple elements and you can have as many elements as you want in a class.

An ID is a singular identifier of one HTML tag. The most important thing to remember about ID's is that they are unique. Each element can have only one ID and each page can only have one element with that ID. Your code will not pass validation if you use the same ID on more than one element. One of the main benefits of using ID's is that they can be accessed directly through a hash value.

So when should you use each one? Any time you want to apply the same styling to multiple elements you want to use a class.

Let's use our Berkshire website as an example. Take a look at the heading of the page:

The heading to the web page is unique to this page. You are not going to want to have this element repeated so an ID makes sense here. I use an id to create a container for the entire heading and add all of the characteristics that are shared within the heading.

Now I want you to focus on the top line. Notice how the B and the H are larger than the rest of the font? This is a good example on when you would want to use a class since this is a style that will be repeated.

Any time I want to make text twice as big as normal I can use this class to style the element.

So what does my HTML code look like?

Notice how I am able to call boldbluetext class (I admit I probably should have named this something better) twice. Once for the H and again for the B.

I hope this blog post was able to help you understand the differences between classes and ids a little bit better. If you are still confused, try to write a blog post explaining the differences and best practices because I know it helped me to understand them a lot better.

Thanks for reading.


text:
//-----------------------------------------------------------------------
// <copyright file="ReadWriteAggregator.cs" company="Akka.NET Project">
//     Copyright (C) 2009-2016 Lightbend Inc. <http://www.lightbend.com>
//     Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------

using Akka.Actor;
using System;
using System.Collections.Immutable;
using System.Linq;
using Akka.Event;
using Akka.Util;

namespace Akka.DistributedData
{
    internal abstract class ReadWriteAggregator : ActorBase
    {
        protected sealed class SendToSecondary
        {
            public static readonly SendToSecondary Instance = new SendToSecondary();
            private SendToSecondary() { }
        }

        private const int MaxSecondaryNodes = 10;

        protected TimeSpan Timeout { get; }
        protected IImmutableSet<Address> Nodes { get; }
        protected IImmutableSet<Address> Unreachable { get; }
        protected IImmutableSet<Address> Reachable { get; }

        private readonly ICancelable _sendToSecondarySchedule;
        private readonly ICancelable _timeoutSchedule;

        private ILoggingAdapter _log;

        protected ILoggingAdapter Log => _log ?? (_log = Context.GetLogger());

        protected abstract int DoneWhenRemainingSize { get; }

        private readonly Lazy<Tuple<IImmutableSet<Address>, IImmutableSet<Address>>> _primaryAndSecondaryNodes;

        protected IImmutableSet<Address> PrimaryNodes => _primaryAndSecondaryNodes.Value.Item1;
        protected IImmutableSet<Address> SecondaryNodes => _primaryAndSecondaryNodes.Value.Item2;

        protected IImmutableSet<Address> Remaining;

        protected ReadWriteAggregator(IImmutableSet<Address> nodes, IImmutableSet<Address> unreachable, TimeSpan timeout)
        {
            Timeout = timeout;
            Nodes = nodes;
            Unreachable = unreachable;
            Reachable = nodes.Except(unreachable);
            Remaining = Nodes;
            _sendToSecondarySchedule = Context.System.Scheduler.ScheduleTellOnceCancelable((int)Timeout.TotalMilliseconds / 5, Self, SendToSecondary.Instance, Self);
            _timeoutSchedule = Context.System.Scheduler.ScheduleTellOnceCancelable(Timeout, Self, ReceiveTimeout.Instance, Self);
            _primaryAndSecondaryNodes = new Lazy<Tuple<IImmutableSet<Address>, IImmutableSet<Address>>>(() =>
            {
                var primarySize = Nodes.Count - DoneWhenRemainingSize;
                if(primarySize >= nodes.Count)
                {
                    return Tuple.Create(nodes, (IImmutableSet<Address>)ImmutableHashSet<Address>.Empty);
                }
                else
                {
                    var n = Nodes.OrderBy(x => ThreadLocalRandom.Current.Next()).ToArray();
                    var p = n.Take(primarySize).ToImmutableHashSet();
                    var s = n.Skip(primarySize).Take(MaxSecondaryNodes).ToImmutableHashSet();
                    return Tuple.Create((IImmutableSet<Address>)p, (IImmutableSet<Address>)s);
                }
            });
        }

        public static int CalculateMajorityWithMinCapacity(int minCapacity, int numberOfNodes)
        {
            if (numberOfNodes <= minCapacity) return numberOfNodes;

            return Math.Max(minCapacity, numberOfNodes / 2 + 1);
        }

        protected override void PostStop()
        {
            _sendToSecondarySchedule.Cancel();
            _timeoutSchedule.Cancel();
        }

        protected virtual ActorSelection Replica(Address address)
        {
            return Context.ActorSelection(Context.Parent.Path.ToStringWithAddress(address));
        }
    }
}


text:
package org.kaazing.gateway.management.session;

public class FullManagementSessionStrategyTest extends CollectOnlyManagementSessionStrategyTest {

    protected ManagementSessionStrategy getManagementSessionStrategy() {
        return new FullManagementSessionStrategy();
    }

}


text:
function [slopeOutput] = SlopeRInverse(Albedos, ConvStruct)
%This is the entire function:
%
%function [slopeOutput] = SlopeRInverse(Albedos, ConvStruct)
%slopeOutput = 1./(slopeOfReflectanceCurve2(Albedos,ConvStruct));
%end

slopeOutput = 1./(slopeOfReflectanceCurve2(Albedos,ConvStruct));
end