text:
<?php

class DatabaseConnection {
	/** @var PDO|null */
	public $cn = null;
	public $server = null;
	public $schema = null;
	public $username = null;
	public $password = null;
	public $type = null;
	public $is_managed = false;
	public $is_managed_slave = false;
	public $managed_slave_wait_in_seconds = 0;
	public function __construct($server,$schema,$username,$password,$type){
		$this->server = $server;
		$this->schema = $schema;
		$this->username = $username;
		$this->password = $password;
		$this->type = $type;
	}
}

class Database {
	const MYSQL = 'mysql';
	const ORACLE = 'oracle';
	const SQLSERVER = 'sqlserver';

	/** @var DatabaseConnection|null */
	private static $cx = null;
	private static $stack = array();

	private static $count_queries = 0;
	private static $queries = array();
	private static $prepared = array();

	// duplicates, for speed:
	/** @var PDO */
	private static $cn = null;
	private static $server = null;
	private static $schema = null;
	private static $type = null;

	public static function GetUpgradeFiles() { return Oxygen::GetDatabaseUpgradeFiles(); }
	public static function AddUpgradeFile($filename) { Oxygen::AddDatabaseUpgradeFile($filename); }

	private static function NeedsUpgrade(){
		foreach (Oxygen::GetDatabaseUpgradeFiles() as $filename){
			$key = 'Database::upgrade_time_of_'. $filename;
			$time = Scope::$DATABASE[$key];
			if (is_null($time))
				return true;
			if (filemtime($filename) > $time)
				return true;
		}
		return false;
	}
	private static $upgrade_running = false;
	public static function Upgrade($force=false,MultiMessage $logger = null){
		if (self::$upgrade_running) return;
		if (is_null(self::$cx)) return;
		if (!$force && !self::$cx->is_managed) return;
		self::$upgrade_running = true;

		$needs_refresh = false;
		if ($force || self::NeedsUpgrade()) {
			Database::SetPatchingSystemLogger($logger);
			Database::SetPatchingSystemSlave(!$force && self::$cx->is_managed_slave);
			$lock_filename = Oxygen::GetSharedTempFolder(true) .'/database.upgrade.lock';
			$f = fopen($lock_filename,'w');
			if (flock($f,LOCK_EX)){
				if ($force || self::NeedsUpgrade()) {
					try{ set_time_limit(0); }catch(Exception $ex){}
					Database::RequireConnection();
					Database::ClearPatchingSystem();
					foreach (Oxygen::GetDatabaseUpgradeFiles() as $filename){
						if (!Database::IsPatchingSystemSlave()) {
							require($filename);
							$key = 'Database::upgrade_time_of_'.$filename;
							Scope::$DATABASE[$key] = time();
						}
						else {
							try {
								require($filename);
								$key = 'Database::upgrade_time_of_'. $filename;
								Scope::$DATABASE[$key] = time();
							}
							catch (Exception $ex) {
								if (self::$cx->managed_slave_wait_in_seconds > 0) {
									sleep(self::$cx->managed_slave_wait_in_seconds);
									try {
										require($filename);
										$key = 'Database::upgrade_time_of_'. $filename;
										Scope::$DATABASE[$key] = time();
									}
									catch (Exception $ex) {
										throw new AccessHaltedException();
									}
								}
								else throw new AccessHaltedException();
							}
						}
					}
					if (Database::IsPatchingSystemDirty()) $needs_refresh = true;
				}
        // try { unlink($lock_filename); } catch(Exception $ex){}
        flock($f,LOCK_UN);
      }
      fclose($f);
		}
		if ($needs_refresh){
			self::ResetCaches();
			Oxygen::ResetSoft();
			Database::WriteToPatchingSystem(new SuccessMessage('Upgrade complete.'));
			Database::WriteToPatchingSystem(new InfoMessage('Total queries: '.(self::$count_queries)));
		}
		self::$upgrade_running = false;
	}

