text:
<?php
/**
 * Online Web Application Builder Classes
 * @package 	OWAB
 */
/**
 * ConfigTool
 *
 * Part of OWAB (Online Web Application Builder) class set.
 *
 * ConfigTool reads normal text file to get all name value pairs, that are ment
 * to use on anykind of php application. In addition to read files, separate comments,
 * automatic variable type scanning through prefix in keys, ConfigTool can be used to
 * add, edit and delete key value pairs and save them to the file. Even new files can be
 * created from the scratch or based on earlier configuration text files.
 *
 * One additional usage with the class is to get language specific information from
 * the external text file. Then you can make straight object references to the
 * variables. Please see language_example.php for more information
 *
 * Special features
 *
 * By starting key name in a config.txt file with one of the five predefined prefixes
 * user can make automatic key conversion to different data types. Five prefixes are:
 * b_ like boolean, s_ like string, a_ like array, d_ like double and i_ like integer.
 *
 * {@internal	Now, if AUTOBOOLEAN, AUTOSTRING, AUTOARRAY, AUTODOUBLE and AUTOINTEGER
 * are set true in field variables (as they are by default), class converts the value
 * accordant to the key to proper data type.}}
 *
 * Normally all values are in string format on text file.
 * With boolean you can use one of the four values to get boolean work on automatic
 * conversion: true/false, on/off, yes/no, 1/0, y/n. So use these values on a text file.
 * More about configuration file format is described on {@link Config_definitions.txt} file.
 * Commenting is also discussed there more precisely.
 *
 * To debug and check key value pair, user can use getConfigLines() method to get
 * an array presentation of all lines with or without comments.
 *
 * Here is a small example, how to use this class:
 * <code>
 * <?php
 * include( "path/to/class/ConfigTool.php" );
 * $conf = new ConfigTool();
 * $conf->setConfigFromFile( "config.txt" );
 * // now you can get key value by direct reference
 * echo $conf->name_of_variable;
 * // to get all config lines for checking and debugging use:
 * $ar = $conf->getConfigLines();
 * // other useful methods are adding, updating, deleting and saving modified
 * // please see function descriptions, tests, and examples to know better, how
 * // they work.
 * ?>
 * </code>
 *
 * There are some known specialities on this class. First, it's not fully directed by OOP
 * form because it uses straight references to class field variables (not encapsulating).
 * And that's a main reason why developer must disable notice reporting if active in
 * php.ini. This is done either straight to the php.ini file (refer to http://www.php.net),
 * or by setting error_reporting( E_ERROR | E_WARNING | E_PARSE ) at runtime. Please see
 * further instructions from {@link http://www.php.net/error_reporting } and examples that
 * follows with the ConfigTool package {@link http://www.hmv-systems.fi/marko/ConfigTool/}.
 *
 * Another issue is to set write permission to the used configuration file(s). Procedure will
 * change on different servers and platforms, but mainly it's important to know, that many php
 * service providers has php in safe-mode. That means you cannot change/write to files from php
 * script. One possibility is to use ftp-tool/-application for file transfer, because most
 * ftp-tools has opportunity to change file permissions too. One good program is SmartFtp. You
 * may find program from {@link http://www.smartftp.com/ } and some figures at
 * {@link http://www.hmv-systems.fi/marko/ConfigTool/docs/smart.html }
 * how to change permissions with that program. Of course you will need ftp access to your
 * webserver to use it. But that's an another story if you don't have. ;)
 *
 * Changed from version 0.01:
 *
 * - Added AUTODOUBLE field variable and _toDouble type converter function. Added reserved word
 *   likewise.
 * - Set flags method has been changed from boolean parameter set to array set. This is
 *   !!!FUNDAMENTAL!!! change, so applications that changes flags with older method, has to be
 *   modified to newer proper one.
 * - Added _doubleToString(), _integerToString(), _checkType() & _checkAutoType() methods.
 * - Added setFileName() method for changing file name and creating new configuration file.
 * - Added _fileWrite() method for checking CHMOD at save and new file creation procedure. And
 *   that affects to ->
 * - Public saveToFile() method simplified to use above mentioned _fileWrite method!
 * - Added get() method to get safely variable name. This is due to notice error, if you refer to
 *   variable in object scope, if it's not defined. With get method you will get 'undefined' if
 *   variable does not exist
 *
 * @author		Marko Manninen <marko.manninen@hmv-systems.fi>
 * @copyright 	Copyright (c) 2004, Marko Manninen
 * @license		http://opensource.org/licenses/gpl-license.php GNU Public License
 * @version		0.02
 * @todo		- Allow multiline variables -> long string sentences
 * 				- Save config file to other known formats like XML, ini, apache,...
 * 				- Tie comments and their key value pairs together. Optimize & better comment code.
 * 				- Comments and variable add to the appropriate line!
 * @package 	OWAB
 */
class ConfigTool
{
	/**
	 * Empty spaces between key string and value string
	 * Thought too obvious to mention, = mark is between them
	 * @access private
	 * @var int
	 */
	var $INDENT;
	/**
	 * Path and name of the configuration file
	 * @access private
	 * @var string
	 */
	var $FILENAME;
	/**#@+
	 * @access private
	 */
	/**
	 * All lines in array that are read from the configuration file
	 * @var array
	 */
	var $LINES;
	/**
	 * Reserved words list, that will be checked runtime
	 * These words cannot be used in configuration file!
	 * @var array
	 */
	var $RESERVED_WORDS;
	/**#@-*/
	/**#@+
	 * @access private
	 */
	/**
	 * Convert key type to boolean if key starts with b_
	 * @var bool
	 */
	var $AUTOBOOL;

	/**
	 * Convert key type to integer if key starts with i_
	 * @var bool
	 */
	var $AUTOINTEGER;
	/**
	 * Convert key type to integer if key starts with i_
	 * @var bool
	 */
	var $AUTODOUBLE;
	/**
	 * Convert key type to array if key starts with a_
	 * @var bool
	 */
	var $AUTOARRAY;
	/**
	 * Convert key type to string if key starts with s_
	 * @var bool
	 */
	var $AUTOSTRING;
	/**#@-*/
	/**
	 * ConfigTool constructor
	 *
	 * @internal	Constructor inits the class fields with wanted values.
	 * Reserved words should be changed by the developer only.
	 */
	function ConfigTool()
	{
		$this->LINES				= array();
		$this->FILENAME				= "";
		// if any new fields are inserted to the class
		// the name of the filed must be added to the RESERVED_WORD list!
		$this->RESERVED_WORDS   	= array( "LINES", "INDENT", "FILENAME", "RESERVED_WORDS", "AUTOBOOL", "AUTOINTEGER", "AUTODOUBLE", "AUTOARRAY", "AUTOSTRING" );
		$this->INDENT				= 25;
		$this->setFlags();
	}//END OF CONSTRUCTOR ConfigTool

	/**
	 * Set flags
	 * Internal key type conversion is activated throught these values
	 * If defauld flags are to be changed, flags must be set before calling
	 * setConfigFromFile() method
	 * Changed to include parameter as array type. That way it's more easier to
	 * set flags, because you don't need to remember the order of parameters.
	 * Array should be form of associative name values. If some of autotype is
	 * missing, then former autotype value will remain. All types will be true
	 * as default!
	 * @access public
	 * @param array $pAuto
	 */
	function setFlags( $pAuto = array( "AUTOBOOL" => true, "AUTOINTEGER" => true, "AUTODOUBLE" => true, "AUTOARRAY" => true, "AUTOSTRING" => true ) )
	{
		if( isset( $pAuto['AUTOBOOL'] ) )
		$this->AUTOBOOL = $pAuto['AUTOBOOL'];
		if( isset( $pAuto['AUTOINTEGER'] ) )
		$this->AUTOINTEGER = $pAuto['AUTOINTEGER'];
		if( isset( $pAuto['AUTODOUBLE'] ) )
		$this->AUTODOUBLE = $pAuto['AUTODOUBLE'];
		if( isset( $pAuto['AUTOARRAY'] ) )
		$this->AUTOARRAY = $pAuto['AUTOARRAY'];
		if( isset( $pAuto['AUTOSTRING'] ) )
		$this->AUTOSTRING = $pAuto['AUTOSTRING'];
	}//END OF FUNCTION setFlags

	/**
	 * Get indent, the number of empty spaces between key name and value
	 * With this value, you can set configuration file variables to look
	 * visually better. That means, it's easier to read.
	 * @access public
	 * @return integer
	 */
	function getIndent()
	{
		return $this->INDENT;
	}//END OF FUNCTION getIndent

	/**
	 * Set indent, the number of empty spaces between key name and value
	 * With this value, you can set configuration file variables to look
	 * visually better. That means, it's easier to read.
	 * @access public
	 * @param string $pIndent
	 */
	function setIndent( $pIndent )
	{
		$this->INDENT = $pIndent;
	}//END OF FUNCTION setIndent

	/**
	 * Set file name of the configuration file. If file name is other than
	 * defined in setConfigFromFile( $pFileName ) and user is saving
	 * configuration variables with saveToFile(), then new file is tried to
	 * create.
	 * @see _fileWrite()
	 * @access public
	 * @param string $pfileName
	 */
	function setFileName( $pfileName )
	{
		$this->FILENAME = $pfileName;
	}//END OF FUNCTION getConfigLines

	/**
	 * cookies support
	 */
	function setCookiePath($path) {
		$this->cookiePath=$path;
	}
	function setCookieDomain($domain) {
		$this->cookieDomain=$domain;
	}
	function setCookieExpire($expire) {
		$this->cookieExpire=time() + $expire;
	}
	function isCookieEnabled() {
		return (isset($this->cookiePath)  && isset($this->cookieExpire)); // && isset($this->cookieDomain)
	}
	function setCookie( $pKey, $val )
	{
		$cookie_key= str_replace ( "." , "_" , $pKey);
		setcookie ( $cookie_key, $val, $this->cookieExpire, $this->cookiePath); //, $this->cookieDomain
	}

	/**
	 * Get configuration file name
	 * @access public
	 * @return string
	 */
	function getConfigFileName()
	{
		return $this->FILENAME;
	}//END OF FUNCTION getConfigFileName

	/**
	 * Get safely variable value. If variable is not defined, method will return 'undefined'
	 * @access public
	 * @param string $pKey
	 * @return mixed
	 */
	function get( $pKey, $checkCookie = false )
	{
		global $_COOKIE;
		if( $this->isDefined( $pKey ) ) {
			$cookie_key= str_replace ( "." , "_" , $pKey);
			if ($checkCookie && $this->isCookieEnabled() && isset($_COOKIE[$cookie_key])) {
				$val = $_COOKIE[$cookie_key];
			}
			else {
				$val = $this->$pKey;
			}
			if ($checkCookie && $this->isCookieEnabled())
			setcookie ( $cookie_key, $val, $this->cookieExpire, $this->cookiePath); //, $this->cookieDomain
		}
		else
		$val = "undefined";

		return $val;
	}//END OF FUNCTION get

	/**
	 * Get safely variable value. If variable is not defined, method will return default value
	 * @access public
	 * @param string $pKey
	 * @param string $default
	 * @return mixed
	 */

	function getDefault( $pKey, $default, $checkCookie = false)
	{
		if( $this->isDefined( $pKey ) ) {
			$cookie_key= str_replace ( "." , "_" , $pKey);
			if ($checkCookie && $this->isCookieEnabled() && isset($_COOKIE[$cookie_key])) {
				$val = $_COOKIE[$cookie_key];
			}
			else {
				$val = $this->$pKey;
			}
		} else {
			$val = $default;
		}
		if ($checkCookie && $this->isCookieEnabled())
		setcookie ( $cookie_key, $val, $this->cookieExpire, $this->cookiePath); //, $this->cookieDomain

		return $val;
	}//END OF FUNCTION get

	function set( $pKey, $val )
	{
		$this->$pKey = $val;
	}//END OF FUNCTION set