	private static function RequireConnection(){
		if (is_null(self::$cn)){
			if (is_null(self::$cx)) throw new Exception('No database connection specified.');
			try{
				switch (self::$cx->type){
					case self::MYSQL:
						$a = explode(':',self::$cx->server);
						$charset = Oxygen::GetCharset();
						if ($charset == 'UTF-8') $charset = 'utf8'; elseif ($charset == 'ISO-8859-1') $charset = 'latin1';
						self::$cx->cn = new PDO('mysql:host='.$a[0].(count($a)>1?';port='.$a[1]:'').';dbname='.self::$cx->schema.';charset='.$charset, self::$cx->username, self::$cx->password, array(PDO::ATTR_PERSISTENT => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION) );
						self::$cn = self::$cx->cn;
						break;
					case self::SQLSERVER:
						self::$cx->cn = new PDO("sqlsrv:Server=".self::$cx->server.";Database=".self::$cx->schema, self::$cx->username, self::$cx->password, array(PDO::ATTR_PERSISTENT => true, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
						self::$cn = self::$cx->cn;
						break;
					case self::ORACLE:
						$a = explode(':',self::$cx->server);
						self::$cx->cn = new PDO('oci:dbname=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST='.$a[0].')(PORT='.(count($a)>1?$a[1]:'1521').')))(CONNECT_DATA=(SERVICE_NAME='.self::$cx->schema.')))',self::$cx->username,self::$cx->password, array(PDO::ATTR_PERSISTENT => true, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
						self::$cn = self::$cx->cn;
						self::$cn->exec('ALTER SESSION SET NLS_LANGUAGE=\'AMERICAN\' NLS_TERRITORY=\'AMERICA\' NLS_CURRENCY=\'$\' NLS_ISO_CURRENCY=\'AMERICA\' NLS_NUMERIC_CHARACTERS=\'.,\' NLS_CALENDAR=\'GREGORIAN\' NLS_DATE_FORMAT=\'YYYY-MM-DD HH24:MI:SS\' NLS_DATE_LANGUAGE=\'AMERICAN\' NLS_SORT=\'BINARY_AI\' NLS_COMP=\'LINGUISTIC\'');
						self::$cn->exec('ALTER SESSION SET DDL_LOCK_TIMEOUT=120');
						break;
				}
			}
			catch (Exception $ex){
				throw new Exception('Cannot connect to database '.self::$cx->server.'/'.self::$cx->schema. '.',0,$ex);
			}
			if (self::$cx->is_managed){
				self::Upgrade();
				//Lemma::LoadLocalDictionary();
			}
		}
	}

	/**
	 * @api Since 1.3
	 * @param $server string
	 * @param $schema string
	 * @param $username string
	 * @param $password string
	 * @param string $type int Possible values Database::MYSQL, Database::SQLSERVER or Database::ORACLE
	 * @return void
	 */
	public static function Connect($server,$schema,$username,$password,$type=self::MYSQL){
		self::PushConnection();
		$c = new DatabaseConnection($server,$schema,$username,$password,$type);
		self::SetConnection( $c );
		try {
			self::RequireConnection();
		}
		catch (Exception $ex){
			self::PopConnection();
			throw $ex;
		}
		self::ResetCaches();
	}
	/**
	 * @api Since 1.3
	 * @param $server string
	 * @param $schema string
	 * @param $username string
	 * @param $password string
	 * @param string $type int Possible values Database::MYSQL, Database::SQLSERVER or Database::ORACLE
	 * @return void
	 */
	public static function ConnectManaged($server,$schema,$username,$password,$type=self::MYSQL){
		while(self::IsConnected()) self::Disconnect();
		$c = new DatabaseConnection($server,$schema,$username,$password,$type);
		$c->is_managed = true;
		self::SetConnection( $c );
		try {
			self::RequireConnection();
		}
		catch (Exception $ex){
			self::PopConnection();
			throw $ex;
		}
		self::ResetCaches();
	}
	public static function ConnectManagedSlave($server,$schema,$username,$password,$type=self::MYSQL,$waiting_in_seconds = 0){
		while(self::IsConnected()) self::Disconnect();
		$c = new DatabaseConnection($server,$schema,$username,$password,$type);
		$c->is_managed = true;
		$c->is_managed_slave = true;
		$c->managed_slave_wait_in_seconds = $waiting_in_seconds;
		self::SetConnection( $c );
		try {
			self::RequireConnection();
		}
		catch (Exception $ex){
			self::PopConnection();
			throw $ex;
		}
		self::ResetCaches();
	}

	public static function ConnectLazily($server,$schema,$username,$password,$type=self::MYSQL){
		$c = new DatabaseConnection($server,$schema,$username,$password,$type);
		self::PushConnection();
		self::SetConnection( $c );
		self::ResetCaches();
	}

	public static function ConnectLazilyManaged($server,$schema,$username,$password,$type=self::MYSQL){
		$c = new DatabaseConnection($server,$schema,$username,$password,$type);
		$c->is_managed = true;
		self::PushConnection();
		self::SetConnection( $c );
		self::ResetCaches();
	}
	public static function ConnectLazilyManagedSlave($server,$schema,$username,$password,$type=self::MYSQL,$waiting_in_seconds = 0){
		$c = new DatabaseConnection($server,$schema,$username,$password,$type);
		$c->is_managed = true;
		$c->is_managed_slave = true;
		$c->managed_slave_wait_in_seconds = $waiting_in_seconds;
		self::PushConnection();
		self::SetConnection( $c );
		self::ResetCaches();
	}

	/**
	 * @api Since 1.3
	 * @return void
	 */
	public static function Disconnect(){
		self::PopConnection();
		self::ResetCaches();
	}
	private static function SetConnection(DatabaseConnection $cx = null){
		if (is_null($cx)){
			self::$cx = null;
			self::$cn = null;
			self::$server = null;
			self::$schema = null;
			self::$type = null;
		}
		else {
			self::$cx = $cx;
			self::$cn = $cx->cn;
			self::$server = $cx->server;
			self::$schema = $cx->schema;
			self::$type = $cx->type;
		}
	}
	private static function PushConnection(){
		if (!is_null(self::$cx)){
			array_push(self::$stack,self::$cx);
			self::$count_queries = 0;
			self::$queries = array();
			self::$prepared = array();
		}
	}
	private static function PopConnection(){
		self::$count_queries = 0;
		self::$queries = array();
		self::$prepared = array();
		self::SetConnection( array_pop(self::$stack) );
	}
	private static function ResetCaches(){
		XMeta::FreeAllMemory();
		Scope::$DATABASE->FreeMemory();
	}

	public static function IsConnected(){ return !is_null(self::$cx); }
	public static function GetServer(){ return self::$server; }
	public static function GetSchema(){ return self::$schema; }
	public static function GetType(){ return self::$type; }

	//
	//
	// Database queries
	//
	//
	public static function GetQueries(){ return self::$queries; }
	public static function GetQueriesAsText(){
		$r = '';
		foreach ( self::$queries as $i => $q ) {
			$r .=  sprintf('%5d',($i+1)) . '. ' . $q . "\n";
		}
		if ($r == '') $r .= '-';
		return $r;
	}

	/**
	 * @param string $sql
	 * @return PDOStatement
	 */
	private static function &Prepare(&$sql){
		if (self::$type == self::ORACLE) {
			$r = self::$cn->prepare($sql); // Oracle handles the caching by itself.
		}
		else {
			if (!array_key_exists($sql,self::$prepared)) self::$prepared[$sql] = self::$cn->prepare($sql);
			$r = self::$prepared[$sql];
		}
		self::$queries[] =& $sql;
		self::$count_queries++;
		if (count(self::$queries) > 1000) { unset(self::$queries[key(self::$queries)]); reset(self::$queries); } // remove the first element from the array
		if (DEBUG && !self::$upgrade_running) Debug::Write( 'Query #'.self::$count_queries.': '.$sql);
		return $r;
	}

	/**
	 * @param string $sql
	 * @param array $params
	 * @return DBReader
	 */
	public static function ExecuteX($sql,$params=array()){
		self::RequireConnection();
//		$t = microtime(true);
		$q = self::Prepare($sql);
		$z = count($params);
		if ($z > 0){ for($i = 0; $i < $z; $i++) $q->bindValue($i+1, XType::Of($params[$i])->ExportPdoValue( $params[$i] , self::$type ) ); }
		try {
			$q->execute();
		}
		catch (Exception $ex) {
			$m = $ex->getMessage().'

'.$sql;
			foreach ($params as $p) $m .= '
• '.Debug::GetVariableAsString(  XType::Of($p)->ExportPdoValue( $p , self::$type ) );
			throw new Exception($m);
		}
		if ( $q->errorCode() !== '00000' ) {
			$info = $q->errorInfo(); $m = $info[2].'

'.$sql;
			foreach ($params as $p) $m .= '
• '.Debug::GetVariableAsString( XType::Of($p)->ExportPdoValue( $p , self::$type ) );
			throw new Exception($m);
		}
		$r = null;
		if ($q->columnCount() > 0) $r = new DBReader($q);
		else $r = $q->rowCount();
//		$t = microtime(true) - $t;
//		if ($t>2) Debug::RecordExceptionSilenced(new Exception('Long query: '.$t.'sec.'),'Execute timer');
		return $r;
	}

	/**
	 * @api Since 1.3
	 * @param string $sql ... Pass the rest of the arguments after $sql
	 * @return DBReader
	 */
	public static function Execute($sql){
		self::RequireConnection();
//		$t = microtime(true);
		$q = self::Prepare($sql);
		$z = func_num_args(); if ($z > 1){ $a = func_get_args(); for($i = 1; $i < $z; $i++) $q->bindValue($i, XType::Of($a[$i])->ExportPdoValue($a[$i] , self::$type ) ); }
		try {
			$q->execute();
		}
		catch (Exception $ex) {
			$m = $ex->getMessage().'

'.$sql;
			$z = func_num_args(); $a = func_get_args(); for($i = 1; $i < $z; $i++) $m .= '
• '.Debug::GetVariableAsString( XType::Of($a[$i])->ExportPdoValue($a[$i] , self::$type ) );
			throw new Exception($m);
		}
		if ( $q->errorCode() !== '00000' ) {
			$info = $q->errorInfo(); $m = $info[2].'

'.$sql;
			$z = func_num_args(); $a = func_get_args(); for($i = 1; $i < $z; $i++) $m .= '
• '.Debug::GetVariableAsString( XType::Of($a[$i])->ExportPdoValue($a[$i] , self::$type ) );
			throw new Exception($m);
		}
		$r = null;
		if ($q->columnCount() > 0) $r = new DBReader($q);
		else $r = $q->rowCount();
//		$t = microtime(true) - $t;
//		if ($t>2) Debug::RecordExceptionSilenced(new Exception('Long query: '.$t.'sec.'),'Execute timer');
		return $r;
	}

	/**
	 * @deprecated Since 1.3
	 * @param XType $type
	 * @param string $sql ... Pass the rest of the arguments after $sql
	 * @return array
	 */
	public static function ExecuteListOf(XType $type,$sql){
		/** @noinspection PhpDeprecationInspection */
		return self::ExecuteListOfX($type,$sql,array_slice(func_get_args(),2)); }
	/**
	 * @deprecated Since 1.3
	 * @param string $sql
	 * @param XType $type
	 * @param array $params
	 * @return array
	 */
	public static function ExecuteListOfX(XType $type,$sql,$params=array()){
		$dr = self::ExecuteX($sql,$params);
		$r = array();
		while ($dr->Read())	$r[] = $dr->Get(0)->CastTo($type);
		$dr->Close();
		return $r;
	}

	/**
	 * @api
	 * @param XType $type
	 * @param string $sql ... Pass the rest of the arguments after $sql
	 * @return array
	 */
	public static function ExecuteColumnOf(XType $type, $sql){ return self::ExecuteColumnOfX($type,$sql,array_slice(func_get_args(),2)); }
	/**
	 * @param string $sql
	 * @param XType $type
	 * @param array $params
	 * @return array
	 */
	public static function ExecuteColumnOfX(XType $type, $sql,$params=array()){
		$dr = self::ExecuteX($sql,$params);
		$r = array();
		while ($dr->Read())	$r[] = $dr->Get(0)->CastTo($type);
		$dr->Close();
		return $r;
	}

	public static function ExecuteTableOf($types=array(),$sql){ return self::ExecuteTableOfX($types,$sql,array_slice(func_get_args(),2)); }
	public static function ExecuteTableOfX($types,$sql,$params=array()){
		$dr = self::ExecuteX($sql,$params);
		$r = array();
		while ($dr->Read()) {
			$l = array();
			foreach ($types as $i => $type) $l[] = $dr->Get($i)->CastTo($type);
			$r[] = $l;
		}
		$dr->Close();
		return $r;
	}

	/**
	 * @api
	 * @param string $sql ... Pass the rest of the arguments after $sql
	 * @return DBValue
	 */
	public static function ExecuteScalar($sql){ return self::ExecuteScalarX($sql,array_slice(func_get_args(),1)); }
	/**
	 * @param string $sql
	 * @param array $params
	 * @return DBValue
	 */
	public static function ExecuteScalarX($sql,$params=array()){
		$dr = self::ExecuteX($sql,$params);
		$r = $dr->Read() ? $dr[0] : new DBValue(null);
		$dr->Close();
		return $r;
	}

	//
	//
	// Database patching system
	//
	//
	/** @var MultiMessage */
	private static $patching_system_logger = null;
	private static $patching_system_name = null;
	private static $patching_system_tablename = null;
	private static $patching_system_fieldnames = array();
	private static $patches = array();
	private static $patching_system_open_patcher = null;
	private static $patching_system_open_patch = null;
	private static $patching_system_is_dirty = false;
	private static $patching_system_is_slave = false;
	private static function SetPatchingSystemLogger(MultiMessage $logger = null){ self::$patching_system_logger = $logger; }
	private static function SetPatchingSystemSlave($v = true){ self::$patching_system_is_slave = $v; }
	public static function ClearPatchingSystem(){
		self::$patching_system_name = null;
		self::$patching_system_tablename = null;
		self::$patching_system_fieldnames = array();
		self::$patching_system_open_patcher = null;
		self::$patching_system_open_patch = null;
		self::$patching_system_is_dirty = false;
		self::$patches = array();
	}
	public static function IsPatchingSystemDirty(){
		return self::$patching_system_is_dirty;
	}
	public static function IsPatchingSystemSlave(){
		return self::$patching_system_is_slave;
	}
	public static function SetPatchingSystem($name,$tablename){
		self::ClearPatchingSystem();
		self::$patching_system_name = $name;
		self::$patching_system_tablename = $tablename;
	}
	public static function AddPatcher($patcher,$fieldname){
		self::$patching_system_fieldnames[$patcher] = $fieldname;
		self::$patches[$patcher] = null;
	}
	public static function GetPatch($patcher){
		$r = self::$patches[$patcher];
		if ($r === null){
			try{
				$r = self::ExecuteScalar('SELECT '.new SqlIden(self::$patching_system_fieldnames[$patcher]).' FROM '.new SqlIden(self::$patching_system_tablename))->AsInteger();
				self::$patches[$patcher] = $r;
			}
			catch (Exception $ex){}
		}
		return $r;
	}
	public static function SetPatch($patcher,$patch){
		self::ExecuteUpdateAll(self::$patching_system_tablename,self::$patching_system_fieldnames[$patcher],$patch);
		self::$patches[$patcher] = $patch;
	}
	public static function BeginPatchingSystem(){
		try{
			$r = 1!=self::ExecuteScalar('SELECT COUNT(*) FROM '.new SqlIden(self::$patching_system_tablename))->AsInteger();
		}
		catch (Exception $ex){
			$r = true;
		}
		if ($r) self::WriteToPatchingSystem('Installing module {'.self::$patching_system_name.'} in database '.Database::GetSchema().'@'.Database::GetServer().'.');
		return $r;
	}
	public static function WriteToPatchingSystem($message) {
		if (self::$patching_system_is_slave) throw new AccessHaltedException();
		self::$patching_system_is_dirty = true;
		if (self::$patching_system_logger === null) self::$patching_system_logger = new MultiMessage();
		if (!($message instanceof Message)) $message = new InfoMessage($message);
		self::$patching_system_logger[] = $message;
	}
	public static function HasPatch($patcher,$patch) {
		$current = self::GetPatch($patcher);
		return !is_null($current) && $current >= $patch;
	}
	public static function BeginPatch($patcher,$patch,$description=null){
		if (!self::HasPatch($patcher,$patch)) {
			if (!self::IsPatchingSystemDirty()){
				self::WriteToPatchingSystem('Upgrading module {'.self::$patching_system_name.'} in database '.Database::GetSchema().'@'.Database::GetServer().'.');
			}
			self::WriteToPatchingSystem('Applying patch {'.$patcher.':'.$patch.'}'.($description===null?'':': '.$description).'...');
			self::$patching_system_open_patcher = $patcher;
			self::$patching_system_open_patch = $patch;
			return true;
		}
		return false;
	}
	public static function ApplyPatch(){
		self::SetPatch(self::$patching_system_open_patcher,self::$patching_system_open_patch);
		self::WriteToPatchingSystem(new SuccessMessage('Patch {'.self::$patching_system_open_patcher.':'.self::$patching_system_open_patch.'} applied.'));
		self::$patching_system_open_patcher = null;
		self::$patching_system_open_patch = null;
	}

	//
	//
	// Advanced
	//
	//
	/**
	 * @api Since 1.3
	 * @param string $tablename ... Pass the rest of the parameters as strings in name-value pairs
	 * @return void
	 */
	public static function ExecuteInsert($tablename){
		$a = func_get_args();
		$z = func_num_args();
		$sql = 'INSERT INTO '.new SqlIden($tablename).' (';
		for($i=1;$i<$z;$i+=2){
			if ($i>1) $sql.=',';
			$sql.=new SqlIden($a[$i]);
		}
		$sql.=') VALUES (';
		for($i=1;$i<$z;$i+=2){
			if ($i>1) $sql.=',';
			$sql.=new Sql($a[$i+1]);
		}
		$sql.=')';
		self::Execute($sql);
	}

	/**
	 * ExecuteInsertNext( 'table_name' [ , 'field_name_1' , $field_value_1 [ , ... ] ] )
	 * ExecuteInsertNext( 'table_name' , 'primary_key_name' [ , 'field_name_1' , $field_value_1 [ , ... ] ] )
	 * @param $tablename
	 * @return ID
	 */
	public static function ExecuteInsertNext($tablename){
		$a = func_get_args();
		$z = func_num_args();
		$primarykey = $z%2 == 1 ? 'id' : $a[1];
		$id = self::ExecuteGetNextID($tablename,$primarykey);
		$sql = 'INSERT INTO '.new SqlIden($tablename).' ('.new SqlIden($primarykey);
		for($i=2-$z%2;$i<$z;$i+=2)
			$sql.=','.new SqlIden($a[$i]);
		$sql.=') VALUES ('.new Sql($id);
		for($i=2-$z%2;$i<$z;$i+=2){
			$sql.=','.new Sql($a[$i+1]);
		}
		$sql.=')';
		self::Execute($sql);
		return $id;
	}

	/**
	 * @api Since 1.3
	 * @param string $tablename ... Pass the rest of the parameters as strings in name-value pairs
	 * @return void
	 */
	public static function ExecuteUpdateAll($tablename){
		$a = func_get_args();
		$z = func_num_args();
		$sql = 'UPDATE '.new SqlIden($tablename).' SET ';
		for($i=1;$i<$z;$i+=2){
			if ($i>1) $sql.=',';
			$sql.=new SqlIden($a[$i]) .'='. new Sql($a[$i+1]);
		}
		self::Execute($sql);
	}
	/**
	 * @api Since 1.3
	 * @param string $tablename
	 * @param string $where ... Pass the rest of the parameters as strings in name-value pairs
	 * @return void
	 */
	public static function ExecuteUpdate($tablename,$where){
		$a = func_get_args();
		$z = func_num_args();
		$sql = 'UPDATE '.new SqlIden($tablename).' SET ';
		for($i=2;$i<$z;$i+=2){
			if ($i>2) $sql.=',';
			$sql.=new SqlIden($a[$i]) .'='. new Sql($a[$i+1]);
		}
		if (!is_null($where)) $sql .=' WHERE '.$where;
		self::Execute($sql);
	}

	public static function ExecuteCopyAll($tablename_dst, $tablename_src) {
		$a = func_get_args();
		$z = func_num_args();
		$sql = 'INSERT INTO '.new SqlIden($tablename_dst).' (';
		for ($i = 2; $i < $z; $i+=2)
			$sql .= ($i>2?',':'').new SqlIden($a[$i]);
		$sql.= ') SELECT ';
		for ($i = 3; $i < $z; $i+=2)
			$sql .= ($i>3?',':'').new SqlIden($a[$i]);
		$sql.= ' FROM '.new SqlIden($tablename_src);
		self::Execute($sql);
	}

	public static function ExecuteCopy($tablename_dst, $tablename_src, $where) {
		$a = func_get_args();
		$z = func_num_args();
		$sql = 'INSERT INTO '.new SqlIden($tablename_dst).' (';
		for ($i = 3; $i < $z; $i+=2)
			$sql .= ($i>3?',':'').new SqlIden($a[$i]);
		$sql.= ') SELECT ';
		for ($i = 4; $i < $z; $i+=2)
			$sql .= ($i>4?',':'').new SqlIden($a[$i]);
		$sql.= ' FROM '.new SqlIden($tablename_src);
		if (!is_null($where)) $sql .=' WHERE '.$where;
		self::Execute($sql);
	}

	/** @return DBReader */
	public static function ExecuteSelect($tablename,$where){
		$a = func_get_args();
		$z = func_num_args();
		if ($z === 2)
			$sql = 'SELECT *';
		else {
			$sql = 'SELECT ';
			for ($i = 2; $i < $z; $i++) {
				if ($i > 2) $sql .= ',';
				$sql .= new SqlIden($a[$i]);
			}
		}
		$sql .= ' FROM '.new SqlIden($tablename);
		if (!is_null($where)) $sql .=' WHERE '.$where;
		return self::Execute($sql);
	}
	/** @return DBReader */
	public static function ExecuteSelectAll($tablename){
		$a = func_get_args();
		$z = func_num_args();
		if ($z === 1)
			$sql = 'SELECT *';
		else {
			$sql = 'SELECT ';
			for ($i = 1; $i < $z; $i++) {
				if ($i > 1) $sql .= ',';
				$sql .= new SqlIden($a[$i]);
			}
		}
		$sql .= ' FROM '.new SqlIden($tablename);
		return self::Execute($sql);
	}

	public static function ExecuteUpdateLine($tablename,$id){
		$a = func_get_args();
		$z = func_num_args();
		$sql = 'UPDATE '.new SqlIden($tablename).' SET ';
		for($i=2;$i<$z;$i+=2){
			if ($i>2) $sql.=',';
			$sql.=new SqlIden($a[$i]) .'='. new Sql($a[$i+1]);
		}
		$sql .=' WHERE '.new SqlIden('id').'='.new Sql($id);
		self::Execute($sql);
	}

	public static function ExecuteDropTable($tablename,$force = false) {
		switch (self::$type) {
			case self::MYSQL:
			case self::SQLSERVER:
				$sql = 'DROP TABLE '.new SqlIden($tablename);
				break;
			case self::ORACLE:
				$sql = 'DROP TABLE '.new SqlIden($tablename).($force?' CASCADE CONSTRAINTS':'').' PURGE';
				break;
		}
		self::Execute($sql);
	}

	public static function ExecuteTableExists($tablename){
		try {
			self::Execute('SELECT COUNT(*) FROM '.new SqlIden($tablename));
		}
		catch (Exception $ex) {
			return false;
		}
		return true;
	}

	public static function ExecuteCreateTable($tablename){
		$a = func_get_args();
		$z = func_num_args();
		$sql = 'CREATE TABLE '.new SqlIden($tablename).' (';
		for($i=1;$i<$z;$i+=2){
			if ($i>1) $sql.=',';
			$sql.=new SqlIden($a[$i]).' '.Sql::GetDataType(self::$type,$a[$i+1]);
		}
		$sql.=')';
		if (self::$type == self::MYSQL) $sql .= ' ENGINE=INNODB';
		self::Execute($sql);
	}

	public static function ExecuteCreateStandardTable($tablename){
		$a = func_get_args();
		$z = func_num_args();
		$sql = 'CREATE TABLE '.new SqlIden($tablename).' ('.new SqlIden('id').' '.Sql::GetDataType(self::MYSQL,Sql::ID).' NOT NULL';
		for($i=1;$i<$z;$i+=2){
			$sql.=','.new SqlIden($a[$i]).' '.Sql::GetDataType(self::$type,$a[$i+1]);
		}
		$sql .= ',PRIMARY KEY ( '.new SqlIden('id').' ))';
		if (self::$type == self::MYSQL) $sql .= ' ENGINE=INNODB';
		self::Execute($sql);
	}

	public static function ExecuteAddPrimaryKey($tablename){
		$a = func_get_args();
		$z = func_num_args();
		$sql = 'ALTER TABLE '.new SqlIden($tablename).' ADD PRIMARY KEY(';
		for($i=1;$i<$z;$i++){
			if ($i>1) $sql .= ',';
			$sql.=new SqlIden($a[$i]);
		}
		$sql.=')';
		self::Execute($sql);
	}
	public static function ExecuteDropFields($tablename){
		$a = func_get_args();
		$z = func_num_args();
		for($i=1;$i<$z;$i++){
			$sql = 'ALTER TABLE '.new SqlIden($tablename).' DROP COLUMN '.new SqlIden($a[$i]);
			self::Execute($sql);
		}
	}
	public static function ExecuteAddFields($tablename){
		$a = func_get_args();
		$z = func_num_args();
		switch (self::$type){
			case self::MYSQL:
				for($i=1;$i<$z;$i+=2){
					$sql = 'ALTER TABLE '.new SqlIden($tablename).' ADD COLUMN '.new SqlIden($a[$i]).' '.Sql::GetDataType(self::$type,$a[$i+1]);
					self::Execute($sql);
				}
				break;
			case self::SQLSERVER:
			case self::ORACLE:
				for($i=1;$i<$z;$i+=2){
					$sql = 'ALTER TABLE '.new SqlIden($tablename).' ADD '.new SqlIden($a[$i]).' '.Sql::GetDataType(self::$type,$a[$i+1]);
					self::Execute($sql);
				}
				break;
		}
	}

	public static function ExecuteRenameFields($tablename){
		$a = func_get_args();
		$z = func_num_args();
		switch (self::$type){
			case self::MYSQL:
			case self::SQLSERVER:
				for($i=1;$i<$z;$i+=3){
					$sql = 'ALTER TABLE '.new SqlIden($tablename).' CHANGE '.new SqlIden($a[$i]).' '.new SqlIden($a[$i+1]).' '.Sql::GetDataType(self::$type,$a[$i+2]);
					self::Execute($sql);
				}
				break;
			case self::ORACLE:
				for($i=1;$i<$z;$i+=3){
					$sql = 'ALTER TABLE '.new SqlIden($tablename).' RENAME COLUMN '.new SqlIden($a[$i]).' TO '.new SqlIden($a[$i+1]);
					self::Execute($sql);
				}
				break;
		}
	}
	public static function ExecuteRecastFields($tablename){
		$a = func_get_args();
		$z = func_num_args();
		for($i=1;$i<$z;$i+=2){
			$tmp = 'tmp_'.Oxygen::HashRandom32();
			self::ExecuteAddFields($tablename,$tmp,$a[$i+1]);
			self::Execute('UPDATE '.new SqlIden($tablename).' SET '.new SqlIden($tmp).'='.new SqlIden($a[$i]));
			self::ExecuteDropFields($tablename,$a[$i]);
			self::ExecuteAddFields($tablename,$a[$i],$a[$i+1]);
			self::Execute('UPDATE '.new SqlIden($tablename).' SET '.new SqlIden($a[$i]).'='.new SqlIden($tmp));
			self::ExecuteDropFields($tablename,$tmp);
		}
	}
	public static function ExecuteNotNullFields($tablename) {
		$a = func_get_args();
		$z = func_num_args();

		switch(self::$type) {
			case self::MYSQL:
				for ($i = 1;$i < $z;$i += 2) {
					self::Execute('ALTER TABLE '.new SqlIden($tablename).' MODIFY '.new SqlIden($a[$i]).' '.Sql::GetDataType(self::$type,$a[$i+1]).' NOT NULL');
				}
				break;
			case self::SQLSERVER:
			case self::ORACLE:
				for ($i = 1;$i < $z;$i += 2) {
					self::Execute('ALTER TABLE '.new SqlIden($tablename).' ALTER COLUMN '.new SqlIden($a[$i]).' '.Sql::GetDataType(self::$type,$a[$i+1]).' NOT NULL');
				}
				break;
		}

	}

	public static function ExecuteRenameTable($tablename, $newName){
		switch(self::$type) {
			case self::MYSQL:
			case self::SQLSERVER:
				self::Execute('RENAME TABLE '.new SqlIden($tablename).' TO '.new SqlIden($newName));
				break;
			case self::ORACLE:
				self::Execute('RENAME '.new SqlIden($tablename).' TO '.new SqlIden($newName));
				break;
		}
	}

	public static function ExecuteCreateStandardSequence($tablename,$from=0) {
		self::ExecuteCreateSequence(self::hash_sequence($tablename,'id'),$from);
	}
  public static function ExecuteCreateSequence($sequence_name,$from=0) {
		switch(self::$type) {
			case self::MYSQL:
			case self::SQLSERVER:
				break;
			case self::ORACLE:
				$sql = 'CREATE SEQUENCE '.new SqlIden($sequence_name).' INCREMENT BY 1 START WITH '.$from.' NOMAXVALUE MINVALUE '.min(0,$from).' NOCYCLE NOCACHE';
				self::Execute($sql);
				break;
		}
  }
	public static function ExecuteDropStandardSequence($tablename) {
		self::ExecuteDropSequence(self::hash_sequence($tablename,'id'));
	}
  public static function ExecuteDropSequence($sequence_name) {
		switch(self::$type) {
			case self::MYSQL:
			case self::SQLSERVER:
				break;
			case self::ORACLE:
				$sql = 'DROP SEQUENCE '.new SqlIden($sequence_name);
				self::Execute($sql);
				break;
		}
  }

	/**
	 * @api Since 1.3
	 * @param string $tablename
	 * @return void
	 */
	public static function ExecuteDeleteAll($tablename){
		$sql = 'DELETE FROM '.new SqlIden($tablename);
		self::Execute($sql);
	}
	/**
	 * @api Since 1.3
	 * @param string $tablename
	 * @param string $where
	 * @return void
	 */
	public static function ExecuteDelete($tablename, $where){
		$sql = 'DELETE FROM '.new SqlIden($tablename).' WHERE '.$where;
		self::Execute($sql);
	}

	/** @return ID */
	public static function ExecuteGetNextID($tablename,$primarykey='id') {
		switch (self::$type) {
			default:
			case self::MYSQL:
				self::Execute('LOCK TABLES `oxy_ids` WRITE,`'.$tablename.'` WRITE');
				$id = self::ExecuteScalar('SELECT `LastID` FROM `oxy_ids` WHERE `TableName`=?',$tablename)->AsID();
				if ($id===null){
					$id = self::ExecuteScalar('SELECT MAX(`'.$primarykey.'`) FROM `'.$tablename.'`')->AsID();
					$id = $id===null ? new ID(0) : new ID($id->AsInt() + 1);
					self::Execute('INSERT INTO `oxy_ids` (`TableName`,`LastID`) VALUES (?,?)',$tablename,$id);
				}
				else {
					$id = new ID($id->AsInt() + 1);
					self::Execute('UPDATE `oxy_ids` SET `LastID`=? WHERE `TableName`=?',$id,$tablename);
				}
				self::Execute('UNLOCK TABLES');
				break;
			case self::SQLSERVER:
				self::TransactionBegin();
				$id = self::ExecuteScalar('SELECT [LastID] FROM [oxy_ids] WITH (TABLOCK, HOLDLOCK) WHERE [TableName]=?',$tablename)->AsID();
				if ($id===null){
					$id = self::ExecuteScalar('SELECT MAX(['.$primarykey.']) FROM ['.$tablename.'] WITH (TABLOCK, HOLDLOCK)')->AsID();
					$id = $id===null ? new ID(0) : new ID($id->AsInt() + 1);
					self::Execute('INSERT INTO [oxy_ids] ([TableName],[LastID]) VALUES (?,?)',$tablename,$id);
				}
				else {
					$id = new ID($id->AsInt() + 1);
					self::Execute('UPDATE [oxy_ids] SET [LastID]=? WHERE [TableName]=?',$id,$tablename);
				}
				self::TransactionCommit();
				break;
			case self::ORACLE:
				try {
					$id = self::ExecuteScalar('SELECT '.new SqlIden(self::hash_sequence($tablename,$primarykey)).'.NEXTVAL A FROM DUAL')->AsID();
				}
				catch (Exception $ex) {
					$id = self::ExecuteScalar('SELECT MAX('.new SqlIden($primarykey).') FROM '.new SqlIden($tablename))->AsID();
					$id = $id===null ? new ID(0) : new ID($id->AsInt() + 1);
					Database::ExecuteCreateSequence(self::hash_sequence($tablename,$primarykey),$id->AsInt());
					$id = self::ExecuteScalar('SELECT '.new SqlIden(self::hash_sequence($tablename,$primarykey)).'.NEXTVAL A FROM DUAL')->AsID();
				}
				break;
		}
		return $id;
	}

	/** @return ID */
	public static function ExecuteAdvanceNextIDTo($table_name,$next_iid,$primarykey='id') {
		if ($next_iid<= 0) return;
		switch (self::$type) {
			default:
			case self::MYSQL:
				self::Execute('LOCK TABLES `oxy_ids` WRITE,`'.$table_name.'` WRITE');
				$id = self::ExecuteScalar('SELECT `LastID` FROM `oxy_ids` WHERE `TableName`=?',$table_name)->AsID();
				if ($id===null){
					$id = self::ExecuteScalar('SELECT MAX(`'.$primarykey.'`) FROM `'.$table_name.'`')->AsID();
					if ($id===null || $id->AsInt() < $next_iid) {
						$id = new ID($next_iid - 1);
						self::Execute('INSERT INTO `oxy_ids` (`TableName`,`LastID`) VALUES (?,?)',$table_name,$id);
					}
				}
				elseif ($id->AsInt() < $next_iid-1) {
					$id = new ID($next_iid-1);
					self::Execute('UPDATE `oxy_ids` SET `LastID`=? WHERE `TableName`=?',$id,$table_name);
				}
				self::Execute('UNLOCK TABLES');
				break;
			case self::SQLSERVER:
				self::TransactionBegin();
				$id = self::ExecuteScalar('SELECT [LastID] FROM [oxy_ids] WITH (TABLOCK, HOLDLOCK) WHERE [TableName]=?',$table_name)->AsID();
				if ($id===null){
					$id = self::ExecuteScalar('SELECT MAX(['.$primarykey.']) FROM ['.$table_name.'] WITH (TABLOCK, HOLDLOCK)')->AsID();
					if ($id===null || $id->AsInt() < $next_iid) {
						$id = new ID($next_iid - 1);
						self::Execute('INSERT INTO [oxy_ids] ([TableName],[LastID]) VALUES (?,?)',$table_name,$id);
					}
				}
				elseif ($id->AsInt() < $next_iid-1) {
					$id = new ID($next_iid-1);
					self::Execute('UPDATE [oxy_ids] SET [LastID]=? WHERE [TableName]=?',$id,$table_name);
				}
				self::TransactionCommit();
				break;
			case self::ORACLE:
				$seq = self::hash_sequence($table_name,$primarykey);
				$id = self::ExecuteScalar('SELECT "LAST_NUMBER" FROM "USER_SEQUENCES" WHERE "SEQUENCE_NAME"='.new Sql($seq))->AsID();
				if ($id !== null) {
					while($id->AsInt() < $next_iid-1) {
						$id = self::ExecuteScalar('SELECT '.new SqlIden($seq).'.NEXTVAL A FROM DUAL')->AsID();
					}
				}
				else {
					$id = self::ExecuteScalar('SELECT MAX('.new SqlIden($primarykey).') FROM '.new SqlIden($table_name))->AsID();
					try { Database::ExecuteDropSequence($seq); } catch (Exception $ex){}
					if ($id===null||$id->AsInt()<$next_iid)
						Database::ExecuteCreateSequence($seq,$next_iid);
					else
						Database::ExecuteCreateSequence($seq,$id->AsInt()+1);
				}
				break;
		}
	}

	/** @return ID */
	public static function ExecuteGetNextIDFromSequence($sequence_name) {
		return self::ExecuteScalar('SELECT '.new SqlIden($sequence_name).'.NEXTVAL A FROM DUAL')->AsID();
	}

	private static function hash_sequence($tablename,$field='id'){ return 'seq_' . substr($tablename,0,15) . '_' . Oxygen::Hash32($tablename.'+'.$field); }
	private static function hash_foreign_key($tablename,$field){ return 'fk_' . Oxygen::Hash32($tablename.'+'.$field); }
	private static function hash_unique_key($tablename,$field){ return 'uq_' . Oxygen::Hash32($tablename.'+'.$field); }
	private static function hash_index($tablename,$field){ return 'idx_' . Oxygen::Hash32($tablename.'+'.$field); }
	public static function ExecuteAddForeignKeys($tablename){
		$a = func_get_args();
		$z = func_num_args();
		for($i=1;$i<$z;$i+=2){
      try { self::ExecuteAddIndices($tablename,$a[$i]); } catch (Exception $ex){}
			self::Execute('ALTER TABLE '.new SqlIden($tablename).' ADD CONSTRAINT '.new SqlIden( self::hash_foreign_key($tablename,$a[$i]) ).' FOREIGN KEY ('.new SqlIden($a[$i]).') REFERENCES '.new SqlIden($a[$i+1]).' ('.new SqlIden('id').')');
		}
	}
	public static function ExecuteAddForeignKeysWithAltTarget($tablename){
		$a = func_get_args();
		$z = func_num_args();
		for($i=1;$i<$z;$i+=3){
			try { self::ExecuteAddIndices($tablename,$a[$i]);  } catch (Exception $ex){}
			self::Execute('ALTER TABLE '.new SqlIden($tablename).' ADD CONSTRAINT '.new SqlIden( self::hash_foreign_key($tablename,$a[$i]) ).' FOREIGN KEY ('.new SqlIden($a[$i]).') REFERENCES '.new SqlIden($a[$i+1]).' ('.new SqlIden($a[$i+2]).')');
		}
	}
	public static function ExecuteDropForeignKeys($tablename){
		$a = func_get_args();
		$z = func_num_args();
		for($i=1;$i<$z;$i++){
			try { self::ExecuteDropIndices($tablename,$a[$i]);  } catch (Exception $ex){}
			switch (self::$type) {
				case self::MYSQL:
				case self::SQLSERVER:
					self::Execute('ALTER TABLE '.new SqlIden($tablename).' DROP FOREIGN KEY '.new SqlIden(self::hash_foreign_key($tablename,$a[$i])));
					break;
				case self::ORACLE:
					self::Execute('ALTER TABLE '.new SqlIden($tablename).' DROP CONSTRAINT '.new SqlIden(self::hash_foreign_key($tablename,$a[$i])));
					break;
			}
		}
	}

	public static function ExecuteAddComplexForeignKey($tablename_src,$tablename_dst){
		$a = func_get_args();
		$z = func_num_args();
		$q1 = array(); for($i=2;$i<$z;$i+=2) $q1[] = $a[$i];
		$q2 = array(); for($i=3;$i<$z;$i+=2) $q2[] = $a[$i];
		$key = self::hash_foreign_key($tablename_src, implode('+',$q1));
		$sql_fields_src = implode(',',array_map(function($x){return new SqlIden($x);},$q1));
		$sql_fields_dst = implode(',',array_map(function($x){return new SqlIden($x);},$q2));
		try { call_user_func_array('Database::ExecuteAddIndex',array_merge(array($tablename_src),$q1)); } catch (Exception $ex){}
		try { call_user_func_array('Database::ExecuteAddUniqueKey',array_merge(array($tablename_dst),$q2)); } catch (Exception $ex){}
		self::Execute('ALTER TABLE '.new SqlIden($tablename_src).' ADD CONSTRAINT '.new SqlIden( $key ).' FOREIGN KEY ('.$sql_fields_src.') REFERENCES '.new SqlIden($tablename_dst).' ('.$sql_fields_dst.')');
	}
	public static function ExecuteAddUniqueKey($tablename){
		$a = func_get_args();
		$key = self::hash_unique_key($tablename, implode('+',array_slice($a,1)));
		$sql_fields = implode(',',array_map(function($x){return new SqlIden($x);},array_slice($a,1)));
		self::Execute('ALTER TABLE '.new SqlIden($tablename).' ADD CONSTRAINT '.new SqlIden( $key ).' UNIQUE ('.$sql_fields.')');
	}
	public static function ExecuteAddUniqueKeys($tablename){
		$a = func_get_args();
		$z = func_num_args();
		for($i=1;$i<$z;$i++){
			self::Execute('ALTER TABLE '.new SqlIden($tablename).' ADD CONSTRAINT '.new SqlIden( self::hash_unique_key($tablename,$a[$i]) ).' UNIQUE ('.new SqlIden($a[$i]).')');
		}
	}

	public static function ExecuteAddIndices($tablename){
		$a = func_get_args();
		$z = func_num_args();
		for($i=1;$i<$z;$i++){
			self::Execute('CREATE INDEX '.new SqlIden(self::hash_index($tablename,$a[$i])).' ON '.new SqlIden($tablename).' ('.new SqlIden($a[$i]).')');
		}
	}
	public static function ExecuteAddIndex($tablename){
		$a = func_get_args();
		$key = self::hash_index($tablename, implode('+',array_slice($a,1)));
		$sql_fields = implode(',',array_map(function($x){return new SqlIden($x);},array_slice($a,1)));
		self::Execute('CREATE INDEX '.new SqlIden($key).' ON '.new SqlIden($tablename).' ('.$sql_fields.')');
	}
	public static function ExecuteAddUniqueIndices($tablename){
		$a = func_get_args();
		$z = func_num_args();
		for($i=1;$i<$z;$i++){
			self::Execute('CREATE UNIQUE INDEX '.new SqlIden(self::hash_index($tablename,$a[$i])).' ON '.new SqlIden($tablename).' ('.new SqlIden($a[$i]).')');
		}
	}
	public static function ExecuteAddUniqueIndex($tablename){
		$a = func_get_args();
		$key = self::hash_index($tablename, implode('+',array_slice($a,1)));
		$sql_fields = implode(',',array_map(function($x){return new SqlIden($x);},array_slice($a,1)));
		self::Execute('CREATE UNIQUE INDEX '.new SqlIden($key).' ON '.new SqlIden($tablename).' ('.$sql_fields.')');
	}
	public static function ExecuteDropIndices($tablename){
		$a = func_get_args();
		$z = func_num_args();
		for($i=1;$i<$z;$i++){
			switch (self::$type) {
				default:
				case self::MYSQL:
					self::Execute('ALTER TABLE '.new SqlIden($tablename).' DROP INDEX '.new SqlIden(self::hash_index($tablename,$a[$i])));
					break;
				case self::SQLSERVER:
					self::Execute('ALTER TABLE '.new SqlIden($tablename).' DROP INDEX '.new SqlIden(self::hash_index($tablename,$a[$i])));
					break;
				case self::ORACLE:
					self::Execute('DROP INDEX '.new SqlIden(self::hash_index($tablename,$a[$i])));
					break;
			}
		}
	}
	public static function ExecuteDropIndex($tablename){
		$a = func_get_args();
		//$z = func_num_args();
		$key = self::hash_index($tablename, implode('+',array_slice($a,1)));
		switch (self::$type) {
			case self::MYSQL:
				self::Execute('ALTER TABLE '.new SqlIden($tablename).' DROP INDEX '.new SqlIden($key));
				break;
			case self::SQLSERVER:
				self::Execute('ALTER TABLE '.new SqlIden($tablename).' DROP INDEX '.new SqlIden($key));
				break;
			case self::ORACLE:
				self::Execute('DROP INDEX '.new SqlIden($key));
				break;
		}
	}
	public static function ExecuteDropIndicesRaw($tablename){
		$a = func_get_args();
		$z = func_num_args();
		for($i=0;$i<$z;$i++){
			self::Execute('DROP INDEX '.new SqlIden($a[$i]));
		}
	}
	public static function ExecuteDropConstraints($tablename){
		$a = func_get_args();
		$z = func_num_args();
		for($i=1;$i<$z;$i++){
			self::Execute('ALTER TABLE '.new SqlIden($tablename).' DROP CONSTRAINT '.new SqlIden($a[$i]));
		}
	}

	public static function ExecuteDropPrimaryKey($tablename){
		self::Execute('ALTER TABLE '.new SqlIden($tablename).' DROP PRIMARY KEY');
	}

	public static function ExecuteMetaForeignKeys_Oracle($tablename) {
		$r = array();
		$dr = Database::Execute('SELECT a.CONSTRAINT_NAME C,b.POSITION I,b.COLUMN_NAME F,c.TABLE_NAME TT,c.COLUMN_NAME FF FROM ALL_CONSTRAINTS a,ALL_CONS_COLUMNS b,ALL_CONS_COLUMNS c WHERE a.CONSTRAINT_TYPE=? AND b.TABLE_NAME=? AND a.CONSTRAINT_NAME=b.CONSTRAINT_NAME AND a.R_CONSTRAINT_NAME=c.CONSTRAINT_NAME AND b.POSITION=c.POSITION ORDER BY a.CONSTRAINT_NAME,b.POSITION','R',$tablename);
		while($dr->Read()) {
			$c = $dr['C']->AsString();
			if (array_key_exists($c,$r))
				$r[$c][$dr['F']->AsString()] = $dr['FF']->AsString();
			else
				$r[$c] = array('' => $dr['TT']->AsString(),$dr['F']->AsString()=>$dr['FF']->AsString());
		}
		$dr->Close();
		return $r;
	}
	public static function ExecuteMetaInverseForeignKeys_Oracle($tablename) {
		$r = array();
		$dr = Database::Execute('SELECT c.COLUMN_NAME F,b.TABLE_NAME TT,b.COLUMN_NAME FF FROM ALL_CONSTRAINTS a,ALL_CONS_COLUMNS b,ALL_CONS_COLUMNS c WHERE a.CONSTRAINT_TYPE=? AND c.TABLE_NAME=? AND a.CONSTRAINT_NAME=b.CONSTRAINT_NAME and a.R_CONSTRAINT_NAME=c.CONSTRAINT_NAME','R',$tablename);
		while($dr->Read())
			$r[] = array('F'=>$dr['F']->AsString(),'TT'=>$dr['TT']->AsString(),'FF'=>$dr['FF']->AsString());
		$dr->Close();
		return $r;
	}

	public static function CreateSchema($server,$schema,$username,$password,$type=self::MYSQL){
		if ($type == self::MYSQL){
			self::PushConnection();
			self::SetConnection( new DatabaseConnection($server,$schema,$username,$password,$type,false) );
			try{
				$a = explode(':',$server);
				$charset = Oxygen::GetCharset();
				if ($charset == 'UTF-8') $charset = 'utf8'; elseif ($charset == 'ISO-8859-1') $charset = 'latin1';
				self::$cx->cn = new PDO('mysql:host='.$a[0].(count($a)>1?';port='.$a[1]:'').';charset='.$charset, $username, $password, array(PDO::ATTR_PERSISTENT => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION) );
				self::$cn = self::$cx->cn;
			}
			catch (Exception $ex){
				self::PopConnection();
				throw new ApplicationException(oxy::txtMsgCannotConnectToDatabase().'

'. $server. '
'.$ex->getMessage());
			}
			try{
				Database::Execute('CREATE DATABASE '.new SqlIden($schema).' DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci');
			}
			catch (Exception $ex){
				self::PopConnection();
				throw new ApplicationException(oxy::txtMsgCannotCreateDatabase().'

'. $server.'/'.$schema. '
'.$ex->getMessage());
			}
			self::PopConnection();
		}
		else throw new NonImplementedException('CreateSchema is not implemented in for this database.');
	}

	public static function TransactionBegin(){
		self::RequireConnection();
		self::$cn->beginTransaction();
	}
	public static function TransactionCommit(){
		self::RequireConnection();
		self::$cn->commit();
	}
	public static function TransactionRollback(){
		self::RequireConnection();
		self::$cn->rollBack();
	}
}


text:
package org.apache.taverna.mobile.activities;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;

import org.apache.taverna.mobile.R;
import org.apache.taverna.mobile.fragments.workflowdetails.RunFragment;

public class RunResult extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_run_result);
        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, RunFragment.newInstance())
                    .commit();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        return false;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

       this.finish();

        return super.onOptionsItemSelected(item);
    }

}

redpajama_set_name: RedPajamaGithub


text:
<?php

declare(strict_types=1);

namespace ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity;

use ApiPlatform\Core\Annotation\ApiProperty;
use ApiPlatform\Core\Annotation\ApiResource;
use ApiPlatform\Core\Tests\Fixtures\TestBundle\Dto\MessengerResponseInput;

/**
 * @ApiResource(messenger="input", input=MessengerResponseInput::class)
 */
class MessengerWithResponse
{
    /**
     * @ApiProperty(identifier=true)
     */
    public $id;
    /**
     * @var string
     */
    public $name;
}


text:
#include "trikKitInterpreterCommon/trikAdditionalPreferences.h"
#include "ui_trikAdditionalPreferences.h"

#include <qrkernel/settingsManager.h>

using namespace trik;
using namespace qReal;

TrikAdditionalPreferences::TrikAdditionalPreferences(const QStringList &realRobotNames, QWidget *parent)
	: AdditionalPreferences(parent)
	, mUi(new Ui::TrikAdditionalPreferences)
	, mRealRobotNames(realRobotNames)
{
	mUi->setupUi(this);
	mUi->robotImagePicker->configure("trikRobot2DImage", tr("2D robot image:"));
}

TrikAdditionalPreferences::~TrikAdditionalPreferences()
{
	delete mUi;
}

void TrikAdditionalPreferences::save()
{
	SettingsManager::setValue("TrikTcpServer", mUi->tcpServerLineEdit->text());
	mUi->robotImagePicker->save();
	emit settingsChanged();
}

void TrikAdditionalPreferences::restoreSettings()
{
	mUi->tcpServerLineEdit->setText(SettingsManager::value("TrikTcpServer").toString());
	mUi->robotImagePicker->restore();
}

void TrikAdditionalPreferences::onRobotModelChanged(kitBase::robotModel::RobotModelInterface * const robotModel)
{
	const bool isReal = !robotModel->name().contains("TwoD");
	mUi->tcpSettingsGroupBox->setVisible(isReal);
}


text:
/* ************************************************************************** */
/*                                                                            */
/*                                                   __                       */
/*   SoftPWMControl.cpp                            <(o )___                   */
/*                                                  ( ._> /   - Weh.          */
/*   By: prp <tfm357@gmail.com>                    --`---'-------------       */
/*                                                 54 69 6E 66 6F 69 6C       */
/*   Created: 2018/09/05 07:41:31 by prp              2E 54 65 63 68          */
/*   Updated: 2018/09/09 08:41:10 by prp              50 2E 52 2E 50          */
/*                                                                            */
/* ************************************************************************** */

#include "SoftPWMControl.hpp"
#include "DebugTools.hpp"

using namespace Lightshow;

void SoftPWMControl::execute(SoftPWMControl* controller) {

	while (controller->to_continue) {

		float duty_cycle = controller->duty_cycle.load();
		Nanos period     = controller->period.load();

		if (controller->duty_cycle != 0)
			controller->pin.set_pin_value(GPIO_ON);

		std::this_thread::sleep_for(period * duty_cycle);

		controller->pin.set_pin_value(GPIO_OFF);

		std::this_thread::sleep_for(period - (period * duty_cycle));
	}
}

void SoftPWMControl::launch_thread() {
	using TF::Debug::print_warning_line;

	if (this->to_continue)
		print_warning_line(
		    "WRN -> [SoftPWMControl::launch_thread]: Thread already started.");
	this->to_continue        = true;
	this->pin_control_thread = std::thread(SoftPWMControl::execute, this);
}

void SoftPWMControl::join_thread() {
	this->to_continue = false;
	this->pin_control_thread.join();
}

SoftPWMControl::SoftPWMControl(GPIOInterface& pin) : pin(pin) {
	this->period      = std::chrono::milliseconds(8);
	this->to_continue = false;
	this->duty_cycle  = 0;
}

SoftPWMControl::SoftPWMControl(GPIOInterface& pin, const float duty_cycle)
    : SoftPWMControl(pin) {
	this->duty_cycle = duty_cycle;
}

SoftPWMControl::SoftPWMControl(GPIOInterface& pin,
                               const float    duty_cycle,
                               const Nanos    period)
    : SoftPWMControl(pin, duty_cycle) {
	this->period = period;
}

SoftPWMControl::~SoftPWMControl() {
	if (this->to_continue)
		this->join_thread();
}


text:
<?php

namespace Sylius\Component\Core\Model;

use Sylius\Component\Channel\Model\ChannelsAwareInterface;
use Sylius\Component\Promotion\Model\PromotionInterface as BasePromotionInterface;

/**
 * @author Kristian Loevstroem <kristian@loevstroem.dk>
 */
interface PromotionInterface extends
    BasePromotionInterface,
    ChannelsAwareInterface
{
}


text:
import { Injectable } from '@angular/core';
import { RuntimeAppDefinitionsApi, AppDefinitionRepresentation } from '@alfresco/js-api';
import { Observable, from, throwError } from 'rxjs';
import { AlfrescoApiService } from './alfresco-api.service';
import { LogService } from './log.service';
import { map, catchError } from 'rxjs/operators';

@Injectable({
    providedIn: 'root'
})
export class AppsProcessService {

    _appsApi: RuntimeAppDefinitionsApi;
    get appsApi(): RuntimeAppDefinitionsApi {
        this._appsApi = this._appsApi ?? new RuntimeAppDefinitionsApi(this.apiService.getInstance());
        return this._appsApi;
    }

    constructor(private apiService: AlfrescoApiService,
                private logService: LogService) {
    }

    /**
     * Gets a list of deployed apps for this user.
     *
     * @returns The list of deployed apps
     */
    getDeployedApplications(): Observable<AppDefinitionRepresentation[]> {
        return from(this.appsApi.getAppDefinitions())
            .pipe(
                map((response: any) => response.data),
                catchError((err) => this.handleError(err))
            );
    }

    /**
     * Gets a list of deployed apps for this user, where the app name is `name`.
     *
     * @param name Name of the app
     * @returns The list of deployed apps
     */
    getDeployedApplicationsByName(name: string): Observable<AppDefinitionRepresentation> {
        return from(this.appsApi.getAppDefinitions())
            .pipe(
                map((response: any) => response.data.find((app) => app.name === name)),
                catchError((err) => this.handleError(err))
            );
    }

    /**
     * Gets the details for a specific app ID number.
     *
     * @param appId ID of the target app
     * @returns Details of the app
     */
    getApplicationDetailsById(appId: number): Observable<AppDefinitionRepresentation> {
        return from(this.appsApi.getAppDefinitions())
            .pipe(
                map((response: any) => response.data.find((app) => app.id === appId)),
                catchError((err) => this.handleError(err))
            );
    }

    private handleError(error: any) {
        this.logService.error(error);
        return throwError(error || 'Server error');
    }

}


text:
package com.apptentive.android.sdk.module.messagecenter.view;

import android.content.Context;
import android.content.res.Resources;
import android.view.LayoutInflater;
import android.widget.FrameLayout;
import android.widget.TextView;
import com.apptentive.android.sdk.Log;
import com.apptentive.android.sdk.R;
import com.apptentive.android.sdk.model.Message;
import com.apptentive.android.sdk.module.metric.MetricModule;
import com.apptentive.android.sdk.util.Util;

/**
 * @author Sky Kelsey
 */
abstract public class PersonalMessageView<T extends Message> extends MessageView<T> {

	public PersonalMessageView(Context context, final T message) {
		super(context, message);
	}

	/**
	 * Perform any view initialization here. Make sure to call super.init() first to initialise the parent hierarchy.
	 */
	protected void init(T message) {
		super.init(message);
		LayoutInflater inflater = LayoutInflater.from(context);
		if (message.isOutgoingMessage()) {
			inflater.inflate(R.layout.apptentive_message_outgoing, this);
		} else {
			inflater.inflate(R.layout.apptentive_message_incoming, this);
		}
	}

	/**
	 * Call when you need to update the view with changed message contents. This should ONLY be called after the view has
	 * been initialized with a message.
	 *
	 * @param newMessage The new message whose contents we want to display.
	 */
	public void updateMessage(final T newMessage) {
		T oldMessage = message;
		super.updateMessage(newMessage);

		// Set timestamp
		TextView timestampView = (TextView) findViewById(R.id.apptentive_message_timestamp);
		timestampView.setText(createTimestamp(message.getCreatedAt()));

		// Set name
		TextView nameView = (TextView) findViewById(R.id.apptentive_message_sender_name);
		String name = message.getSenderUsername();
		if (name == null || name.equals("")) {
			Resources resources = context.getResources();
			name = newMessage.isOutgoingMessage() ? resources.getString(R.string.apptentive_you) : resources.getString(R.string.apptentive_developer);
		}
		nameView.setText(name);

		// Set profile photo
		final FrameLayout avatarFrame = (FrameLayout) findViewById(R.id.apptentive_message_avatar);
		String photoUrl = message.getSenderProfilePhoto();
		boolean avatarNeedsUpdate = oldMessage == null || (photoUrl != null && !photoUrl.equals(oldMessage.getSenderProfilePhoto()));
		if (avatarNeedsUpdate) {
			// Perform the fetch on a new thread, and the UI update on the UI thread so we don't block everything.
			Thread thread = new Thread() {
				public void run() {
					final AvatarView avatar = new AvatarView(context, message.getSenderProfilePhoto());
					post(new Runnable() {
						public void run() {
							avatarFrame.addView(avatar);
						}
					});
				}
			};
			Thread.UncaughtExceptionHandler handler = new Thread.UncaughtExceptionHandler() {
				@Override
				public void uncaughtException(Thread thread, Throwable throwable) {
					Log.w("UncaughtException in PersonalMessageView.", throwable);
					MetricModule.sendError(context.getApplicationContext(), throwable, null, null);
				}
			};
			thread.setUncaughtExceptionHandler(handler);
			thread.setName("Apptentive-MessageViewLoadAvatar");
			thread.start();
		}
	}

	protected String createTimestamp(Double seconds) {
		Resources resources = context.getResources();
		if (seconds != null) {
			return Util.secondsToDisplayString(resources.getString(R.string.apptentive_message_sent_timestamp_format), seconds);
		}
		return resources.getString(R.string.apptentive_sending);
	}
}


text:
hsp-web-component
=================

Hashspace and Webcomponents


text:
package eu.epfc.cours3449.LibrarySQL;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.*;
import java.util.Scanner;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import eu.epfc.cours3449.LibrarySQL.*;

public class ManageLibrary {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        Boolean cont = true;
        String option=new String();
        Scanner input = new Scanner(System.in);

        while (cont) {
            System.out.println("Management of Library");
            System.out.println("To manage authors, enter 'A'");
            System.out.println("To manage editions, enter 'E'");
            System.out.println("To manage works, enter 'W'");
            System.out.println("To manage books, enter 'B'");
            System.out.println("To quit this menu, enter 'Q'");
            option = input.nextLine();
            System.out.println("");
            switch (option) {
                case "A": ManageAuthors.main(null);break;
                case "E": ManageEditions.main(null); break;
                case "W": ManageWorks.main(null); break;
                case "B": ManageBooks.main(null); break;
                case "Q": cont=false; break;
                default : System.out.println("The value entered is not valid, please enter a correct one");
            }
        }
    }

}


text:
<!DOCTYPE html>

	<base href=/ >
	<title>Aulas AMiGAS</title>
	<meta charset=UTF-8>
	<meta name=viewport content="width=device-width,initial-scale=1">
	<link href="https://fonts.googleapis.com/css?family=Lato:300,300i,400,400i,700,700i,900,900i" rel=stylesheet>

	<link href="app.css" rel="stylesheet">

Hello World!

	<animations></animations>


text:
package models;

import java.util.List;
import views.formdata.RainGardenFormData;

/**
 * Stores a list of contacts in a data structure.
 */
public class RainGardenDB {

  /**
   * Add rain garden.
   *
   * @param formData Data form data.
   * @param userInfo Registering user.
   * @return The rain garden that has been added.
   */
  public static RainGarden addRainGarden(RainGardenFormData formData, UserInfo userInfo) {
    RainGarden garden;
    if (formData.id == -1) {
      garden = new RainGarden(formData.title, formData.propertyType, formData.address, formData.hideAddress,
                              formData.description, formData.month + "/" + formData.day + "/" + formData.year,
                              formData.plants, formData.rainGardenSize, formData.waterFlowSourceSize,
                              formData.waterFlowDescription, formData.infiltrationRate);
      garden.setOwner(userInfo);
      garden.getOwner().getGardens().add(garden);
      garden.save();
      return garden;
    }
    else {
      garden = RainGardenDB.getRainGarden(formData.id);
      garden.setTitle(formData.title);
      garden.setPropertyType(formData.propertyType);
      garden.setAddress(formData.address);
      garden.setHideAddress(formData.hideAddress);
      garden.setDescription(formData.description);
      garden.setDateInstalled(formData.month + "/" + formData.day + "/" + formData.year);
      garden.setPlants(formData.plants);
      garden.setRainGardenSize(formData.rainGardenSize);
      garden.setWaterFlowSourceSize(formData.waterFlowSourceSize);
      garden.setWaterFlowDescription(formData.waterFlowDescription);
      garden.setInfiltrationRate(formData.infiltrationRate);
      garden.save();
      return garden;
    }
  }