	/**
	 * Get configuration file lines.
	 * Method gives all the read lines from the configuration file. This is useful
	 * when debugging and checking all the name value pairs from the file. Additional parameter
	 * is used to get either all lines with comments, or lines without comments, or only comment lines.
	 * So parameters can be: 1. all 2. "" that is same as 3. configs 4. comment
	 * @access public
	 * @param string $pStr
	 * @return array
	 */
	function getConfigLines( $pStr = "" )
	{
		$temp_array = array();
		// return all rows
		if( $pStr == "all" )
		$temp_array = $this->LINES;
		// return only configuration rows
		$count = count( $this->LINES );
		if( $pStr == "configs" || $pStr == "" )
		{
			for( $i=0; $i < $count; $i++ )
			{
				//$val = ereg_replace( "[ 	]", "", $val );
				//$val = preg_replace( "/\s+/",	"", $val );

				//if ( eregi( "^[A-Z]", $this->LINES[$i] ) )
				if ( preg_match( "/^[A-Z]/i", $this->LINES[$i] ) )
				{
					array_push( $temp_array, $this->LINES[$i] );
				}
			}
		}
		// return only comment rows
		if( $pStr == "comments" )
		{
			for( $i=0; $i < $count; $i++ )
			{
				//if ( eregi( "^[A-Z]", $this->LINES[$i] ) )
				if ( preg_match( "/^[A-Z]/i", $this->LINES[$i] ) )
				{
					array_push( $temp_array, $this->LINES[$i] );
				}
			}
		}
		//
		return $temp_array;

	}//END OF FUNCTION getConfigLines

	/**
	 * Set configurations from the file
	 * This is the main method for getting and setting configuration variables
	 * Parameter given is the relative path and exact name of the configuration file
	 * Method checks if file name is specified, exists and contains valueable data.
	 * Comments are not counted as valuable data, so to keep method working, you need
	 * at least one name value pair in your configuration file. If everything goes well
	 * method returns boolean true. Else false is returned
	 *
	 * @access public
	 * @param string $pFileName
	 * @return bool
	 */
	function setConfigFromFile( $pFileName )
	{
		$this->FILENAME = $pFileName;
		//
		if( empty( $this->FILENAME  ) )
		{
			trigger_error( "File not specified!", E_USER_ERROR );
			return false;
		}
		if( !file_exists( $this->FILENAME  ) )
		{
			trigger_error( "File [" . $this->FILENAME . "] does not exist!", E_USER_ERROR );
			return false;
		}
		//
		$fp = fopen( $this->FILENAME, "r" );
		//
		if( ( !$fp) || ( empty( $fp ) ) )
		{
			trigger_error( "File opening error!", E_USER_ERROR );
			return false;
		}
		//
		while( !feof( $fp ) )
		{
			$line = fgets( $fp, 4096 );
			// trim lines from leading and trailing whitespaces and line-endings
			// now, if line starts with empty spaces and then follows with
			// variable name, config will be fine with that name, but remember
			// when you save back to file, the white space will be removed!
			$this->LINES[] = trim( $line );
		}
		//
		if( count( $this->getConfigLines() ) == 0 )
		{
			trigger_error( "Config file [" . $this->FILENAME . "] doesn't contain any key value pairs!", E_USER_WARNING );
			return false;
		}

		return $this->_parseConfig();
	}//END OF FUNCTION _setConfigFromFile

	/**
	 * Parse configuration lines from the LINES array
	 * If line start with alphabeth, it is tranported to the
	 * _parseConfig() method. Line that start with anything else
	 * like # / ; or other marks are not touched.
	 * If everything goes well, return true
	 * @see _setConfig()
	 * @access private
	 * @return boolean
	 */
	function _parseConfig()
	{
		$count = count( $this->LINES );
		for( $i = 0; $i < $count; $i++ )
		{
			// if line starts with a-Z alphabeth, it is supposed to be
			// a configuration name value pair
			//if ( eregi( "^[A-Z]", $this->LINES[$i] ) )
			if ( preg_match( "/^[A-Z]/i", $this->LINES[$i] ) )
			{
				$this->_setConfig( $this->LINES[$i] );
			}
		}
		return true;

	}//END OF FUNCTION _parseConfig

	/**
	 * Set configuration line. With this function line is separated to the
	 * key value pairs and class scope is filled with keys. Automatic key type
	 * concersion is made now. Return true, if everything is done right
	 * @see _parseConfig()
	 * @access private
	 * @param string $line
	 * @return boolean
	 */
	function _setConfig( $line )
	{
		// check, if there are any occurence of = marks in the line
		// at least one must be founded to make name value to work
		if( substr_count( $line, "=" ) < 1 )
		trigger_error( "There was no = -marks on the line: " . $line . " in file: " . $this->FILENAME . ". Please set at least one = -mark to separate name from value.", E_USER_WARNING );
		// separate line with =
		$pos = strpos($line, "=");
		$key = substr($line, 0, $pos);
		$val = substr($line, $pos+1);
		//list ( $key, $val ) = explode( "=", $line );
		// remove all white spaces from the key
		//$key = ereg_replace( "[ 	]",	"", $key );
		$key = preg_replace( "/\s+/",	"", $key );
		// remove white spaces before and after val
		$val = trim( $val );
		// then check '-marks at line start
		//if ( !ereg( "^'", $val ) && !preg_match( "/a_/i", $key ) )
		if ( !preg_match( "/^'/", $val ) && !preg_match( "/a_/i", $key ) )
		{
			//$val = ereg_replace( "[ 	]", "", $val );
			$val = preg_replace( "/\s+/",	"", $val );
		}
		else
		{
			// remove the leading ' and trailing '
			//$val = ereg_replace( "^'", "", $val );
			//$val = ereg_replace( "'$", "", $val );
			$val = preg_replace( "/^'/", "", $val );
			$val = preg_replace( "/'$/", "", $val );
		}
		// if key is not defined in the object scope
		// set up new key with new value
		if( !isset( $this->$key ) )
		{
			$this->$key	= $val;
		}
		else
		{
			// if dublicate configuration variable is found, lift user warning!
			trigger_error( "Initialization error. Dublicate variable (key: " . $key . ") was found from the configuration file! Please change the name in the file: " .$this->FILENAME, E_USER_WARNING );
		}
		if( $this->isReserved( $key ) )
		{
			trigger_error( "Key word is in reserved word list (key: " . $key . ")! Please change the name in the file: " .$this->FILENAME, E_USER_WARNING );
		}
		// check autotypes: boolean, integer, string and array
		$this->_checkAutoTypes( $key );
		// set key value pair to the debug array
		return true;
	}//END OF FUNCTION _setConfig

	/**
	 * Deletes key and value from the config array.
	 * Key name is checked, if it is defined in ConfigTool object. Then it's deleted.
	 * You must call saveToFile() method, if you need to save changes to the text file.
	 * @see saveToFile()
	 * @access public
	 * @param string $pKey
	 * @return boolean
	 */
	function deleteKey( $pKey )
	{
		if( $pKey == "" || $pKey == NULL )
		{
			trigger_error( "Delete error. Key was not defined.", E_USER_WARNING );
			return false;
		}
		if( $this->isReserved( $pKey ) )
		{
			trigger_error( "Delete error. Key is on reserved word list and cannot be deleted.", E_USER_WARNING );
			return false;
		}
		//
		$temp_array = array();
		//
		if( isset( $this->$pKey ) )
		{
			$ar = $this->getConfigLines( "all" );
			$count = count( $ar );
			for( $i = 0; $i < $count; $i++ )
			{
				// we need to check only lines, that may contain variables
				// comment lines are avoided. split function throws notice
				// if line doesn't contain any = mark
				$add = true;
				//if ( eregi( "^[A-Z]", $ar[$i] ) )
				if ( preg_match( "/^[A-Z]/i", $ar[$i] ) )
				{
					list ( $key, $val ) = explode( "=", $ar[$i] );
					//$key = ereg_replace( "[ 	]",	"", $key );
					$key = preg_replace( "/\s+/",	"", $key );
					if ( $key == $pKey )
					{
						$add = false;
					}
					else
					$add = true;
				}
				if( $add )
				{
					$temp_array[] = $ar[$i];
				}
			}
			$this->LINES = $temp_array;
			//
			unset( $this->$pKey );
			unset( $temp_array );
			return true;
		}
		else
		{
			trigger_error( "Delete error. Name ($pKey) is was not found from the configuration file ($this->FILENAME) and couldn't be deleted!", E_USER_WARNING );
			return false;
		}

	}//END OF FUNCTION deleteKey

	/**
	 * Saves all config variables to the file
	 * All variables and comments are saved to the file. File name is defined
	 * automatic when you construct the object and call setConfigFromFile( $pFileName )
	 * Name can be changed with setFileName() method. Also fi you make new configuration
	 * file from the scratch, you need to define file name with setFileName()
	 * @see setConfigFromFile( $pFileName )
	 * @see setFileName( $pFileName )
	 * @access public
	 * @return boolean
	 */
	function saveToFile()
	{
		$contents = $this->_arrayToString( $this->LINES, "\r\n" );
		// write to file prosess checks CHMOD and current file name
		if( $this->_fileWrite( 'w', $contents ) )
		return true;
		else
		{
			trigger_error( "Save operation failed!", E_USER_WARNING );
			return false;
		}
	}//END OF FUNCTION saveToFile

	/**
	 * Add key value pair.
	 *
	 * Method checks if key is already defined or is in reserved word list and then
	 * adds key value pair{@internal as a string presentation to the global line array}}.
	 * Long string values must be started and ended with ' marks!
	 * See config_definitions to learn, how to make ConfigTool compatible configurations
	 * name value pairs.
	 * You must call saveToFile() method, if you need to save changes to the text file.
	 * @see saveToFile()
	 * @access public
	 * @param string $pKey
	 * @param string $pVal
	 * @return boolean
	 */
	function addKeyValue( $pKey, $pVal )
	{
		if( $pKey == "" || $pKey == NULL )
		{
			trigger_error( "Add error. Key was not defined.", E_USER_WARNING );
			return false;
		}
		if( $this->isReserved( $pKey ) )
		{
			trigger_error( "Add error. Key is on reserved word list. Change the key name.", E_USER_WARNING );
			return false;
		}
		if( !$this->isDefined( $pKey ) )
		{
			$pVal = $this->_checkType( $pKey, $pVal );
			$line = $pKey . str_pad( " ", $this->INDENT - strlen( $pKey )  ) . " = " . $pVal;
			array_push( $this->LINES, $line );
			// if value starts with ', remove them from object value
			// however, ' marks are left in array, because
			// array is saved to the file, and long strings
			// must be surrounded by ' marks to work properly
			//if ( ereg( "^'", $pVal ) )
			if ( preg_match( "/^'/", $pVal ) )
			{
				//$pVal = ereg_replace( "^'", "", $pVal );
				//$pVal = ereg_replace( "'$", "", $pVal );
				$pVal = preg_replace( "/^'/", "", $pVal );
				$pVal = preg_replace( "/'$/", "", $pVal );
			}
			$this->$pKey = $pVal;
			$this->_checkAutoTypes( $pKey );
			return true;
		}
		else
		{
			trigger_error( "Add error. Name ($pKey) is already defined in configuration file ($this->FILENAME). Please choose another name!", E_USER_WARNING );
			return false;
		}
	}//END OF FUNCTION addKeyValue

	/**
	 * Check type of key and value and return correct value back as a string type
	 * Conversion is needed
	 * @see addKeyValue()
	 * @access private
	 * @param string $pKey
	 * @param string $pVal
	 * @return string
	 */
	function _checkType( $pKey, $pVal )
	{
		// boolean must start with b_
		if ( preg_match( "/^b_/i", $pKey ) )
		{
			if( gettype( $pVal ) == "boolean" )
			return $this->_booleanToString( $pVal );
			else
			{
				$pattern = array( "true","yes","1","on","y","false","no","0","off","n" );
				$count = count( $pattern );
				if( in_array( strtolower( $pVal ), $pattern ) )
				return $pVal;
				trigger_error( "Boolean error. Specified boolean value ($pVal) is not accepted. Use (true|yes|1|on|y) or (false|no|0|off|n) values only.", E_USER_WARNING );
			}
		}
		// array must start with a_
		else if ( preg_match( "/a_/i", $pKey ) )
		{
			if( gettype( $pVal ) == "array" )
			return $this->_arrayToString( $pVal );
			else
			return $pVal;
		}
		// integer must start with i_
		// do we have to check gettype( $pVal ) in any case???
		// i don't think so...
		else if ( preg_match( "/i_/i", $pKey ) )
		{
			return $this->_integerToString( $pVal );
		}
		// double must start with d_
		else if ( preg_match( "/d_/i", $pKey ) )
		{
			return $this->_doubleToString( $pVal );
		}
		// string must start with s_
		else if ( preg_match( "/s_/i", $pKey ) )
		{
			return $this->_stringToString( $pVal );
		}
		// everything else is handled as a string
		else
		{
			return $this->_stringToString( $pVal );
		}
	}//END OF FUNCTION _checkType

	/**
	 * Checks, if key word is defined
	 *
	 * This is more presice method than trying to refer straight to
	 * the class scope keys. Expecially boolean keys and values
	 * may cause problems with straight object referings. Another
	 * knows issue comes, when userr tries to point keyname on object
	 * that doesn't exist. It causes notice of undefined property.
	 * One solution is to check with isDefined before trying to
	 * catch key value. Another solution may come if new method
	 * secureGet will be announced. That function could return undefined
	 * if key is not defined...
	 * @access public
	 * @param string $pKey
	 * @return bool
	 */
	function isDefined( $pKey )
	{
		$ar = $this->getConfigLines();
		$count = count( $ar );
		for( $i = 0; $i < $count; $i++ )
		{
			$line = $ar[$i];
			list ( $key, $val ) = explode( "=", $line );
			//$key = ereg_replace( "[ 	]",	"", $key );
			$key = preg_replace( "/\s+/",	"", $key );
			if( $pKey == $key )
			return true;
		}
		return false;
	}//END OF FUNCTION isDefined

	/**
	 * Checks, if key word is in reserved word list
	 * @access public
	 * @param string $pKey
	 * @return bool
	 */
	function isReserved( $pKey )
	{
		for( $i=0; $i< count( $this->RESERVED_WORDS ); $i++ )
		if( $pKey == $this->RESERVED_WORDS )
		return true;
		return false;
	}//END OF FUNCTION isReserved

	/**
	 * Update excisting key value pair
	 * Long string values must be started and ended with ' marks!
	 * See config_definitions to learn, how to make ConfigTool
	 * compatible configurations name value pairs.
	 * @access public
	 * @param string $pKey
	 * @param string $pVal
	 * @return bool
	 */
	function updateKeyValue( $pKey, $pVal )
	{
		$temp_array = array();
		//
		$pVal = $this->_checkType( $pKey, $pVal );
		//
		if( $this->isDefined( $pKey ) )
		{
			$ar = $this->getConfigLines( "all" );
			$count = count( $ar );
			for( $i=0; $i < $count; $i++ )
			{
				// we need to check only lines, that may contain variables
				// comment lines are avoided. split function throws notice
				// if line doesn't contain any = mark
				//if ( eregi( "^[A-Z]", $ar[$i] ) )
				if ( preg_match( "/^[A-Z]/i", $ar[$i] ) )
				{
					list ( $key, $val ) = explode( "=", $ar[$i] );
					//$key = ereg_replace( "[ 	]",	"", $key );
					$key = preg_replace( "/\s+/",	"", $key );
					if ( $key == $pKey )
					$line = $pKey . str_pad( " ", $this->INDENT - strlen( $pKey )  ) . " = " . $pVal;
					else
					$line = $ar[$i];
				}
				else
				$line = $ar[$i];
				//
				$temp_array[$i] = $line;
			}
			$this->LINES = $temp_array;
			// if value starts with ', remove them from object value
			// however, ' marks are left in array, because
			// array is saved to the file, and long strings
			// must be surrounded by ' marks to work properly
			if ( preg_match( "/^'/i", $pVal ) )
			//if ( ereg( "^'", $pVal ) )
			{
				//$pVal = ereg_replace( "^'", "", $pVal );
				//$pVal = ereg_replace( "'$", "", $pVal );
				$pVal = preg_replace( "/^'/", "", $pVal );
				$pVal = preg_replace( "/'$/", "", $pVal );
			}
			$this->$pKey = $pVal;
			$this->_checkAutoTypes( $pKey );
			unset( $temp_array );
			return true;
		}
		else
		{
			unset( $temp_array );
			trigger_error( "Update error. Name ($pKey) was not found from the configuration file ($this->FILENAME). Please choose another name!", E_USER_WARNING );
			return false;
		}
	}//END OF FUNCTION updateKeyValue

	/**
	 * Check, if string starts with specified symbol (b_, i_, a_, s_)
	 * @access private
	 * @param string $key
	 */
	function _checkAutoTypes( $key )
	{
		// boolean must start with b_
		if ( $this->AUTOBOOL && preg_match( "/^b_/i", $key ) )
		{
			$this->_toBoolean( $key );
		}
		// array must start with a_
		else if ( $this->AUTOARRAY && preg_match( "/a_/i", $key ) )
		{
			$this->_toArray( $key );
		}
		// integer must start with i_
		else if ( $this->AUTOINTEGER && preg_match( "/i_/i", $key ) )
		{
			$this->_toInteger( $key );
		}
		// double must start with d_
		else if ( $this->AUTODOUBLE && preg_match( "/d_/i", $key ) )
		{
			$this->_toDouble( $key );
		}
		// string must start with s_
		else if ( $this->AUTOSTRING && preg_match( "/s_/i", $key ) )
		{
			$this->_toString( $key );
		}
		// everything else is handled as a string
		else
		{
			$this->_toString( $key );
		}
	}//END OF FUNCTION _checkAutoTypes

	/**
	 * Set key to boolean from string presentation
	 * @access private
	 * @param string $key
	 * @return boolean
	 */
	function _toBoolean( $key )
	{
		$val = $this->$key;

		//if( eregi( "(true|yes|1|on|y)", $val ) )
		if( preg_match( "/(true|yes|1|on|y)/i", $val ) )
		{
			$this->$key = true;
			return true;
		}
		//else if( eregi( "(false|no|0|off|n)", $val ) )
		else if( preg_match( "/(false|no|0|off|n)/i", $val ) )
		{
			$this->$key = false;
			return true;
		}
		else
		{
			trigger_error( "_toBoolean operation failed. Value couldn't be detected (" . $key . " = " . $val . ").Please check the value in the configuration file.", E_USER_WARNING );
			unset( $this->$key );
			return false;
		}
	}//END OF FUNCTION _toBoolean

	/**
	 * Set key to array from string presentation
	 * @access private
	 * @param string $key
	 */
	function _toArray( $key )
	{
		$ar = array();
		//$this->$key = str_replace( " ",	"", $this->$key );
		$ar = explode( ",", $this->$key );
		$this->$key = $ar;
		unset ( $ar );
	}//END OF FUNCTION _toArray

	/**
	 * Set key to string from string presentation
	 * @access private
	 * @param string $key
	 */
	function _toString( $key )
	{
		settype( $this->$key, "string" );
	}//END OF FUNCTION _toString

	/**
	 * Set key to integer from string presentation
	 * @access private
	 * @param string $key
	 */
	function _toInteger( $key )
	{
		settype( $this->$key, "integer" );
	}//END OF FUNCTION _toInteger

	/**
	 * Set key to integer from string presentation
	 * @access private
	 * @param string $key
	 */
	function _toDouble( $key )
	{
		settype( $this->$key, "double" );
	}//END OF FUNCTION _toDouble

	/**
	 * Set value to boolean from string presentation
	 * @access private
	 * @param bool $b
	 * @return string
	 */
	function _booleanToString( $b )
	{
		if( $b )
		return "true";
		else
		return "false";
	}//END OF FUNCTION _booleanToString

	/**
	 * Set value from string to string presentation
	 * @access private
	 * @param string $str
	 * @return string $str
	 */
	function _stringToString( $str )
	{
		return "" . $str;
	}//END OF FUNCTION _stringToString

	/**
	 * Set value from integer to string presentation
	 * @access private
	 * @param integer $int
	 * @return string $str
	 */
	function _integerToString( $int )
	{
		return "" . $int;
	}//END OF FUNCTION _integerToString

	/**
	 * Set value from double to string presentation
	 * @access private
	 * @param double $dbl
	 * @return string $str
	 */
	function _doubleToString( $dbl )
	{
		return "" . $dbl;
	}//END OF FUNCTION _doubleToString

	/**
	 * Convert array to comma separated string. Other separator can be
	 * defined in parameter
	 * @access private
	 * @param array $array
	 * @param string $separ
	 * @return string $str
	 */
	function _arrayToString( $array, $separ = "," )
	{
		$str = "";
		$count = count( $array );
		for( $i=0; $i < $count - 1; $i++ )
		{
			$str .= $array[$i] . $separ;
		}
		$str .= $array[$i];
		return $str;
	}//END OF FUNCTION _arrayToString

	/**
	 * Write to file
	 *
	 * Overwrite to file, if exists and is writable.
	 * Try to create new if file name doesn't exists.
	 * If new is about to write, then directory has to have CHMOD 0666 or 0777 also!
	 *
	 * @access private
	 * @param string $pFlag
	 * @param string $pContent
	 * @return boolean
	 */
	function _fileWrite( $pFlag, &$pContent )
	{
		if( file_exists( $this->FILENAME ) )
		{
			if( !is_writable( $this->FILENAME ) )
			{
				if( !chmod( $this->FILENAME, 0666 ) )
				{
					trigger_error( "Cannot change the mode of file (" . $this->FILENAME . "). Php may work on safe mode... You should change file permission to CHMOD 0666 or 0777 manually by using ftp tool or shell commands.", E_USER_WARNING );
					return false;
				};
			}
		}
		//
		$path_parts = pathinfo( $this->FILENAME );
		//echo $this->FILENAME;
		$directory = $path_parts['dirname'];
		//
		if( !is_writable( $directory ) )
		{
			if( !chmod( $directory, 0666 ) )
			{
				trigger_error( "Cannot change the mode of directory (" . $directory . "). Php may work on safe mode... You should change directory permission to CHMOD 0666 or 0777 manually by using ftp tool or shell commands.", E_USER_WARNING );
				return false;
			};
		}
		//
		if( !$fp = @fopen( $this->FILENAME, $pFlag ) )
		{
			trigger_error( "Cannot open file (" . $this->FILENAME . ")", E_USER_WARNING );
			return false;
		}
		if( fwrite( $fp, $pContent ) === FALSE )
		{
			trigger_error( "Cannot write to file (" . $this->FILENAME . ")", E_USER_WARNING );
			return false;
		}
		if( !fclose( $fp ) )
		{
			trigger_error( "Cannot close file (" . $this->FILENAME . ")", E_USER_WARNING );
			return false;
		}
		return true;
	}//END OF FUNCTION _fileWrite

}//END OF CLASS ConfigTool
?>


text:
package mil.nga.geopackage.io;

import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * Conversions between Bitmaps and image bytes
 *
 * @author osbornb
 */
public class BitmapConverter {

    /**
     * Decode the bytes to a bitmap
     *
     * @param bytes image bytes
     * @return image bitmap
     */
    public static Bitmap toBitmap(byte[] bytes) {
        return toBitmap(bytes, null);
    }

    /**
     * Decode the bytes to a bitmap, with options
     *
     * @param bytes   image bytes
     * @param options decode options
     * @return image bitmap
     */
    public static Bitmap toBitmap(byte[] bytes, Options options) {
        Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length,
                options);
        return bitmap;
    }

    /**
     * Compress the bitmap to a byte array at full quality
     *
     * @param bitmap image bitmap
     * @param format compress format
     * @return image bytes
     * @throws IOException upon failure
     */
    public static byte[] toBytes(Bitmap bitmap, CompressFormat format)
            throws IOException {
        return toBytes(bitmap, format, 100);
    }

    /**
     * Compress the bitmap to a byte array
     *
     * @param bitmap  bitmap image
     * @param format  compress format
     * @param quality quality
     * @return image bytes
     * @throws IOException upon failure
     */
    public static byte[] toBytes(Bitmap bitmap, CompressFormat format,
                                 int quality) throws IOException {
        byte[] bytes = null;
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        try {
            bitmap.compress(format, quality, byteStream);
            bytes = byteStream.toByteArray();
        } finally {
            byteStream.close();
        }
        return bytes;
    }

}

redpajama_set_name: RedPajamaGithub


text:
namespace dart {

// Forward declarations.
class NativeArguments;

// We have three variants of native functions:
//  - bootstrap natives, which are called directly from stub code. The callee is
//    responsible for safepoint transitions and setting up handle scopes as
//    needed. Only VM-defined natives are bootstrap natives; they cannot be
//    defined by embedders.
//  - no scope natives, which are called through a wrapper function. The wrapper
//    function handles the safepoint transition. The callee is responsible for
//    setting up API scopes as needed.
//  - auto scope natives, which are called through a wrapper function. The
//    wrapper function handles the safepoint transition and sets up an API
//    scope.

typedef void (*NativeFunction)(NativeArguments* arguments);
typedef void (*NativeFunctionWrapper)(Dart_NativeArguments args,
                                      Dart_NativeFunction func);

}  // namespace dart

#endif  // RUNTIME_VM_NATIVE_FUNCTION_H_


text:
using Android.App;
using Android.OS;
using Cirrious.MvvmCross.Droid.Views;

namespace backstack.Droid.Views
{
    [Activity(Label = "Deep View")]
    public class DeepView : MvxActivity
    {
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
			SetContentView(Resource.Layout.DeepView);
        }
    }
}


text:
'use strict';