  /**
   * Return list of rain gardens.
   *
   * @return List of rain gardens.
   */
  public static List<RainGarden> getRainGardens() {
    return RainGarden.find().all();
  }

  /**
   * Return rain garden with matching ID.
   *
   * @param id The ID to be matched.
   * @return The rain garden with the matching ID.
   */
  public static RainGarden getRainGarden(long id) {
   return RainGarden.find().byId(id);
  }

  /**
   * Delete a rain garden.
   *
   * @param id ID of rain garden.
   */
  public static void deleteRainGarden(long id) {
    if (hasID(id)) {
      RainGarden.find().byId(id).delete();
    }
  }

  /**
   * Check if database has ID.
   * @param id ID to check.
   * @return True if the database has the ID, false otherwise.
   */
  public static boolean hasID(long id) {
    return (getRainGarden(id) != null);
  }
}


text:
pagarme-cardhash-android
========================

A very simple Android lib to generate [Pagar.me](https://pagar.me/) card hashs.

Installation
------------

To install, just copy the CardHash class into your project, update the package declaration, and that's it. Actually, no; this lib uses [Volley](https://developer.android.com/training/volley/index.html), so you'll need to have that installed too.

Better install options coming soon.

Usage
-----

Put your Pagar.me encryption key on you manifest:

```xml
<meta-data
    android:name="me.pagar.EncryptionKey"
    android:value="my_encryption_key" />
```

Then do something like this:

```java
CardHash card = new CardHash();
card.holderName = "Some Name";
card.number = "4111111111111111"; // no whitespaces
card.expirationDate = "0817";
card.cvv = "123";
card.generate(context, new CardHash.Listener() {
    @Override
    public void onSucess(String cardHash) {
        // do your thing
    }
    @Override
    public void onError(Exception e) {
        if (e instanceof VolleyError) {
          // show network error message
        } else {
          // show strange error message
        }
    }
});
```

License
-------

MIT/X11


text:
package org.syphr.mythtv.db;

import org.syphr.mythtv.db.schema.Channel;
import org.syphr.mythtv.db.schema.Program;
import org.syphr.mythtv.db.schema.Recorded;
import org.syphr.mythtv.db.schema.Settings;
import org.syphr.mythtv.db.schema.TvChain;

public class Table
{
    private static final String CHANNEL = Channel.class.getName();
    private static final String PROGRAM = Program.class.getName();
    private static final String RECORDED = Recorded.class.getName();
    private static final String SETTINGS = Settings.class.getName();
    private static final String TV_CHAIN = TvChain.class.getName();

    private Table()
    {
        /*
         * Static constants
         */
    }
}


text:
author: reilly-smith
title: 'Stay Positive'
date: '2016-12-29 00:03:00'
cover: 'positive-banner.jpg'
---

We hope your holidays have been wonderful.

This week, instead of a gift from us at LBRY, we give you a gift from users of the LBRY network, Tim and Steve.

With the recent surge in Bitcoin, from whose codebase LBRY owes many thanks, it is a fitting 2016 send off to share the first LBRY-exclusive book release, on finance and cryptocurrency:

Enjoy [*The Little Book of Positive Returns In Negative Rates*](lbry://positivereturnsinnegativerates) by Steve Park and Tim Smith.

![Positive Returns In Negative Rates](/img/news/positive-inline.jpg)

Available exclusively at `lbry://positivereturnsinnegativerates` for 250 LBC ($2.50).

> *Life doesn't come with negative interest rates; life only comes with occasional failure, and failure is an event that occurs and can be minimized if we learn from it and (or) if we prepare for what caused our failure.*

> -Tim Smith and Steve Park

Tim and Steve are long-time cryptocurrency advocates. If you have questions about life on crypto, they've probably answered in their writings at http://fintekneeks.com.

Here's to LBRY in 2017 and a happy new year!

**Check out the LBRY film playlist when you're done reading!**
- [*Jingle Bell Rocks!*](https://open.lbry.com/jinglebellrocks:7)
- [*Rare Exports: A Christmas Tale*](https://open.lbry.com/@oscopelabs:4/rare-exports:2)
- [*Coherence*](https://open.lbry.com/coherence:b)
- [*It's A Disaster*](https://open.lbry.com/itsadisaster:f)
- [*Bellflower*](https://open.lbry.com/bellflower:d)
- [*The Internet's Own Boy*](https://open.lbry.com/theinternetsownboy:2)
- [*TPB AFK: The Pirate Bay Away from Keyboard*](https://open.lbry.com/tpbafk:b)
- [*S&M Lawn Care*](lbry://smlawncare)
- [*Cinema Six*](https://open.lbry.com/cinemasix:4)

**Not on LBRY yet?** [Get an invite here](/get). Do you write novels? Email [reilly@lbry.com](mailto:reilly@lbry.com), and we'll help you make publishing outside of Amazon a reality.


text:
package org.kuali.rice.kim.api.jaxb;

import javax.xml.bind.MarshalException;
import javax.xml.bind.UnmarshalException;
import javax.xml.bind.annotation.adapters.NormalizedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlAdapter;

import org.apache.commons.lang.StringUtils;
import org.kuali.rice.core.util.jaxb.NameAndNamespacePair;
import org.kuali.rice.kim.api.services.KimApiServiceLocator;
import org.kuali.rice.kim.api.type.KimTypeContract;

/**
 * An XML adapter that converts between a NameAndNamespacePair and a KIM type ID.
 *
 * @author Kuali Rice Team (rice.collab@kuali.org)
 */
public class NameAndNamespacePairToKimTypeIdAdapter extends XmlAdapter<NameAndNamespacePair,String> {

    /**
     * @see javax.xml.bind.annotation.adapters.XmlAdapter#unmarshal(java.lang.Object)
     */
    @Override
    public String unmarshal(NameAndNamespacePair v) throws Exception {
        if (v != null) {
            KimTypeContract kimType = KimApiServiceLocator.getKimTypeInfoService().findKimTypeByNameAndNamespace(
                    v.getNamespaceCode(), new NormalizedStringAdapter().unmarshal(v.getName()));
            if (kimType == null) {
                throw new UnmarshalException("Cannot find KIM Type with namespace \"" + v.getNamespaceCode() + "\" and name \"" + v.getName() + "\"");
            }
            return kimType.getId();
        }
        return null;
    }

    /**
     * @see javax.xml.bind.annotation.adapters.XmlAdapter#marshal(java.lang.Object)
     */
    @Override
    public NameAndNamespacePair marshal(String v) throws Exception {
        if (v != null) {
            KimTypeContract kimType = KimApiServiceLocator.getKimTypeInfoService().getKimType(StringUtils.trim(v));
            if (kimType == null) {
                throw new MarshalException("Cannot find KIM Type with ID \"" + v + "\"");
            }
            return new NameAndNamespacePair(kimType.getNamespaceCode(), kimType.getName());
        }
        return null;
    }

}


text:
package com.eclipsesource.schema

import com.eclipsesource.schema.drafts.{Version4, Version7}
import com.eclipsesource.schema.internal.refs.{SchemaRefResolver, SchemaResolutionScope}
import com.eclipsesource.schema.internal.validators.ArrayValidator
import com.eclipsesource.schema.test.JsonSpec
import org.specs2.mutable.Specification
import play.api.libs.json.{JsNumber, Json}

class ItemsSpec extends Specification with JsonSpec {

  "validate draft4" in {
    import Version4._
    implicit val validator: SchemaValidator = SchemaValidator(Some(Version4))
    validate("items", "draft4")
  }

  "validate draft7" in {
    import Version7._
    implicit val validator: SchemaValidator = SchemaValidator(Some(Version7))
    validate("items", "draft7")
  }

  "validate array with some invalid items" in {
    import Version4._
    implicit val validator: SchemaValidator = SchemaValidator(Some(Version4))
    val schema = JsonSource.schemaFromString(
      """{
        |  "type": "array",
        |  "items": {
        |    "minimum": 3
        |  }
        |}""".stripMargin).get

    val instance = Json.arr(2, 3, 4, 1)

    val result = validator.validate(schema, instance)
    result.isError must beTrue
    result.asEither must beLeft.like { case error =>
      error.toJson.value must haveLength(2)
    }
  }

  "validate array with wrong json type" in {
    import Version4._
    val schema = JsonSource.schemaFromString(
      """{
        |  "type": "array",
        |  "items": {
        |    "minimum": 3
        |  }
        |}""".stripMargin).get.asInstanceOf[SchemaArray]
    val context = SchemaResolutionContext(SchemaRefResolver(Version4), SchemaResolutionScope(schema))
    val result = ArrayValidator.validate(schema, JsNumber(2), context)
    result.isFailure must beTrue
  }
}


text:
package com.blocklatency.embeddedlinuxjvm.commandline;

import lombok.Builder;

import java.util.Collection;

@Builder
public class LinuxCommand {
    private Collection<String> commands;

    @Override
    public String toString() {
        final StringBuilder stringBuilder = new StringBuilder();
        for (String command : commands) {
            stringBuilder.append(command).append(";").append(" ");
        }
        return stringBuilder.toString().replaceAll("\\s{2,}", " ").trim();
    }
}


text:
//
// Generated by fetch-leetcode-submission project on GitHub.
// https://github.com/gitzhou/fetch-leetcode-submission
// Contact Me: aaron67[AT]aaron67.cc
//
// Linked List Cycle
// https://leetcode.com/problems/linked-list-cycle/
//

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public boolean hasCycle(ListNode head) {
        if(head == null||head.next == null) {
            return false;
        }
        ListNode slow = head;
        ListNode fast = head;
        while(fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            if (slow == fast) {
                return true;
            }
        }
        return  false;
    }
}


text:
package com.sc2geeks.commons.web;

import org.apache.commons.lang3.StringUtils;

/**
 * Created by IntelliJ IDEA.
 * User: robert
 * Date: 10/23/11
 * Time: 6:31 PM
 * To change this template use File | Settings | File Templates.
 */
public class UrlUtility
{
		public static String removeParameter(String baseUrl, String paramName)
	{
		int startPos;
		if ((startPos = baseUrl.indexOf(paramName + "=")) == -1)
			return baseUrl;

		int endPos = baseUrl.indexOf("&", startPos);
		if (endPos == -1)
			endPos = baseUrl.length();
		String subString = baseUrl.substring(startPos, endPos);
		baseUrl = baseUrl.replace(subString, "");

		if (baseUrl.endsWith("?"))
			baseUrl = StringUtils.removeEnd(baseUrl, "?");

		if (baseUrl.endsWith("&"))
			baseUrl = StringUtils.removeEnd(baseUrl, "&");

		return baseUrl;
	}

	public static String setParameter(String baseUrl, String paramName, String paramValue)
	{
		baseUrl = removeParameter(baseUrl, paramName);
		if (!baseUrl.contains("?"))
			baseUrl = baseUrl + "?";
		else if (!baseUrl.endsWith("&"))
			baseUrl = baseUrl + "&";

		return baseUrl + paramName + "=" + paramValue;
	}

	public static String Utf8Encode(String input)
	{
		return UrlUTF8Encoder.encode(input);
	}
}


text:
package org.neo4j.legacy.consistency.report;

import org.neo4j.kernel.impl.store.record.AbstractBaseRecord;
import org.neo4j.legacy.consistency.RecordType;

public interface InconsistencyLogger
{
    void error( RecordType recordType, AbstractBaseRecord record, String message, Object[] args );

    void error( RecordType recordType, AbstractBaseRecord oldRecord, AbstractBaseRecord newRecord, String message,
                Object[] args );

    void warning( RecordType recordType, AbstractBaseRecord record, String message, Object[] args );

    void warning( RecordType recordType, AbstractBaseRecord oldRecord, AbstractBaseRecord newRecord, String message,
                  Object[] args );
}


text:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;

namespace Piranha
{
    ///
    /// Utility methods.
    ///
    public static class Utils
    {
        ///
        /// Gets a subset of the given array as a new array.
        ///
        /// <typeparam name="T">The array type</typeparam>
        /// <param name="arr">The array</param>
        /// <param name="startpos">The startpos</param>
        /// <param name="length">The length</param>
        /// <returns>The new array</returns>
        public static T[] Subset<T>(this T[] arr, int startpos = 0, int length = 0)
        {
            List<T> tmp = new List<T>();

            length = length > 0 ? length : arr.Length - startpos;

            for (var i = 0; i < arr.Length; i++)
            {
                if (i >= startpos && i < (startpos + length))
                    tmp.Add(arr[i]);
            }
            return tmp.ToArray();
        }

        ///
        /// Generates a slug from the given string.
        ///
        /// <param name="str">The string</param>
        /// <returns>The slug</returns>
        public static string GenerateSlug(string str, bool hierarchical = true)
        {
            if (App.Hooks != null && App.Hooks.OnGenerateSlug != null)
            {
                // Call the registered slug generation
                return App.Hooks.OnGenerateSlug(str);
            }
            else
            {
                // Trim & make lower case
                var slug = str.Trim().ToLower();

                // Convert culture specific characters
                slug = slug
                    .Replace("å", "a")
                    .Replace("ä", "a")
                    .Replace("á", "a")
                    .Replace("à", "a")
                    .Replace("ö", "o")
                    .Replace("ó", "o")
                    .Replace("ò", "o")
                    .Replace("é", "e")
                    .Replace("è", "e")
                    .Replace("í", "i")
                    .Replace("ì", "i");

                // Remove special characters
                slug = Regex.Replace(slug, @"[^a-z0-9-/ ]", "").Replace("--", "-");

                // Remove whitespaces
                slug = Regex.Replace(slug.Replace("-", " "), @"\s+", " ").Replace(" ", "-");

                // Remove slash if non-hierarchical
                if (!hierarchical)
                    slug = slug.Replace("/", "-");

                // Remove multiple dashes
                slug = Regex.Replace(slug, @"[-]+", "-");

                // Remove leading & trailing dashes
                if (slug.EndsWith("-"))
                    slug = slug.Substring(0, slug.LastIndexOf("-"));
                if (slug.StartsWith("-"))
                    slug = slug.Substring(Math.Min(slug.IndexOf("-") + 1, slug.Length));
                return slug;
            }
        }

        ///
        /// Generates a camel cased internal id from the given string.
        ///
        /// <param name="str">The string</param>
        /// <returns>The internal id</returns>
        public static string GenerateInteralId(string str)
        {
            var ti = new CultureInfo("en-US", false).TextInfo;
            return ti.ToTitleCase(GenerateSlug(str).Replace('-', ' ')).Replace(" ", "");
        }

        ///
        /// Generates a ETag from the given name and date.
        ///
        /// <param name="name">The resource name</param>
        /// <param name="date">The modification date</param>
        /// <returns>The etag</returns>
        public static string GenerateETag(string name, DateTime date)
        {
            var encoding = new UTF8Encoding();

            using (var crypto = MD5.Create())
            {
                var str = name + date.ToString("yyyy-MM-dd HH:mm:ss");
                var bytes = crypto.ComputeHash(encoding.GetBytes(str));
                return $"\"{Convert.ToBase64String(bytes)}\"";
            }
        }

        ///
        ///
        ///
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static string FormatByteSize(double bytes)
        {
            string[] SizeSuffixes = { "bytes", "KB", "MB", "GB" };

            int index = 0;
            if (bytes > 1023)
            {
                do
                {
                    bytes /= 1024;
                    index++;
                } while (bytes >= 1024 && index < 3);
            }

            return $"{bytes:0.00} {SizeSuffixes[index]}";
        }

        ///
        /// Gets the first paragraph from the given html string.
        ///
        /// <param name="str">The string</param>
        /// <returns>The first paragraph</returns>
        public static string FirstParagraph(string str)
        {
            Regex reg = new Regex("
]*>.*?
");
            var matches = reg.Matches(str);

            return matches.Count > 0 ? matches[0].Value : "";
        }

        ///
        /// Gets the first paragraph from the given markdown field.
        ///
        /// <param name="md">The field</param>
        /// <returns>The first paragraph</returns>
        public static string FirstParagraph(Extend.Fields.MarkdownField md)
        {
            Regex reg = new Regex("
]*>.*?
");
            var matches = reg.Matches(md.ToHtml());

            return matches.Count > 0 ? matches[0].Value : "";
        }

        ///
        /// Gets the first paragraph from the given html field.
        ///
        /// <param name="html">The field</param>
        /// <returns>The first paragraph</returns>
        public static string FirstParagraph(Extend.Fields.HtmlField html)
        {
            Regex reg = new Regex("
]*>.*?
");
            var matches = reg.Matches(html.Value);

            return matches.Count > 0 ? matches[0].Value : "";
        }

        ///
        /// Gets the formatted three digit version number of the given assembly.
        ///
        /// <param name="assembly">The assembly</param>
        /// <returns>The version string</returns>
        public static string GetAssemblyVersion(Assembly assembly)
        {
            var version = assembly.GetName().Version;

            return $"{version.Major}.{version.Minor}.{version.Build}";
        }
    }
}


text:
0.sec=gemäß Artikel 26 Absatz 2 der Richtlinie 95/46/EG für die Übermittlung personenbezogener Daten an {_Auftragsverarbeiter}, die in Drittländern niedergelassen sind, in denen kein angemessenes Schutzniveau gewährleistet ist

Exporter.1.sec=Bezeichnung der Organisation ({_Datenexporteur}): {Exporter.Name.Full}

Exporter.2.sec=Anschrift: {Exporter.Addr.1,2}

Exporter.3.sec=Tel.:  {Exporter.Phone}

Exporter.4.sec=Fax: {Exporter.Fax}

Exporter.5.sec=E-Mail: {Exporter.Email}

Exporter.6.sec=Weitere Angaben zur Identifizierung der Organisation {Exporter.OtherInformationToIdentify}

Exporter.7.sec=("{_Datenexporteur}")

2.sec=
und

Importer.1.sec=Bezeichnung der Organisation ({_Datenexporteur}): {Importer.Name.Full}

Importer.2.sec=Anschrift: {Importer.Addr.1,2}

Importer.3.sec=Tel.:  {Importer.Phone}

Importer.4.sec=Fax: {Importer.Fax}

Importer.5.sec=E-Mail: {Importer.Email}

Importer.6.sec=Weitere Angaben zur Identifizierung der Organisation {Importer.OtherInformationToIdentify}

Importer.7.sec=("{_Datenimporteur}")

4.sec=(die "{_Partei}", wenn eine dieser Organisationen gemeint ist, die "{_Parteien}", wenn beide gemeint sind)

00.sec=VEREINBAREN folgende Vertragsklauseln ("{_Klauseln}"), um angemessene Garantien hinsichtlich des Schutzes der Privatsphäre, der Grundrechte und der Grundfreiheiten von Personen bei der Übermittlung der in Anhang 1 zu diesen Vertragsklauseln spezifizierten {_personenbezogenen_Daten} vom {_Datenexporteur} an den {_Datenimporteur} zu bieten.


text:
name: ElementButton
---
<style scoped>
.button {
	display: inline-block;
	min-width: 175px;
	padding: 12px 24px;
	border: 2px solid currentColor;
	font-weight: bold;
	line-height: 40px;
	text-align: center;
	color: var(--s2-black);
}
.button:hover {
	color: var(--s2-white);
	background: var(--s2-black);
}

.button-bg {
	background-color: var(--s2-white);
}

.invert {
	color: var(--s2-white);
}
.invert:hover {
	background: var(--s2-white-fade);
}

[data-theme=white]:hover {
	background-color: var(--s2-white);
	border-color: var(--s2-white);
}
[data-theme=green]:hover {
	background-color: var(--s2-green);
	border-color: var(--s2-green);
}
[data-theme=blue]:hover {
	background-color: var(--s2-blue);
	border-color: var(--s2-blue);
}
[data-theme=red]:hover {
	background-color: var(--s2-red);
	border-color: var(--s2-red);
}
</style>
<a
		href={props.href}
		className={helpers.classNames(style.button, {[style.buttonBg]: props.buttonBg, [style.invert]: props.invert})}
		data-theme={props.theme}
		target={props.target}
		>
	{props.label}
</a>


text:
package testsample.altvr.com.testsample.vo;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

import java.io.Serializable;

@JsonIgnoreProperties(ignoreUnknown = true)
public class PhotoVo implements Serializable{
    public String id;
    public String pageURL;
    public String type;
    public String tags;
    public String previewURL;
    public int previewWidth;
    public int previewHeight;
    public String webformatURL;
    public int webformatWidth;
    public int webformatHeight;
    public int imageWidth;
    public int imageHeight;
    public int views;
    public int downloads;
    public int favorites;
    public int likes;
    public int comments;
    public int user_id;
    public String user;
    public String userImageURL;
}


text:
package forms;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Properties;

import models.SourceConfiguration;
import play.data.validation.Constraints.Required;

import com.pickleproject.Selectors;

public class BulkConfiguration {

	private Long key;

	private int revision;

	@Required
	private String sourceKey;

	@Required
	private String bulkData;

	public BulkConfiguration() {
		super();
	}

	public BulkConfiguration(SourceConfiguration model) {
		key = model.getKey();
		revision = model.getRevision();
		sourceKey = model.getSourceKey();
		bulkData = propertyString(model);
	}

	public SourceConfiguration toModel() {
		SourceConfiguration sc = new SourceConfiguration();
		sc.setKey(key);
		sc.setSourceKey(sourceKey);
		sc.setRevision(revision);
		try {
			Properties p = new Properties();
			p.load(new StringReader(bulkData));
			Selectors sel = new Selectors(p);
			sc.setNameSelector(sel.elementSelector("Name"));
			sc.setNameValue(sel.valueSelector("Name"));
			sc.setNameRequired(sel.required("Name"));
			sc.setDescriptionSelector(sel.elementSelector("Description"));
			sc.setDescriptionValue(sel.valueSelector("Description"));
			sc.setDescriptionRequired(sel.required("Description"));
			sc.setPriceSelector(sel.elementSelector("Price"));
			sc.setPriceValue(sel.valueSelector("Price"));
			sc.setPriceRequired(sel.required("Price"));
			sc.setDiscountPriceSelector(sel.elementSelector("DiscountPrice"));
			sc.setDiscountPriceValue(sel.valueSelector("DiscountPrice"));
			sc.setDiscountPriceRequired(sel.required("DiscountPrice"));
			sc.setImageLinkSelector(sel.elementSelector("ImageLink"));
			sc.setImageLinkValue(sel.valueSelector("ImageLink"));
			sc.setImageLinkRequired(sel.required("ImageLink"));
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		return sc;
	}

	public static String propertyString(SourceConfiguration m) {
		Properties p = new Properties();

		p.setProperty("Name", m.getNameSelector());
		if (!empty(m.getNameValue()))
			p.setProperty("Name.value", m.getNameValue());
		if (m.isNameRequired())
			p.setProperty("Name.required", "true");

		p.setProperty("Description", m.getDescriptionSelector());
		if (!empty(m.getDescriptionValue()))
			p.setProperty("Description.value", m.getDescriptionValue());
		if (m.isDescriptionRequired())
			p.setProperty("Description.required", "true");

		p.setProperty("Price", m.getPriceSelector());
		if (!empty(m.getPriceValue()))
			p.setProperty("Price.value", m.getPriceValue());
		if (m.isPriceRequired())
			p.setProperty("Price.required", "true");

		p.setProperty("DiscountPrice", m.getDiscountPriceSelector());
		if (!empty(m.getDiscountPriceValue()))
			p.setProperty("DiscountPrice.value", m.getDiscountPriceValue());
		if (m.isDiscountPriceRequired())
			p.setProperty("DiscountPrice.required", "true");

		p.setProperty("ImageLink", m.getImageLinkSelector());
		if (!empty(m.getImageLinkValue()))
			p.setProperty("ImageLink.value", m.getImageLinkValue());
		if (m.isImageLinkRequired())
			p.setProperty("ImageLink.required", "true");

		Writer w = new StringWriter();
		try {
			p.store(w, "key=" + m.getKey());
		} catch (IOException e) {
			e.printStackTrace();
		}
		return w.toString();
	}

	private static boolean empty(String s) {
		return s == null || "".equals(s);
	}

	public String getSourceKey() {
		return sourceKey;
	}

	public void setSourceKey(String sourceKey) {
		this.sourceKey = sourceKey;
	}

	public String getBulkData() {
		return bulkData;
	}

	public void setBulkData(String bulkData) {
		this.bulkData = bulkData;
	}

	public Long getKey() {
		return key;
	}

	public void setKey(Long key) {
		this.key = key;
	}

	public int getRevision() {
		return revision;
	}

	public void setRevision(int revision) {
		this.revision = revision;
	}

	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder.append("BulkConfiguration [key=").append(key)
				.append(", revision=").append(revision).append(", sourceKey=")
				.append(sourceKey).append("]");
		return builder.toString();
	}

}


text:
[![Stories in Ready](https://badge.waffle.io/healthbam/healthbam.png?label=ready&title=Ready)](https://waffle.io/healthbam/healthbam)

# healthBAM
Making an **impact** on the health of Babies And Mothers

## How To Contribute

[See Contributing Guidelines](CONTRIBUTING.md).

## Getting Started

### Setting Up IDE

If using IntelliJ, "Import Project", and select the build.gradle file.
This will build and set up IntelliJ for the project.

Alternative method: you can run this command to generate an "ipr" file that can be opened:

~~~~shell
~/projects/healthbam $ ./gradlew idea
~~~~

### Building

~~~~shell
~/projects/healthbam $ ./gradlew build
~~~~

### Running Locally

#### PostgreSQL

You must have a postgres DB to use when running locally.

First, connect to the local DBMS from your project's top level directory (same directory as this README):

~~~~shell
~/projects/healthbam $ psql postgres
~~~~

Next, initialize the user & database with the local-setup.sql:

~~~~shell
postgres=# \i database/local-setup.sql
~~~~

Last, quit out of the psql shell:

~~~~shell
hmhb_db=# \q
~~~~

Note: If you want to start over, you can use the local-drop-everything.sql script to clean up the user & database created to start fresh.

#### Environment Variable Setup

Create a .env file to the top level directory of this project with the PORT to serve and JDBC_DATABASE_URL:

~~~~shell
PORT=8080
JDBC_DATABASE_URL="jdbc:postgresql://localhost:5432/hmhb_db"
GOOGLE_OAUTH_CLIENT_ID="259324353484-f8u4ltb5qko7fltub68dguhs16ae93nr.apps.googleusercontent.com"
GOOGLE_OAUTH_CLIENT_SECRET="<secret>"
HMHB_JWT_SECRET="<also secret>"
~~~~

Now you can run the latest code you have built locally with:

~~~~shell
~/projects/healthbam $ heroku local
~~~~

### Perks Offered By Spring Boot

Endpoints providing information on:

* Health Check: Local / Heroku
* Logs: Local / Heroku
* Java Heap Dump: Local / Heroku
* Java Thread Dump: Local / Heroku
* Environment Variables: Local / Heroku
* Metrics Local / Heroku
* Application Info: Local / Heroku
* Trace Info Of The Last 100 Requests: Local / Heroku
* Spring Config Beans: Local / Heroku
* Spring Beans: Local / Heroku
* Spring MVC Request Mappings: Local / Heroku
* Spring Boot Autoconfig Info: Local / Heroku
* Documenation For These Endpoints: Local / Heroku


text:
Clazz.declarePackage ("J.shapebio");
Clazz.load (["J.shapebio.BioShapeCollection"], "J.shapebio.Backbone", ["java.lang.Float", "JU.BS"], function () {
c$ = Clazz.decorateAsClass (function () {
this.bsSelected = null;
Clazz.instantialize (this, arguments);
}, J.shapebio, "Backbone", J.shapebio.BioShapeCollection);
Clazz.defineMethod (c$, "initShape",
function () {
Clazz.superCall (this, J.shapebio.Backbone, "initShape", []);
this.madOn = 1;
this.madHelixSheet = 1500;
this.madTurnRandom = 500;
this.madDnaRna = 2000;
this.isActive = true;
});
Clazz.overrideMethod (c$, "setProperty",
function (propertyName, value, bsSelected) {
if ("bitset" === propertyName) {
this.bsSelected = value;
return;
}this.setPropBSC (propertyName, value, bsSelected);
}, "~S,~O,JU.BS");
Clazz.overrideMethod (c$, "setShapeSizeRD",
function (size, rd, bsSelected) {
var mad = size;
this.initialize ();
var useThisBsSelected = (this.bsSelected != null);
if (useThisBsSelected) bsSelected = this.bsSelected;
for (var iShape = this.bioShapes.length; --iShape >= 0; ) {
var bioShape = this.bioShapes[iShape];
if (bioShape.monomerCount == 0) continue;
var bondSelectionModeOr = this.vwr.getBoolean (603979812);
var atomIndices = bioShape.bioPolymer.getLeadAtomIndices ();
var isVisible = (mad != 0);
if (bioShape.bsSizeSet == null) bioShape.bsSizeSet =  new JU.BS ();
bioShape.isActive = true;
for (var i = bioShape.monomerCount - 1; --i >= 0; ) {
var index1 = atomIndices[i];
var index2 = atomIndices[i + 1];
var isAtom1 = bsSelected.get (index1);
var isAtom2 = bsSelected.get (index2);
if (isAtom1 && isAtom2 || useThisBsSelected && isAtom1 || bondSelectionModeOr && (isAtom1 || isAtom2)) {
bioShape.monomers[i].setShapeVisibility (this.vf, isVisible);
var atomA = this.ms.at[index1];
if (rd != null) {
if (Float.isNaN (rd.values[index1]) || Float.isNaN (rd.values[index2])) continue;
mad = Clazz.floatToShort ((rd.values[index1] + rd.values[index2]) * 1000);
isVisible = (mad != 0);
}var atomB = this.ms.at[index2];
var wasVisible = (bioShape.mads[i] != 0);
if (wasVisible != isVisible) {
atomA.addDisplayedBackbone (this.vf, isVisible);
atomB.addDisplayedBackbone (this.vf, isVisible);
}bioShape.mads[i] = mad;
bioShape.bsSizeSet.setBitTo (i, isVisible);
bioShape.bsSizeDefault.setBitTo (i, mad == -1);
}}
}
if (useThisBsSelected) this.bsSelected = null;
}, "~N,J.atomdata.RadiusData,JU.BS");
Clazz.overrideMethod (c$, "setAtomClickability",
function () {
if (this.bioShapes == null) return;
for (var iShape = this.bioShapes.length; --iShape >= 0; ) {
var bioShape = this.bioShapes[iShape];
var atomIndices = bioShape.bioPolymer.getLeadAtomIndices ();
for (var i = bioShape.monomerCount; --i >= 0; ) {
var atom = this.ms.at[atomIndices[i]];
if (atom.nBackbonesDisplayed > 0 && !this.ms.isAtomHidden (i)) atom.setClickable (this.vf);
}
}
});
});


text:
package com.mobilesolutionworks.android.httpcache;

import android.content.ContentValues;
import android.os.Bundle;
import android.text.TextUtils;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.RequestHandle;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;

import org.apache.commons.lang3.SerializationUtils;

import cz.msebera.android.httpclient.Header;
import cz.msebera.android.httpclient.client.HttpResponseException;

/**
 * Created by yunarta on 29/10/14.
 */
public class LoopJHttpCacheService extends HttpCacheService {

    @Override
    protected void executeRequest(final String local, final String remote, String method, Bundle params, final int cache, int timeout) {
        RequestParams rp = new RequestParams();
        if (params != null) {
            for (String key : params.keySet()) {
                String value = params.getString(key);
                if (!TextUtils.isEmpty(value)) {
                    rp.add(key, value);
                }
            }
        }

        TextHttpResponseHandler handler = new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                if (throwable instanceof HttpResponseException) {
                    ContentValues values = new ContentValues();
                    values.put("local", local);
                    values.put("remote", remote);
                    values.put("data", "");
                    values.put("time", System.currentTimeMillis() + cache);

                    if (onValidateStatus(statusCode)) {
                        values.put("error", CacheErrorCode.createNet(statusCode));
                        values.putNull("trace");
                    } else {
                        values.put("error", CacheErrorCode.PROCESS_ERROR);
                        values.put("trace", SerializationUtils.serialize(throwable));
                    }

                    values.put("status", statusCode);

                    insert(values, local);
                } else {
                    ContentValues values = new ContentValues();
                    values.put("local", local);
                    values.put("remote", remote);
                    values.put("data", "");
                    values.put("time", System.currentTimeMillis() + cache);
                    values.put("error", CacheErrorCode.PROCESS_ERROR);

                    values.put("trace", SerializationUtils.serialize(throwable));
                    values.put("status", statusCode);

                    insert(values, local);
                }
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                ContentValues values = new ContentValues();

                values.put("local", local);
                values.put("remote", remote);
                values.put("data", responseString);
                values.put("time", System.currentTimeMillis() + cache);
                values.put("error", CacheErrorCode.OK);

                values.putNull("trace");
                values.put("status", statusCode);
                insert(values, local);
            }
        };

        Header[] headers = null;
        String contentType = null;

        AsyncHttpClient client = new AsyncHttpClient();
        client.setCookieStore(mCookieStore);

        RequestHandle handle;
        if ("POST".equals(method)) {
            handle = client.post(this, remote, headers, rp, contentType, handler);
        } else {
            handle = client.get(this, remote, headers, rp, handler);
        }
    }

    protected boolean onValidateStatus(int statusCode) {
        return true;
    }
}


text:
/**
 * Created by GlazedSolutions on 12/05/2015.
 */

import ApeyEye from '../../apey-eye';

let Decorators = ApeyEye.Decorators;
let GenericResource = ApeyEye.GenericResource;
let Input = ApeyEye.Input;

import CategoryModel from '../models/CategoryModel.js';

@Decorators.Model(CategoryModel)
@Decorators.Name("category")
@Decorators.Authentication("basic")
@Decorators.Roles(["restaurant_owner"])
class CategoryResource extends GenericResource {
}

export default CategoryResource;


text:
package persistence

import (
	"fmt"
	"github.com/nu7hatch/gouuid"
	"testing"
	"time"
)

func DisableTestCreate(t *testing.T) {
	assetDS := &AssetDS{}
	err := assetDS.InitDatabase("mysql", "stormio", "stormio", "password", "localhost", "3306")
	if err != nil {
		t.Errorf(err.Error())
		return
	}
	assetDS.GetConnection()
	defer assetDS.Close()
	assetRequest := &AssetRequest{}
	u4, _ := uuid.NewV4()
	assetRequest.Id = u4.String()
	assetRequest.AssetProviderId = "self"
	assetRequest.ResourceId = "No callback"
	assetRequest.ReceivedOn = time.Now().String()
	assetDS.Create(assetDS.conn, assetRequest)
	fmt.Println("Test Create success")
}

func DisableTestUpate(t *testing.T) {
	assetDS := &AssetDS{}
	err := assetDS.InitDatabase("mysql", "stormio", "stormio", "password", "localhost", "3306")
	if err != nil {
		t.Errorf(err.Error())
	}
	assetDS.GetConnection()
	defer assetDS.Close()
	assetRequest := &AssetRequest{}
	u4, _ := uuid.NewV4()
	assetRequest.Id = u4.String()
	assetRequest.AssetProviderId = "self"
	assetRequest.ResourceId = "No callback"
	assetRequest.ReceivedOn = time.Now().String()
	assetDS.Create(assetDS.conn, assetRequest)
	assetRequest.ResourceId = "yes callback"
	assetDS.Update(assetDS.conn, assetRequest)
	fmt.Println("Test Update success")
}

func DisableTestRemove(t *testing.T) {
	assetDS := &AssetDS{}
	err := assetDS.InitDatabase("mysql", "stormio", "stormio", "password", "localhost", "3306")
	if err != nil {
		t.Errorf(err.Error())
	}
	assetDS.GetConnection()
	defer assetDS.Close()
	assetRequest := &AssetRequest{}
	u4, _ := uuid.NewV4()
	assetRequest.Id = u4.String()
	assetRequest.AssetProviderId = "self"
	assetRequest.ResourceId = "No callback"
	assetRequest.ReceivedOn = time.Now().String()
	assetDS.Create(assetDS.conn, assetRequest)
	assetDS.Remove(assetDS.conn, assetRequest.Id)
	fmt.Println("Test Delete success")
}

func DisableTestFind(t *testing.T) {
	assetDS := &AssetDS{}
	err := assetDS.InitDatabase("mysql", "stormio", "stormio", "password", "localhost", "3306")
	if err != nil {
		t.Errorf(err.Error())
	}
	assetDS.GetConnection()
	defer assetDS.Close()
	assetRequest := &AssetRequest{}
	u4, _ := uuid.NewV4()
	assetRequest.Id = u4.String()
	assetRequest.AssetProviderId = "self"
	assetRequest.ResourceId = "No callback"
	assetRequest.ReceivedOn = time.Now().String()
	assetDS.Create(assetDS.conn, assetRequest)
	newAs, err := assetDS.Find(assetDS.conn, assetRequest.Id)
	fmt.Println(newAs.ResourceId)
}