module.exports = {
    db: 'mongodb://localhost/gdgbh-certificados-test',
    port: 3001,
    app: {
        title: 'gdgbh-certificados - Test Environment'
    },
    google: {
        clientID: process.env.GOOGLE_ID || 'APP_ID',
        clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET',
        callbackURL: '/auth/google/callback'
    },
    github: {
        clientID: process.env.GITHUB_ID || 'APP_ID',
        clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET',
        callbackURL: '/auth/github/callback'
    },
    mailer: {
        from: process.env.MAILER_FROM || 'MAILER_FROM',
        options: {
            service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER',
            auth: {
                user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID',
                pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD'
            }
        }
    }
};


text:
/***************************************************************************
File: MarchingCube.hh
Abstract: MarchingCube class for marching cube algrithms
Created: 2002-06-24

(C) 2002 by Wake Forest University School of Medicine
                             and
        Virgina Polytechnic Institute and State University

Last Revision ($Revision: 1.1.1.1 $) by $Author: hongli $ on $Date: 2002/12/06 21:49:28 $
***************************************************************************/
#ifndef _MarchingCube_hh_
#define _MarchingCube_hh_

#include "Cube.hh"
#include "Triangle_with_Features.hh"
#include <slist>

class MarchingCube;

class IsoPoint
{
private:
	Point p;
	MarchingCube * pCube;
	int vIndexin;
	int vIndexout;
	int faceIndex[2];
	bool mark;
	int index;
public:
	IsoPoint(Point point)
		{
		p = point;
		mark = false;
		index = vIndexin = vIndexout = -1;
		}
	IsoPoint(MarchingCube * cube, Point point)
		{
		pCube = cube;
		p = point;
		index = vIndexin = vIndexout = -1;
		mark = false;

		}

	IsoPoint()
		{
		index = vIndexin = vIndexout = -1;
		mark = false;
		}

	void setMark(bool value) {mark = value; }
	bool getMark(void) { return mark;}
	void setIndex(int i) {index = i;}
	int getIndex(void) {return index;}
	void setVIndexin(int index) { vIndexin = index;}
	void setVIndexout(int index) { vIndexout = index;}
	int getVIndexin() { return vIndexin;}
	int getVIndexout() {return  vIndexout;}
	void setFaceIndex(void);
	void getFaceIndex(int & f1, int & f2)
		{
		f1 = faceIndex[0];
		f2 = faceIndex[1];
		 }
	Point getPoint(void) { return p;}
};

class MarchingCube : public Cube
{
private :
	float threshold; /// the threshold for out and in
	std::slist<IsoPoint *> isoPoints;
	std::slist<Triangle *> triList; ///Triangle list
	bool flag;
	bool thrflag; // 0/1 high value in/out
public:
	MarchingCube(mvVec3i iVertex) : Cube(iVertex) {}
	MarchingCube(Point Vertex) : Cube(Vertex) {}
	MarchingCube() : Cube() {}

	bool isoPointExist(void);
	std::slist<IsoPoint *> getIsoPoints(void);
	std::slist<Triangle *> getTriangles(void);
	void setThreshold(float t) {threshold = t;}
	float getThreshold(void) {return threshold;}
	void setFlag(bool v) {flag = v;}
	bool getFlag() {return flag;}
	void setThrFlag(bool v) {thrflag = v;}
	bool getThrFlag() {return thrflag;}
	IsoPoint * getNextIsoPoint(IsoPoint *curP, bool & dir);

};

#endif


text:
package com.restfb.types;

import com.restfb.Facebook;

import lombok.Getter;
import lombok.Setter;

/**
 * Respresents the User Profile object as defined
 * here
 */
public class UserProfile extends NamedFacebookType {

  @Getter
  @Setter
  @Facebook("first_name")
  private String firstName;

  @Getter
  @Setter
  @Facebook("last_name")
  private String lastName;

  @Getter
  @Setter
  @Facebook("profile_pic")
  private String profilePic;

  @Getter
  @Setter
  @Facebook
  private String locale;

  @Getter
  @Setter
  @Facebook
  private String timezone;

  @Getter
  @Setter
  @Facebook
  private String gender;

  @Getter
  @Setter
  @Facebook("is_payment_enabled")
  private Boolean isPaymentEnabled;

  @Getter
  @Setter
  @Facebook("last_ad_referral")
  private LastAdReferral lastAdReferral;

  public static class LastAdReferral extends AbstractFacebookType {

    @Getter
    @Setter
    @Facebook
    private String source;

    @Getter
    @Setter
    @Facebook
    private String type;

    @Getter
    @Setter
    @Facebook("ad_id")
    private String adId;
  }
}


text:
/**
 * exposes in UI a set of properties belonging to the selected object or node
 * these are wired via get/set proxies
 */
var UIAbstractProperties = function UIAbstractProperties(domElement) {
	EventEmitter.apply(this, arguments)
	var that = this

	this.attached = false
	this.updateQueued = false
	this.detachQueue = []

	this.dom = {
		container: null		// typically $(domElement)
	}

	// holds references to any custom UI control objects, controlling this.adapter via dom events
	this.controls = {}

	// collects exposed properties. set at render-time
	this.adapter = null

	Object.defineProperty(this, 'selectedEditorObjectMeshPlugin', {
		get: function() {
			return E2.app.worldEditor.getSelectedObjectPlugin()
		}
	})

	// one graph node or nothing
	Object.defineProperty(this, 'selectedGraphNode', {
		get: function() {
			var sel = E2.ui.state.selectedObjects
			return (sel &&  sel.length === 1  && sel[0]) ? sel[0] : null
		}
	})

	Object.defineProperty(this, 'selectedIsCamera', {
		get: function() {
			var sel = this.selectedEditorObjectMeshPlugin
			return sel && (sel.id === 'three_vr_camera')
		}
	})

	// convenience methods
	Object.defineProperty(this, 'isValidObjectSelection', {
		get: function() {
			return !!this.selectedEditorObjectMeshPlugin
		}
	})

	Object.defineProperty(this, 'isValidNodeSelection', {
		get: function() {
			return !!this.selectedGraphNode
		}
	})

	Object.defineProperty(this, 'isInBuildMode', {
		get: function() {
			return E2.ui.isInBuildMode()
		}
	})

	E2.ui.state.on('changed:mode', this.render.bind(this))
	E2.ui.on('undo', this.onUndo.bind(this))
	E2.ui.on('redo', this.onRedo.bind(this))
}
UIAbstractProperties.prototype = Object.create(EventEmitter.prototype)
UIAbstractProperties.prototype.constructor = UIAbstractProperties

UIAbstractProperties.prototype.onUndo = function() {
	this.render()
}
UIAbstractProperties.prototype.onRedo = UIAbstractProperties.prototype.onUndo

// sometimes we need to wait the graph to complete a cycle so we request a call on next frame
UIAbstractProperties.prototype.queueUpdate = function() {
	var that = this

	if (this.updateQueued)
		return

	this.updateQueued = true

	setTimeout(function() {
		that.updateQueued = false

		if (that.attached)
			that.update()
		else
			console.error('queueUpdate() not attached?')
	}, 0)
}

// resets panel, clearing container, refreshing adapter, and controls, and rerendering template
UIAbstractProperties.prototype.render = function() {
	this._detach()
	var canRender = this.isValidNodeSelection || this.isValidObjectSelection
	if (canRender) {
		this.adapter = this.getAdapter()
		this.controls = this.getControls()
		var props = this.getTemplateData()	// formatted etc
	} else {
		var props = {}
		this.adapter = {}
		this.controls = {}
	}

	this.dom.container.empty()
	this.dom.container.html(this.template({
		adapter : this.adapter,
		controls: this.controls,
		properties: props
	}))

	VizorUI.replaceSVGButtons(this.dom.container)

	this._attach()
	this.emit('rendered')

	this.update()

	return this
}

UIAbstractProperties.prototype._detach = function() {

	$('*', this.dom).off('.uiProperties')

	if (this.detachQueue && this.detachQueue.length) {
		var removeHandler
		while (removeHandler = this.detachQueue.pop()) {
			removeHandler()
		}
	}

	this.onDetach()

	this.emit('detached')
	this.attached = false

}

UIAbstractProperties.prototype.watchConnectionUpdates = function(node) {

	var update = this.render.bind(this)	// heavyhanded but object3d doesnt work otherwise

	node.on('connected', update)
	node.on('disconnected', update)

	this.detachQueue.push(function () {
		node.off('disconnected', update)
		node.off('connected', update)
	})

}

UIAbstractProperties.prototype._attach = function() {
	// if anything is connected we wait a frame
	if (this.selectedGraphNode) {
		this.watchConnectionUpdates(this.selectedGraphNode)
	}
	this.onAttach()
	this.emit('attached')
	this.attached = true
}

UIAbstractProperties.prototype._reset = function() {	// resets handling, clears interface
	this.onReset()
	this._detach()
	this.adapter = {}
	this.controls = {}
	this.emit('reset')
	return this
}

// makes a control based on an adapter prop
/**
 * {e.g.
 *  position: {
 *    value:
 *    canEdit: (bool)
 *    label: (string)
 *    dt: (e2.core.datatypes)
 *  }
 * }
 * @param props (adapter)
 * @param propName (e.g. 'position' for adapter.position)
 * @param onChange (optional callback)
 * @private
 */
UIAbstractProperties.prototype._makeControl = function(node, props, propName, onChange, opts) {
	var controlType = VizorUI.getControlTypeForDt(props[propName].dt)
	if (!controlType) {
		console.error('could not get control type for dt of prop:'+propName, props)
		return
	}
	if (!props[propName]) {
		console.error('no ' + propName + ' in slotProps', props)
		return
	}
	var prop = props[propName]
	var control = new controlType(prop, 'value', null, onChange, opts)
	var changeHandler = function(key){
		if (key.name && key.name !== propName) return	// this is a slot and it's not for us
		control.onSourceChange()
	}
	if (node) {
		control.__attach = control.attach
		control.attach = function () {
			control.__attach()
			node.on(prop.eventName, changeHandler)
		}
		control.__detach = control.detach
		control.detach = function () {
			node.off(prop.eventName, changeHandler)
			control.__detach()
		}
	}
	if (prop.canEdit !== undefined) {
		if (!prop.canEdit) control.disable()
	}

	control.label 	= prop.label
	control.dt 		= prop.dt
	return control
}

// make the UI conform to the protocol loop (emit event, update on receive)
// we can read direct from the proxy, but setting the values has to go via the graph API
// when the node actually changes its input slot value (via graph call / event), control must update
UIAbstractProperties.prototype.uifySlotProxy = function(node, slotName, inputSlotProxy) {	//
	var proxy = inputSlotProxy
	if (!(proxy instanceof Object)) {
		console.error('proxy not an object', proxy)
		return
	}
	Object.defineProperty(proxy, 'value', {
		get: function() {
			return proxy.canEdit ? proxy._value : proxy.default
		},
		set: function(v) {
			if (proxy.canEdit)
				E2.app.graphApi.changeInputSlotValue(node.parent_graph, node, slotName, v)
			return v
		}
	})
	Object.defineProperty(proxy, 'eventName', {value: 'uiSlotValueChanged'})	// control will listen to this
	return proxy
}

/********* methods to implement ***********/

/* recommend implementing */
				UIAbstractProperties.prototype.getTemplateData = function() {return this.adapter}

// the adapter bridges values for the selected object's state or properties, and the UI controls
/* @abstract */ UIAbstractProperties.prototype.getAdapter = function() {return {}}
/* @abstract */ UIAbstractProperties.prototype.getControls = function() {return {}}
/* @abstract */ UIAbstractProperties.prototype.onAttach 	= function() {}
/* @abstract */ UIAbstractProperties.prototype.onDetach 	= function() {}	// this.detachQueue is automatically processed
/* @abstract */ UIAbstractProperties.prototype.onReset 	= function() {}
/* @abstract */ UIAbstractProperties.prototype.update 	= function() {}	// soft-update this.dom{} in place


text:
/**
 *
 */
package org.mford.gae.testAppv6.entity;

import java.util.List;

/**
 * site readsing
 * @author nick
 *
 */
public class AnemometerSiteResponse {

	/**
	 * operations outcome status
	 */
	private ResultStatus status;

	/**
	 * identifies site
	 */
	private AnemometerSite site;

	/**
	 * readings
	 */
	private List<AnemometerReading> readings;

	public AnemometerSiteResponse() {
	}

	public AnemometerSiteResponse(AnemometerSite site,
			List<AnemometerReading> readings, ResultStatus status) {
		this.site = site;
		this.readings = readings;
		this.status = status;
	}

	/**
	 * @return the site
	 */
	public AnemometerSite getSite() {
		return site;
	}

	/**
	 * @param site the site to set
	 */
	public void setSite(AnemometerSite site) {
		this.site = site;
	}

	/**
	 * @return the readings
	 */
	public List<AnemometerReading> getReadings() {
		return readings;
	}

	/**
	 * @param readings the readings to set
	 */
	public void setReadings(List<AnemometerReading> readings) {
		this.readings = readings;
	}

	/**
	 * @param status the status to set
	 */
	public ResultStatus getStatus() {
		return status;
	}

	/**
	 * @param status the status to set
	 */
	public void setStatus(ResultStatus status) {
		this.status = status;
	}

}


text:
namespace performance_monitor {

#if defined(OS_MAC)
TEST(ProcessMetricsRecorderUtilTest, RecordCoalitionData) {
  base::HistogramTester histogram_tester;
  ProcessMonitor::Metrics metrics;
  ResourceCoalition::DataRate coalition_data = {};

  coalition_data.cpu_time_per_second = 0.1;
  coalition_data.interrupt_wakeups_per_second = 0.3;
  coalition_data.platform_idle_wakeups_per_second = 2;
  coalition_data.bytesread_per_second = 10;
  coalition_data.byteswritten_per_second = 0.1;
  coalition_data.gpu_time_per_second = 0.8;
  coalition_data.energy_impact_per_second = 3.0;
  coalition_data.power_nw = 1000;

  for (int i = 0;
       i < static_cast<int>(ResourceCoalition::QoSLevels::kMaxValue) + 1; ++i) {
    coalition_data.qos_time_per_second[i] = i * 0.1;
  }

  metrics.coalition_data = coalition_data;

  std::vector<const char*> suffixes = {"", ".Foo", ".Bar"};
  RecordCoalitionData(metrics, suffixes);

  for (const char* scenario_suffix : suffixes) {
    // These histograms reports the CPU/GPU times as a percentage of time with a
    // permyriad granularity, 10% (0.1) will be represented as 1000.
    histogram_tester.ExpectUniqueSample(
        base::StrCat(
            {"PerformanceMonitor.ResourceCoalition.CPUTime2", scenario_suffix}),
        coalition_data.cpu_time_per_second * 10000, 1);
    histogram_tester.ExpectUniqueSample(
        base::StrCat(
            {"PerformanceMonitor.ResourceCoalition.GPUTime2", scenario_suffix}),
        coalition_data.gpu_time_per_second * 10000, 1);

    // These histograms report counts with a millievent/second granularity.
    histogram_tester.ExpectUniqueSample(
        base::StrCat(
            {"PerformanceMonitor.ResourceCoalition.InterruptWakeupsPerSecond",
             scenario_suffix}),
        coalition_data.interrupt_wakeups_per_second * 1000, 1);
    histogram_tester.ExpectUniqueSample(
        base::StrCat({"PerformanceMonitor.ResourceCoalition."
                      "PlatformIdleWakeupsPerSecond",
                      scenario_suffix}),
        coalition_data.platform_idle_wakeups_per_second * 1000, 1);
    histogram_tester.ExpectUniqueSample(
        base::StrCat({"PerformanceMonitor.ResourceCoalition.BytesReadPerSecond",
                      scenario_suffix}),
        coalition_data.bytesread_per_second * 1000, 1);
    histogram_tester.ExpectUniqueSample(
        base::StrCat(
            {"PerformanceMonitor.ResourceCoalition.BytesWrittenPerSecond",
             scenario_suffix}),
        coalition_data.byteswritten_per_second * 1000, 1);
    // EI is reported in centi-EI so the data needs to be multiplied by 100.0.
    histogram_tester.ExpectUniqueSample(
        base::StrCat({"PerformanceMonitor.ResourceCoalition.EnergyImpact",
                      scenario_suffix}),
        coalition_data.energy_impact_per_second * 100.0, 1);

    // Power is reported in milliwatts (mj/s), the data is in nj/s so it has to
    // be divided by 1000000.
    histogram_tester.ExpectUniqueSample(
        base::StrCat(
            {"PerformanceMonitor.ResourceCoalition.Power", scenario_suffix}),
        coalition_data.power_nw / 1000000, 1);

    // The QoS histograms also reports the CPU times as a percentage of time
    // with a permyriad granularity.
    histogram_tester.ExpectUniqueSample(
        base::StrCat({"PerformanceMonitor.ResourceCoalition.QoSLevel.Default",
                      scenario_suffix}),
        coalition_data.qos_time_per_second[0] * 10000, 1);
    histogram_tester.ExpectUniqueSample(
        base::StrCat(
            {"PerformanceMonitor.ResourceCoalition.QoSLevel.Maintenance",
             scenario_suffix}),
        coalition_data.qos_time_per_second[1] * 10000, 1);
    histogram_tester.ExpectUniqueSample(
        base::StrCat(
            {"PerformanceMonitor.ResourceCoalition.QoSLevel.Background",
             scenario_suffix}),
        coalition_data.qos_time_per_second[2] * 10000, 1);
    histogram_tester.ExpectUniqueSample(
        base::StrCat({"PerformanceMonitor.ResourceCoalition.QoSLevel.Utility",
                      scenario_suffix}),
        coalition_data.qos_time_per_second[3] * 10000, 1);
    histogram_tester.ExpectUniqueSample(
        base::StrCat({"PerformanceMonitor.ResourceCoalition.QoSLevel.Legacy",
                      scenario_suffix}),
        coalition_data.qos_time_per_second[4] * 10000, 1);
    histogram_tester.ExpectUniqueSample(
        base::StrCat(
            {"PerformanceMonitor.ResourceCoalition.QoSLevel.UserInitiated",
             scenario_suffix}),
        coalition_data.qos_time_per_second[5] * 10000, 1);
    histogram_tester.ExpectUniqueSample(
        base::StrCat(
            {"PerformanceMonitor.ResourceCoalition.QoSLevel.UserInteractive",
             scenario_suffix}),
        coalition_data.qos_time_per_second[6] * 10000, 1);
  }
}
#endif

}  // namespace performance_monitor


text:
/* bufferlist.h */

/* A class for buffering the I/O and allow multiple streams to read the data
   asynchronously */

#ifndef _MPEGLIST_H_
#define _MPEGLIST_H_

#include "SDL.h"

class MPEGlist {
public:
  MPEGlist();
  ~MPEGlist();

  /* Get to the next free buffer or allocate a new one if none is free */
  MPEGlist * Alloc(Uint32 Buffer_Size);

  /* Lock current buffer */
  void Lock();

  /* Unlock current buffer */
  void Unlock();

  /* Get the buffer */
  inline void * Buffer() { return(data); };

  inline Uint32 Size() { return(size); };

  inline MPEGlist * Next() { return(next); };

  inline MPEGlist * Prev() { return(prev); };

  inline Uint32 IsLocked() { return(lock); };

  double TimeStamp;

private:
  class MPEGlist * next;
  class MPEGlist * prev;
  Uint32 lock;
  Uint8 * data;
  Uint32 size;
};
#endif


text:
require "cardgame/version"

module Cardgame
  # Your code goes here...
end


text:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import scipy.stats as spst
import shapely.geometry as geom
import geopandas as gpd
import sklearn as sklearn
from sklearn import cluster
from sklearn import preprocessing
from matplotlib.colors import ListedColormap
get_ipython().magic(u'matplotlib inline')
from rnn import RNN, MetaRNN

food = pd.read_csv('food_final.csv')
food = food[food.SCORE > 0]
latlon = pd.DataFrame(list(food.latlon.str.split()))
latlon.columns = ['latitude', 'longitude']
latlon['latitude'] = latlon['latitude'].map(lambda x: str(x)[:-1])
latlon = latlon.astype(float)
latlon = latlon[['longitude', 'latitude']]
boros = gpd.GeoDataFrame.from_file('nycb.shp')

#Plotting geographical distribution of the points
plt.figure(figsize=(10,8))
boros.plot(alpha=0)
plt.scatter(latlon.longitude, latlon.latitude, s=20, alpha=0.3)
plt.title("Distribution of food stablishments @ NYC", fontsize = 20)
plt.ylim([40.45, 40.95])
plt.xlim([-74.3, -73.6])
plt.grid()

ax3 = food['SCORE'].plot(kind='hist', bins = 20, figsize=(6,4), grid=True,
                title="Histogram of DOH Scores", alpha=0.8)
ax = food.plot(x='rating', y='SCORE', kind='scatter', figsize=(8,6), grid=True,
          title="DOH Score Vs 4Square ratings", alpha=0.5)
ax.set(xlabel="Rating", ylabel="DOH Score")
print(spst.pearsonr(food.rating, food.SCORE))
ax1 = food.plot(x='price.tier', y='SCORE', kind='scatter', figsize=(8,6),
                grid=True, title="DOH Score Vs 4Square price range", alpha=0.5)
ax1.set(xlabel="Price Tier", ylabel="DOH Score")

ax2 = food['rating'].plot(kind='hist', bins = 20, figsize=(6,4), grid=True,
                 title="Histogram of 4Square ratings", alpha=0.8)

#Subsetting and whitening the data for clustering
food_sel = food[['rating','SCORE','price.tier', 'stats.checkinsCount']]
food_sel['price.tier'] = food_sel['price.tier'].fillna(value=1)
food_sel1 = food_sel[['rating', 'SCORE']]
food_sel1_scaled = preprocessing.scale(food_sel1)
food_sel_scaled = preprocessing.scale(food_sel)

#Clustering with kmeans and only rating and DOH Score
k = 3
est = cluster.KMeans(n_clusters = k, n_init = 100)
est.fit(food_sel1_scaled)
colors = est.labels_.astype(np.float)
cmap = ListedColormap(['blue','green','yellow','red', 'cyan'])
plt.figure(figsize=(10, 8))
boros.plot(alpha=0)
plt.scatter(latlon.longitude, latlon.latitude, s=20, c=colors, cmap=cmap,
            alpha = 0.5)
plt.title("Clustering with K-means and 3 clusters", fontsize = 20)
plt.xlabel('Latitude', fontsize=16)
plt.ylabel('Longitude', fontsize=16)
plt.ylim([40.5, 40.95])
plt.xlim([-74.3, -73.6])
plt.grid()

#Clustering with kmeans and all featrures (rating, DOH Score, price tier and
#4squared checkins)
k = 2
est = cluster.KMeans(n_clusters = k, n_init = 100)
est.fit(food_sel_scaled)
colors = est.labels_.astype(np.float)
cmap = ListedColormap(['blue','green','yellow','red', 'cyan'])
plt.figure(figsize=(10, 8))
boros.plot(alpha=0)
plt.scatter(latlon.longitude, latlon.latitude, s=20, c=colors, cmap=cmap,
            alpha =0.5)
plt.title("Clustering with K-means and 2 clusters", fontsize = 20)
plt.xlabel('Latitude', fontsize=16)
plt.ylabel('Longitude', fontsize=16)
plt.ylim([40.5, 40.95])
plt.xlim([-74.3, -73.6])
plt.grid()

food_sel_scaled_df = pd.DataFrame(preprocessing.scale(food_sel), columns =['rating','SCORE','price.tier', 'stats.checkinsCount'])

#Dividing the sample into train and test sets
np.random.seed(2015)
ind=spst.bernoulli.rvs(p = 0.75, size = len(food_sel1))
food_sel_scaled_train = food_sel_scaled_df[ind==1]
food_sel_scaled_test = food_sel_scaled_df[ind==0]

#Creating parameters for training RNN
n_hidden = 5 # M
n_in = 3      # D
n_out = 1     # K
n_steps = 1  # the length of each sequence
n_seq = len(food_sel_scaled_train)   # the number of datapoints (i.e. sequences)

#Creating input and output arrays for training RNN
rating = np.array(food_sel_scaled_train[['rating','price.tier','stats.checkinsCount']]).reshape(n_seq,n_steps,n_in)
score = np.array(food_sel_scaled_train['SCORE']).reshape(n_seq,n_steps,n_out)

#Creating the model and feeding it with training data set
model = MetaRNN(n_in=n_in, n_hidden=n_hidden, n_out=n_out,
                    learning_rate=0.001, learning_rate_decay=0.999,
                    n_epochs=50, activation='tanh')
model.fit(rating, score, validation_frequency=5000)

guess = model.predict(rating.reshape(len(rating), n_in))
scores_pred = pd.DataFrame(guess)

scores_pred.columns = ['predictions']

scores_pred.predictions.plot(kind='hist', bins=20, figsize=(6,4), grid=True,                             title = "Histogram of predicted DOH normalized Scores (IS)", alpha=0.8)

food_sel_scaled_train.SCORE.plot(kind='hist', bins=20, figsize=(6,4), grid=True,                             title = "Histogram of actual DOH normalized Scores (IS)", alpha=0.8)

#Creating parameters for training RNN
n_hidden = 5 # M
n_in = 3      # D
n_out = 1     # K
n_steps = 1  # the length of each sequence
n_seq = len(food_sel_scaled_test)   # the number of datapoints (i.e. sequences)

#Creating input and output arrays for training RNN
rating1 = np.array(food_sel_scaled_test[['rating','price.tier','stats.checkinsCount']]).reshape(n_seq,n_steps,n_in)
score1 = np.array(food_sel_scaled_test['SCORE']).reshape(n_seq,n_steps,n_out)

guess1 = model.predict(rating1.reshape(len(rating1), n_in))
scores_pred1 = pd.DataFrame(guess1)

scores_pred1.columns = ['predictions']

scores_pred1.predictions.plot(kind='hist', bins=20, figsize=(6,4), grid=True,                             title = "Histogram of predicted DOH normalized Scores (OS)", alpha=0.8)

food_sel_scaled_test.SCORE.plot(kind='hist', bins=20, figsize=(6,4), grid=True,                             title = "Histogram of actual DOH normalized Scores (OS)", alpha=0.8)

fig = plt.figure(figsize=(8,6))
ax = plt.scatter(x=food_sel_scaled_test.SCORE, y=scores_pred1.predictions,
                 alpha=0.8)
plt.grid()
plt.title('OS predicted and actual results (Normalized)')
plt.xlabel('Actual Score', fontsize=16)
plt.ylabel('Predicted Score', fontsize=16)

BCsubset = (food[food.SCORE > 13])

latlon1 = pd.DataFrame(list(BCsubset.latlon.str.split()))
latlon1.columns = ['latitude', 'longitude']
latlon1['latitude'] = latlon1['latitude'].map(lambda x: str(x)[:-1])
latlon1 = latlon1.astype(float)
latlon1 = latlon1[['longitude', 'latitude']]

#Plotting geographical distribution of the points
plt.figure(figsize=(10,8))
boros.plot(alpha=0)
plt.scatter(latlon1.longitude, latlon1.latitude, s=20, alpha=0.3)
plt.title("Distribution of food stablishments @ NYC (B and C rated)",
          fontsize = 20)
plt.ylim([40.45, 40.95])
plt.xlim([-74.3, -73.6])
plt.grid()

ax3 = BCsubset['SCORE'].plot(kind='hist', bins = 20, figsize=(6,4), grid=True,
                title="Histogram of DOH Scores (B and C)", alpha=0.8)
ax = BCsubset.plot(x='rating', y='SCORE', kind='scatter', figsize=(8,6), grid=True,
          title="DOH Score (B & C) Vs 4Square ratings", alpha=0.5)
ax.set(xlabel="Rating", ylabel="DOH Score")
print(spst.pearsonr(BCsubset.rating, BCsubset.SCORE))
ax1 = BCsubset.plot(x='price.tier', y='SCORE', kind='scatter', figsize=(8,6),
                grid=True, title="DOH Score (B & C) Vs 4Square price range", alpha=0.5)
ax1.set(xlabel="Price Tier", ylabel="DOH Score")

ax2 = food['rating'].plot(kind='hist', bins = 20, figsize=(6,4), grid=True,
                 title="Histogram of 4Square ratings (B & C restaurants)", alpha=0.8)

#Subsetting and whitening the data for clustering
BC_food_sel = BCsubset[['rating','SCORE','price.tier', 'stats.checkinsCount']]
BC_food_sel['price.tier'] = BCsubset['price.tier'].fillna(value=1)
BC_food_sel1 = BCsubset[['rating', 'SCORE']]
BC_food_sel1_scaled = preprocessing.scale(BC_food_sel1)
BC_food_sel_scaled = preprocessing.scale(BC_food_sel)

#Clustering with kmeans and only rating and DOH Score
k = 2
est = cluster.KMeans(n_clusters = k, n_init = 100)
est.fit(BC_food_sel1_scaled)
colors = est.labels_.astype(np.float)
cmap = ListedColormap(['blue','green','yellow','red', 'cyan'])
plt.figure(figsize=(10, 8))
boros.plot(alpha=0)
plt.scatter(latlon1.longitude, latlon1.latitude, s=20, c=colors, cmap=cmap,
            alpha = 0.5)
plt.title("Clustering with K-means and 2 clusters", fontsize = 20)
plt.xlabel('Latitude', fontsize=16)
plt.ylabel('Longitude', fontsize=16)
plt.ylim([40.5, 40.95])
plt.xlim([-74.3, -73.6])
plt.grid()

#Clustering with kmeans and all featrures (rating, DOH Score, price tier and
#4squared checkins)
k = 2
est = cluster.KMeans(n_clusters = k, n_init = 100)
est.fit(BC_food_sel_scaled)
colors = est.labels_.astype(np.float)
cmap = ListedColormap(['blue','green','yellow','red', 'cyan'])
plt.figure(figsize=(10, 8))
boros.plot(alpha=0)
plt.scatter(latlon1.longitude, latlon1.latitude, s=20, c=colors, cmap=cmap,
            alpha =0.5)
plt.title("Clustering with K-means and 2 clusters", fontsize = 20)
plt.xlabel('Latitude', fontsize=16)
plt.ylabel('Longitude', fontsize=16)
plt.ylim([40.5, 40.95])
plt.xlim([-74.3, -73.6])
plt.grid()

BC_food_sel_scaled_df = pd.DataFrame(preprocessing.scale(BC_food_sel),
                                     columns =['rating','SCORE','price.tier','stats.checkinsCount'])

#Dividing the sample into train and test sets
np.random.seed(2015)
ind=spst.bernoulli.rvs(p = 0.75, size = len(BC_food_sel))
BC_food_sel_scaled_train = BC_food_sel_scaled_df[ind==1]
BC_food_sel_scaled_test = BC_food_sel_scaled_df[ind==0]

#Creating parameters for training RNN
n_hidden = 5 # M
n_in = 3      # D
n_out = 1     # K
n_steps = 1  # the length of each sequence
n_seq = len(BC_food_sel_scaled_train)   # the number of datapoints (i.e. sequences)

#Creating input and output arrays for training RNN
BC_rating = np.array(BC_food_sel_scaled_train[['rating','price.tier','stats.checkinsCount']]).reshape(n_seq,n_steps,n_in)
BC_score = np.array(BC_food_sel_scaled_train['SCORE']).reshape(n_seq,n_steps,n_out)

#Creating the model and feeding it with training data set
model = MetaRNN(n_in=n_in, n_hidden=n_hidden, n_out=n_out,
                    learning_rate=0.001, learning_rate_decay=0.999,
                    n_epochs=200, activation='tanh')
model.fit(BC_rating, BC_score, validation_frequency=5000)

BCguess = model.predict(BC_rating.reshape(len(BC_rating), n_in))
BCscores_pred = pd.DataFrame(BCguess)

BCscores_pred.columns = ['predictions']

BCscores_pred.predictions.plot(kind='hist', bins=20, figsize=(6,4), grid=True,
                               title = "Histogram of predicted DOH normalized Scores B&C (IS)", alpha=0.8)

BC_food_sel_scaled_train.SCORE.plot(kind='hist', bins=20, figsize=(6,4), grid=True,
                                    title = "Histogram of actual DOH normalized Scores B&C (IS)", alpha=0.8)

#Creating parameters for training RNN
n_hidden = 5 # M
n_in = 3      # D
n_out = 1     # K
n_steps = 1  # the length of each sequence
n_seq = len(BC_food_sel_scaled_test)   # the number of datapoints (i.e. sequences)

#Creating input and output arrays for training RNN
BC_rating1 = np.array(BC_food_sel_scaled_test[['rating','price.tier','stats.checkinsCount']]).reshape(n_seq,n_steps,n_in)
BC_score1 = np.array(BC_food_sel_scaled_test['SCORE']).reshape(n_seq,n_steps,n_out)

BCguess1 = model.predict(BC_rating1.reshape(len(BC_rating1), n_in))
BCscores_pred1 = pd.DataFrame(BCguess1)

BCscores_pred1.columns = ['predictions']

BCscores_pred1.predictions.plot(kind='hist', bins=20, figsize=(6,4), grid=True,
                                title = "Histogram of predicted DOH normalized Scores B&C (OS)", alpha=0.8)

BC_food_sel_scaled_test.SCORE.plot(kind='hist', bins=20, figsize=(6,4), grid=True,
                                   title = "Histogram of actual DOH normalized Scores B&C (OS)", alpha=0.8)

fig = plt.figure(figsize=(8,6))
ax = plt.scatter(x=BC_food_sel_scaled_test.SCORE, y=BCscores_pred1.predictions,
                 alpha=0.8)
plt.grid()
plt.title('OS predicted and actual results (Normalized)')
plt.xlabel('Actual Score', fontsize=16)
plt.ylabel('Predicted Score', fontsize=16)


text:
/*
angular.module('idModule', [])
    .controller('idcontroller', ['$scope', function($scope) {

      $scope.index = function() {
        $scope.urlIndex = "http://www.kenworthdeleste.com.mx/KwEste/index.html";
      };

	  $scope.unidades = function() {
        $scope.urlUnidades = "http://www.kenworthdeleste.com.mx/KwEste/index.html#section-feature";
      };

      $scope.index();
    }]);
*/
function crearFrame() {
    var testFrame = document.createElement("IFRAME");
    testFrame.id = "testFrame";
    testFrame.src = "http://www.kenworthdeleste.com.mx";
    document.body.appendChild(testFrame);
}

function cambiar(){

	var cambio = document.getElementById('testFrame');
	cambio.src="http://www.kenworthdeleste.com.mx/KwEste/index.html#section-feature";
    document.body.appendChild(testFrame);

}

$(document).ready(function(){
    var cambio = document.getElementById('testFrame');
	cambio.src="http://www.kenworthdeleste.com.mx/";
    document.body.appendChild(testFrame);
});


text:
<?php

namespace Devswert\Dolly\Exceptions;

use Exception;

class WebPayConnectionException extends Exception{
}


text:
#if !defined(WINCONFIG_H)
#define WINCONFIG_H

#if !defined(PACKAGE_VERSION)
#define PACKAGE_VERSION "0.23"
#endif /* #if !defined(PACKAGE_VERSION) */

#define HAVE_STDIO_H 1
#define HAVE_STDLIB_H 1
#define HAVE_STRING_H 1
#define HAVE_LIMITS_H 1

#define HAVE_MEMCHR 1
#define HAVE_MEMCMP 1
#define HAVE_MEMCPY 1
#define HAVE_MEMSET 1
#define HAVE_STRLEN 1

#define XRABPLY_TYPE64 __int64
#define XV64(v) ((xply_word) v ## UI64)

#endif /* WINCONFIG_H */


text:
<ServiceRequest>
  <data>
    <WebApp>
      <urlBlacklist>
        <set>
          <UrlEntry regex="true"><![CDATA[http://rg.blacklist.*.com]]></UrlEntry>
        </set>
      </urlBlacklist>
    </WebApp>
  </data>
</ServiceRequest>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Biblthca Lichenol. 48: 170 (1992)

#### Original name
Lecidea verrucariae Metzler ex Nyl.

### Remarks
null


text:
<?php

namespace MathQuiz\MainBundle\Entity;

use Symfony\Component\Config\Definition\Exception\Exception;

class Expression
{

    protected $operands;

    protected $operations;

    protected $result;

    protected $possibleOperations = [0, 1, 2, 3];

    public function __construct($operands, $operations)
    {

        $this->operands = $operands;
        $this->operations = $operations;

        $this->isValidate();

        $this->calculateResult();

    }

    protected function calculateResult()
    {

        $result = array();

        for ($i = 0; $i < count($this->operations); $i++) {

            $result[] = [
                'type' => 'operand',
                'value' => $this->getOperandValue($this->operands[$i]),
            ];
            $result[] = [
                'type' => 'operation',
                'value' => $this->operations[$i],
            ];

        }

        $result[] = [
            'type' => 'operand',
            'value' => $this->operands[count($this->operands) - 1],
        ];

        for ($i = count($this->possibleOperations) - 1; $i > -1; $i--) {

            $operation = $this->possibleOperations[$i];

            $existsCurrentOperationFlag = true;

            while ($existsCurrentOperationFlag) {

                $existsCurrentOperationFlag = false;

                for ($j = 1; $j < count($result); $j += 2) {

                    if ($result[$j]['value'] == $operation) {

                        $existsCurrentOperationFlag = true;

                        if ($j > 1) {

                            $result = array_merge(
                                array_slice($result, 0, $j - 1),
                                [
                                    [
                                        'type' => 'operand',
                                        'value' => $this->simpleOperation($result[$j - 1]['value'], $result[$j + 1]['value'], $operation),
                                    ],
                                ],
                                array_slice($result, $j + 2)
                            );

                        } else {

                            $result = array_merge(
                                [
                                    [
                                        'type' => 'operand',
                                        'value' => $this->simpleOperation($result[$j - 1]['value'], $result[$j + 1]['value'], $operation),
                                    ],
                                ],
                                array_slice($result, $j + 2)
                            );

                        }

                        break;

                    }

                }

            }

        }

        $this->result = $result[0]['value'];

    }

    protected function simpleOperation($arg1, $arg2, $operation)
    {

        switch ($operation) {

            case 0:

                return $this->getOperandValue($arg1) + $this->getOperandValue($arg2);

                break;

            case 1:

                return $this->getOperandValue($arg1) - $this->getOperandValue($arg2);

                break;

            case 2:

                return $this->getOperandValue($arg1) * $this->getOperandValue($arg2);

                break;

            case 3:

                $arg2 = $this->getOperandValue($arg2);

                if ($arg2 == 0) {

                    throw new Exception('Devision by zero: ' . $this);

                }

                return $this->getOperandValue($arg1) / $arg2;

                break;

            default:

                throw new Exception('Unsupported operation: ' . $operation);
        }

    }

    protected function isValidate()
    {

        $result =
            is_array($this->operands) &&
            is_array($this->operations) &&
            count($this->operands) > 1 &&
            count($this->operands) - count($this->operations) == 1;

        if ($result) {

            $this->operationsValidate();
            $this->operandsValidate();

        } else {

            throw new Exception('Unvalid arguments');

        }

    }

    protected function operationsValidate()
    {

        foreach ($this->operations as $operation) {

            if (!in_array(trim($operation), $this->possibleOperations)) {

                throw new Exception('Unsupported operation: ' . $operation);

            }

        }

    }

    protected function operandsValidate()
    {

        for ($i = 0; $i < count($this->operands); $i++) {

            $operand = $this->operands[$i];

            if (!($operand instanceof self)) {

                if (!filter_var($operand, FILTER_VALIDATE_FLOAT)) {

                    if ($operand != 0) {

                        throw new Exception('Undefined operand: ' . $operand);

                    } elseif ($operand == 0 && isset($this->operations[$i - 1]) && $this->operations[$i - 1] == 3) {

                        throw new Exception('Devision by zero: ' . $this);

                    }

                }

            }

        }

    }

    private function getOperandValue($operand)
    {

        return
            $operand instanceof self
                ? $operand->getResult()
                : $operand;

    }

    public function __toString()
    {

        $string = '';

        $operationsSymbols = ['+', '-', '×', '÷'];

        for ($i = 0; $i < count($this->operands); $i++) {

            if ($this->operands[$i] instanceof self) {

                if ($i == count($this->operands) - 1) {

                    $string .= '(' . $this->operands[$i] . ')';

                } else {

                    $string .= '(' . $this->operands[$i] . ') ' . $operationsSymbols[$this->operations[$i]] . ' ';

                }

            } else {

                if ($i == count($this->operands) - 1) {

                    $string .= $this->operands[$i];

                } else {

                    $string .= $this->operands[$i] . ' ' . $operationsSymbols[$this->operations[$i]] . ' ';

                }

            }

        }

        return $string;

    }

    /**
     * @return
     */
    public function getResult()
    {

        return $this->result;

    }

    protected function  getFloatOperandTail($operand)
    {

        $operandTail = $operand - intval($operand);

        if (!$operandTail) {

            return false;

        }

        return ltrim((string)$operandTail, '0.');

    }

    public function forPdf($withAnswer = false)
    {

        $rows = [];

        if (count($this->operations) == 1 && $this->operations[0] == 3) {
            $operand0ValueString = (string)$this->getOperandValue($this->operands[0]);
            $rows[] = $withAnswer ? (string)$this->getResult() : ' ';
            $rows[] = 'division_line';
            $rows[] = $this->getOperandValue($this->operands[1]) . ' |  ' . $operand0ValueString;

        } else {

            $operationsSymbols = ['+', '—', '×', '÷'];

            for ($i = 0; $i < count($this->operands); $i++) {

                $operand = $this->getOperandValue($this->operands[$i]);

                if ($i > 0) {

                    $rows[] = $operationsSymbols[$this->operations[$i - 1]] . substr('          ' . $operand, strlen('' . $operand) - 1);

                } else {

                    $rows[] = substr('      ' . $operand, strlen('' . $operand) - 1);

                }

            }

            $rows[] = 'line';

            if ($withAnswer) {

                $rows[] = substr('      ' . $this->getResult(), strlen('' . $this->getResult()) - 1);

            }

        }

        return $rows;

    }

}


text:
// Copyright (c) Microsoft Corporation.  All rights reserved.
// Licensed under the MIT License.  See License.txt in the project root for license information.

using System.IO;
using System.Web.OData.Design.Scaffolding.ReadMe;
using System.Web.OData.Design.Scaffolding.VisualStudio;
using Microsoft.AspNet.Scaffolding;

namespace System.Web.OData.Design.Scaffolding
{
    public class ODataDependencyInstaller : DependencyInstaller
    {
        public ODataDependencyInstaller(CodeGenerationContext context, IVisualStudioIntegration visualStudioIntegration)
            : base(context, visualStudioIntegration)
        {
        }

        protected override string[] SearchFolders
        {
            get
            {
                // TODO: this is temporarily here until we reorganize these dependency folders
                return new string[] { Path.Combine(TemplateSearchDirectories.InstalledTemplateRoot, "ODataDependencyCodeGenerator") };
            }
        }

        protected override FrameworkDependencyStatus GenerateConfiguration()
        {
            object isODataAssemblyReferenced;
            Context.Items.TryGetProperty(ContextKeys.IsODataAssemblyReferencedKey, out isODataAssemblyReferenced);

            object isWebApiAssemblyReferenced;
            Context.Items.TryGetProperty(ContextKeys.IsWebApiAssemblyReferencedKey, out isWebApiAssemblyReferenced);

            bool showODataReadme = !(bool)isODataAssemblyReferenced;
            bool showWebApiReadme = !(bool)isWebApiAssemblyReferenced;
            bool isNewGlobalAsaxCreated = TryCreateGlobalAsax();

            if (isNewGlobalAsaxCreated && showODataReadme)
            {
                return FrameworkDependencyStatus.FromReadme(ODataReadMe.CreateReadMeText());
            }
            else if (!isNewGlobalAsaxCreated)
            {
                string readmeText = String.Empty;

                if (showODataReadme)
                {
                    readmeText += ODataReadMe.CreateReadMeText();
                }

                if (showWebApiReadme)
                {
                    // WebApiReadMe readMeGenerator = new WebApiReadMe(Context.ActiveProject.GetCodeLanguage(), Context.ActiveProject.Name, AppStartFileNames);
                    // readmeText += readMeGenerator.CreateReadMeText();
                }

                if (!String.IsNullOrEmpty(readmeText))
                {
                    return FrameworkDependencyStatus.FromReadme(readmeText);
                }
            }

            return FrameworkDependencyStatus.InstallSuccessful;
        }
    }
}


text:
A RESTful API for playing
[Love Letter](http://boardgamegeek.com/boardgame/129622/love-letter).

## License

This code is copyright Jonathan M. Lange, 2015, and is made available
under the Apache License, version 2.0. See LICENSE for details.

## Further reading

* [Problem statement](doc/Problem.md) – high-level design document
* [API design](doc/API-Design.md) – more detailed design of the API
* [haverer](https://github.com/jml/haverer) – the Love Letter library


text:
/* Author: Mahfouz-z */
/*
 * Copyright (c) 2022, The Regents of the University of California
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the University nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "ord/OpenRoad.hh"

// Stubs out functions from OpenRoad that aren't needed by Testing but
// are referenced from dst modules or its dependencies.

namespace ord {

OpenRoad::OpenRoad()
    : tcl_interp_(nullptr),
      logger_(nullptr),
      db_(nullptr),
      verilog_network_(nullptr),
      sta_(nullptr),
      resizer_(nullptr),
      ioPlacer_(nullptr),
      opendp_(nullptr),
      optdp_(nullptr),
      finale_(nullptr),
      macro_placer_(nullptr),
      macro_placer2_(nullptr),
      global_router_(nullptr),
      restructure_(nullptr),
      tritonCts_(nullptr),
      tapcell_(nullptr),
      extractor_(nullptr),
      detailed_router_(nullptr),
      antenna_checker_(nullptr),
      replace_(nullptr),
      pdnsim_(nullptr),
      partitionMgr_(nullptr),
      pdngen_(nullptr),
      distributer_(nullptr),
      stt_builder_(nullptr),
      threads_(0)
{
}

OpenRoad* OpenRoad::openRoad()
{
  return nullptr;
}

}  // namespace ord


text:
	jQuery(document).ready(function() {
		Metronic.init(); // init metronic core components
		Layout.init(); // init current layout
		QuickSidebar.init(); // init quick sidebar
		Demo.init(); // init demo features
		TableManaged.init();
		$('#coupons_list').addClass('active');
		$("#coupon-table").on('click', ".btn-coupon-delete", function(){
			$this_tr = $(this).closest('tr');
			var el = $(this).closest(".portlet").children(".portlet-body");
			Metronic.blockUI({ target: el, animate: true, overlayColor: '#000000' });
			$.post( base_url()+"admin/deleteCoupon", {"coupon-id":$this_tr.data('coupon')}, function(data){
				data = jQuery.parseJSON(data);
				if(data.error == "no"){
					$this_tr.fadeOut("normal", function() { $(this).remove(); });
					Metronic.alert({type: 'success', message: data.msg, closeInSeconds: 5, icon: 'check'});
				}else{
					Metronic.alert({type: 'danger', message: data.msg, closeInSeconds: 5, icon: 'warning'});
				}
			});
			Metronic.unblockUI(el);
		});
		$("#coupon-table").on('click', ".btn-coupon-toggle", function(){
			$this = $(this);
			$this_tr = $this.closest('tr');
			var el = $(this).closest(".portlet").children(".portlet-body");
			Metronic.blockUI({ target: el, animate: true, overlayColor: '#000000' });
			$.post( base_url()+"admin/couponstatus", {"coupon-id":$this_tr.data('coupon'), "coupon-status":$this.data('coupon-status')}, function(data){
				data = jQuery.parseJSON(data);
				if(data.error == "no"){
					if(data.status > 0){
						$this.data('coupon-status', data.status).removeClass('yellow').addClass('green').html("Disable");
					}else{
						$this.data('coupon-status', data.status).removeClass('green').addClass('yellow').html("Enable");
					}
					Metronic.alert({type: 'success', message: data.msg, closeInSeconds: 5, icon: 'check'});
				}else{
					Metronic.alert({type: 'danger', message: data.msg, closeInSeconds: 5, icon: 'warning'});
				}
			});
			Metronic.unblockUI(el);
		});
});

var TableManaged = function () {

    var initTable1 = function () {

        var table = $('#coupon-table');

        // begin first table
        table.dataTable({

            // Internationalisation. For more info refer to http://datatables.net/manual/i18n
            "language": {
                "aria": {
                    "sortAscending": ": activate to sort column ascending",
                    "sortDescending": ": activate to sort column descending"
                },
                "emptyTable": "No data available in table",
                "info": "Showing _START_ to _END_ of _TOTAL_ records",
                "infoEmpty": "No records found",
                "infoFiltered": "(filtered1 from _MAX_ total records)",
                "lengthMenu": "Show _MENU_ records",
                "search": "Search:",
                "zeroRecords": "No matching records found",
                "paginate": {
                    "previous":"Prev",
                    "next": "Next",
                    "last": "Last",
                    "first": "First"
                }
            },
						"lengthMenu": [
								[10, 15, 20, 100, -1],
								[10, 15, 20, 100, "All"] // change per page values here
						],
						// set the initial value
						"pageLength": 10,
            "pagingType": "bootstrap_full_number",
            "columnDefs": [{  // set default column settings
                'orderable': true,
                'targets': [0]
            }, {
                "searchable": true,
                "targets": [0]
            }],
            "order": [
                [0, "asc"]
            ], // set first column as a default sort by asc
						"fnDrawCallback": function ( oSettings ) {
				          /* Need to redo the counters if filtered or sorted */
      				if ( oSettings.bSorted || oSettings.bFiltered )
      				{
      					for ( var i=0, iLen=oSettings.aiDisplay.length ; i<iLen ; i++ )
      					{
      						$('td:eq(0)', oSettings.aoData[ oSettings.aiDisplay[i] ].nTr ).html( i+1 );
      					}
      				}
      			}
        });

    }

    return {

        init: function () {
            if (!jQuery().dataTable) {
                return;
            }

            initTable1();
        }

    };

}();


text:
require 'poseidon'
require 'json'
require 'csv'
require 'base64'
require 'awesome_print'
class Tester
    attr_reader :events
    def initialize
        start = Time.new
        dir = "/tmp/fuse-kafka-test/"
        started = false
        @events = []
        n_partition = 2
        stop_file = dir + "stop"
        start_file = dir + "start"
        write_file = dir + "blah"
        write_files = []
        done = false
        threads = n_partition.times.collect do |partition|
            Thread.new do
                consumer = Poseidon::PartitionConsumer.new("_", "localhost", 9092, "logs", partition, :latest_offset)
                loop do
                    break if done
                    consumer.fetch.each do |m|
                        event = JSON.parse(m.value)
                        if event["path"] == start_file
                            started = true
                            break
                        end
                        done = (event["path"] == stop_file)
                        ["@message", "command"].each do |w|
                            event[w] = Base64.decode64(event[w])
                        end
                        break if done
                        @events.push event
                    end
                    break if done
                end
            end
        end
        @n = 0
        loop { sleep 1; File.write(start_file, "startup"); break if started }
        ["a", "w", "w+", "a", "a+"].each do |mode|
            [true, false].each do |flush|
                write_files += [write_file + @n.to_s]
                File.open(write_files.last, mode) do |f|
                    100.times do
                        f.write "#{@n} "
                        @n += 1
                        f.flush if flush
                    end
                end
            end
        end
        (n_partition * 10).times.each { File.write(stop_file, "shutdown") }
        threads.each { |t| t.join }
        write_files + [stop_file, start_file].each { |f| File.delete(f) }
        @duration = Time.new - start
    end
    def save path
        values = []
        File.open(path, "w") do |f|
            f.puts "duration: #{@duration}"
            @events.each do |event|
                values += event["@message"].split(" ").collect { |x| x.to_i }
                f.puts "#{event["@timestamp"]} #{event["path"]}: #{event["@message"]}"
            end
        end
        print_missing values
    end
    def print_missing_summary first, last
        if not first.nil?
            puts "#{first}...#{last} missing"
        end
        nil
    end
    def print_missing values
        first = nil
        last = nil
        @n.times do |i|
            if not values.include?(i)
                if not first.nil?
                    last = i
                else
                    last = first = i
                end
            else
                first = print_missing_summary first, last
            end
        end
        print_missing_summary first, last
        puts "saved #{@events.size} events"
    end
end
tester = Tester.new
tester.save ARGV[0]


text:
"use strict";
exports.__esModule = true;
var channel;
(function (channel) {
    channel["RBTV"] = "UCQvTDmHza8erxZqDkjQ4bQQ";
    channel["LP"] = "UCtSP1OA6jO4quIGLae7Fb4g";
    channel["G2"] = "UCFBapHA35loZ3KZwT_z3BsQ";
    channel["INSIDE_PS"] = "UCP6gDeEEOVpKgzywJ8pfiRw";
})(channel = exports.channel || (exports.channel = {}));
var channelMap = (_a = {},
    _a[channel.RBTV] = 'Rocket Beans TV',
    _a[channel.LP] = 'Let`s Play',
    _a[channel.G2] = 'Game Two',
    _a[channel.INSIDE_PS] = 'Inside Playstation',
    _a);
function getChannelName(channel) {
    return channelMap[channel];
}
exports.getChannelName = getChannelName;
var _a;


text:
The following guide will show you how to build and run a self-contained Go app using rkt, the reference implementation of the [App Container Specification][appc-spec].
If you're not on Linux, you should do all of this inside [the rkt Vagrant][rkt-vagrant].

For a more complex example, please check the [build container examples](examples/build-container/README.md).

## Create a hello go application

```go
package main

import (
	"log"
	"net/http"
)

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		log.Printf("request from %v\n", r.RemoteAddr)
		w.Write([]byte("hello\n"))
	})
	log.Fatal(http.ListenAndServe(":5000", nil))
}
```

### Build a statically linked Go binary

Next we need to build our application.
We are going to statically link our app so we can ship an App Container Image with no external dependencies.

With Go 1.9:

```
$ CGO_ENABLED=0 go build -ldflags '-extldflags "-static"'
```

Note that if you use [gccgo][gcc-go], the command is instead:

```
$ go build -compiler gccgo -gccgoflags '-static'
```

Before proceeding, verify that the produced binary is statically linked:

```
$ file hello
hello: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked, not stripped
$ ldd hello
	not a dynamic executable
```

## Create the image

To create the image, we can use [`acbuild`][acbuild], which can be downloaded via one of the [releases in the containers/build repository][rkt-releases].

The following commands will create an ACI containing our application and important metadata.

```bash
acbuild begin
acbuild set-name example.com/hello
acbuild copy hello /bin/hello
acbuild set-exec /bin/hello
acbuild port add www tcp 5000
acbuild label add version 0.0.1
acbuild label add arch amd64
acbuild label add os linux
acbuild annotation add authors "Carly Container <carly@example.com>"
acbuild write hello-0.0.1-linux-amd64.aci
acbuild end
```

## Run

### Launch a local application image

```
# rkt --insecure-options=image run hello-0.0.1-linux-amd64.aci
```

Note that `--insecure-options=image` is required because, by default, rkt expects our images to be signed.
See the [Signing and Verification Guide][signing-guide] for more details.

At this point our hello app is running and ready to handle HTTP requests.

To stop the container, pass three escape characters (`^]^]^]`), which is generated by `Ctrl-]` on a US keyboard. You can also [run rkt as a daemon][rkt-daemon].

### Test with curl

By default, rkt will assign the running container an IP address. Use `rkt list` to discover what it is:

```
# rkt list
UUID		APP	IMAGE NAME		STATE	NETWORKS
885876b0	hello	example.com/hello:0.0.1	running	default:ip4=172.16.28.2
```

Then you can `curl` that IP on port 5000:

```
$ curl 172.16.28.2:5000
hello
```

[acbuild]: https://github.com/containers/build
[appc-spec]: https://github.com/appc/spec
[rkt-daemon]: subcommands/run.md#run-rkt-as-a-daemon
[rkt-releases]: https://github.com/containers/build/releases
[rkt-vagrant]: https://github.com/rkt/rkt/blob/master/Documentation/trying-out-rkt.md#rkt-using-vagrant
[signing-guide]: signing-and-verification-guide.md
[gcc-go]: https://golang.org/doc/install/gccgo


text:
package com.mltoolbox4j.data.exception;

/**
 * <tt>HeadersNotReadyException.java</tt><br>
 *
 * @author TerenceWu
 * @time 2017年11月10日 上午9:21:26
 * @version 1.0
 */
public class HeadersNotReadyException extends Exception {
	private static final long serialVersionUID = 1L;

	public HeadersNotReadyException() {
		super();
	}

	public HeadersNotReadyException(String arg0) {
		super(arg0);
	}
}


text:
__author__ = 'ben@emailscrubbed.com (Ben Darnell)'

from viewfinder.backend.db.test.base_test import DBBaseTestCase
from viewfinder.backend.db.subscription import Subscription
from viewfinder.backend.services import itunes_store
from viewfinder.backend.services.test import itunes_store_test

class SubscriptionTestCase(DBBaseTestCase):
  def testCreateFromITunes(self):
    # Create an initial subscription.
    verify_response = itunes_store.VerifyResponse(itunes_store_test.kReceiptData, itunes_store_test.MakeNewResponse())
    Subscription.RecordITunesTransaction(self._client, self.stop, user_id=self._user.user_id, verify_response=verify_response)
    self.wait()

    # The test subscription is expired, so it won't be returned by default.
    Subscription.QueryByUser(self._client, self.stop, self._user.user_id)
    subs = self.wait()
    self.assertEqual(len(subs), 0)

    # It's there with include_expired=True.
    Subscription.QueryByUser(self._client, self.stop, self._user.user_id, include_expired=True)
    subs = self.wait()
    self.assertEqual(len(subs), 1)
    self.assertEqual(subs[0].expiration_ts, itunes_store_test.kExpirationTime)
    first_transaction_id = subs[0].transaction_id

    # Now add a renewal.
    verify_response = itunes_store.VerifyResponse(itunes_store_test.kReceiptData, itunes_store_test.MakeRenewedResponse())
    Subscription.RecordITunesTransaction(self._client, self.stop, user_id=self._user.user_id, verify_response=verify_response)
    self.wait()

    # Only the latest transaction is returned.
    Subscription.QueryByUser(self._client, self.stop, self._user.user_id, include_expired=True)
    subs = self.wait()
    self.assertEqual(len(subs), 1)
    self.assertEqual(subs[0].expiration_ts, itunes_store_test.kExpirationTime2)
    self.assertNotEqual(subs[0].transaction_id, first_transaction_id)

    # With include_history=True we get both transactions.
    Subscription.QueryByUser(self._client, self.stop, self._user.user_id, include_history=True)
    subs = self.wait()
    self.assertEqual(len(subs), 2)
    self.assertItemsEqual([sub.expiration_ts for sub in subs],
                          [itunes_store_test.kExpirationTime, itunes_store_test.kExpirationTime2])


text:
package com.planet_ink.coffee_mud.Abilities.Spells;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.util.*;

public class Spell_ConjureNexus extends Spell
{

	@Override
	public String ID()
	{
		return "Spell_ConjureNexus";
	}

	private final static String localizedName = CMLib.lang().L("Conjure Nexus");

	@Override
	public String name()
	{
		return localizedName;
	}

	@Override
	protected int canTargetCode()
	{
		return 0;
	}

	@Override
	protected int canAffectCode()
	{
		return Ability.CAN_ROOMS;
	}

	@Override
	public int classificationCode()
	{
		return Ability.ACODE_SPELL|Ability.DOMAIN_CONJURATION;
	}

	@Override
	public int abstractQuality()
	{
		return Ability.QUALITY_INDIFFERENT;
	}

	@Override
	public void unInvoke()
	{
		if((canBeUninvoked())&&(invoker()!=null)&&(affected instanceof Room))
			invoker().tell(L("The Nexus in '@x1' dissipates.",((Room)affected).displayText()));
		super.unInvoke();
	}

	@Override
	public boolean tick(final Tickable ticking, final int tickID)
	{
		if(!super.tick(ticking,tickID))
			return false;
		if((affected==null)||(!(affected instanceof Room)))
			return false;
		final Room R=(Room)affected;
		if(tickID==Tickable.TICKID_MOB)
		{
			for(int m=0;m<R.numInhabitants();m++)
			{
				final MOB mob=R.fetchInhabitant(m);
				if(mob!=null)
				{
					final int oldHP=mob.curState().getHitPoints();
					final int oldMV=mob.curState().getMovement();
					final int oldHU=mob.curState().getHunger();
					final int oldTH=mob.curState().getThirst();
					CMLib.combat().recoverTick(mob);
					mob.curState().setHitPoints(oldHP);
					mob.curState().setMovement(oldMV);
					mob.curState().setHunger(oldHU);
					mob.curState().setThirst(oldTH);
				}
			}
		}
		return true;
	}

	@Override
	public boolean invoke(final MOB mob, final List<String> commands, final Physical givenTarget, final boolean auto, final int asLevel)
	{
		try
		{
			for(final Enumeration<Room> r=CMLib.map().rooms();r.hasMoreElements();)
			{
				final Room R=r.nextElement();
				if(CMLib.flags().canAccess(mob,R))
				{
					for(final Enumeration<Ability> a=R.effects();a.hasMoreElements();)
					{
						final Ability A=a.nextElement();
						if((A!=null)&&(A.ID().equals(ID())))
						{
							A.unInvoke();
							break;
						}
					}
				}
			}
		}
		catch (final NoSuchElementException nse)
		{
		}
		if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
			return false;

		final boolean success=proficiencyCheck(mob,0,auto);

		if(success)
		{
			final CMMsg msg=CMClass.getMsg(mob,mob.location(),this,verbalCastCode(mob,mob.location(),auto),auto?"A Nexus of Mana appears!":L("^S<S-NAME> summon(s) the Nexus of mana!^?"));
			if(mob.location().okMessage(mob,msg))
			{
				mob.location().send(mob,msg);
				beneficialAffect(mob,mob.location(),asLevel,0);
			}

		}
		else
			beneficialWordsFizzle(mob,null,L("<S-NAME> attempt(s) to summon a Nexus, but fail(s)."));

		// return whether it worked
		return success;
	}
}