text:
<?php

require_once 'include/logging.php';
include_once 'libraries/adodb/adodb.inc.php';
require_once 'libraries/adodb/adodb-xmlschema.inc.php';

$log = LoggerManager::getLogger('VT');
$logsqltm = LoggerManager::getLogger('SQLTIME');

// Callback class useful to convert PreparedStatement Question Marks to SQL value
// See function convertPS2Sql in PearDatabase below
class PreparedQMark2SqlValue {
	// Constructor
	function PreparedQMark2SqlValue($vals){
        $this->ctr = 0;
        $this->vals = $vals;
    }
    function call($matches){
            /**
             * If ? is found as expected in regex used in function convert2sql
             * /('[^']*')|(\"[^\"]*\")|([?])/
             *
             */
            if($matches[3]=='?'){
                    $this->ctr++;
                    return $this->vals[$this->ctr-1];
            }else{
                    return $matches[0];
            }
    }
}

/**
 * Performance perference API
 */
@include_once('config.performance.php'); // Ignore warning if not present
class PerformancePrefs {
	/**
	 * Get performance parameter configured value or default one
	 */
	static function get($key, $defvalue=false) {
		global $PERFORMANCE_CONFIG;
		if(isset($PERFORMANCE_CONFIG)){
			if(isset($PERFORMANCE_CONFIG[$key])) {
				return $PERFORMANCE_CONFIG[$key];
			}
		}
		return $defvalue;
	}
	/** Get boolean value */
	static function getBoolean($key, $defvalue=false) {
		return self::get($key, $defvalue);
	}
	/** Get Integer value */
	static function getInteger($key, $defvalue=false) {
		return intval(self::get($key, $defvalue));
	}
}

class PearDatabase{
    var $database = null;
    var $dieOnError = false;
    var $dbType = null;
    var $dbHostName = null;
    var $dbName = null;
    var $dbOptions = null;
    var $userName=null;
    var $userPassword=null;
    var $query_time = 0;
    var $log = null;
    var $lastmysqlrow = -1;
    var $enableSQLlog = false;
    var $continueInstallOnError = true;

    // If you want to avoid executing PreparedStatement, set this to true
    // PreparedStatement will be converted to normal SQL statement for execution
	var $avoidPreparedSql = false;

	/**
	 * Performance tunning parameters (can be configured through performance.prefs.php)
	 * See the constructor for initialization
	 */
	var $isdb_default_utf8_charset = false;

	/**
	 * Manage instance usage of this class
	 */
	static function &getInstance() {
		global $adb, $log;

		if(!isset($adb)) {
			$adb = new self();
		}
		return $adb;
	}
	// END

    function isMySQL() { return (stripos($this->dbType ,'mysql') === 0);}
    function isOracle() { return $this->dbType=='oci8'; }
    function isPostgres() { return $this->dbType=='pgsql'; }

    function println($msg)
    {
		require_once('include/logging.php');
		$log1 = LoggerManager::getLogger('VT');
		if(is_array($msg)) {
		    $log1->info("PearDatabse ->".print_r($msg,true));
		} else {
		    $log1->info("PearDatabase ->".$msg);
		}
		return $msg;
    }

    function setDieOnError($value){	 $this->dieOnError = $value; }
    function setDatabaseType($type){ $this->dbType = $type; }
    function setUserName($name){ $this->userName = $name; }

    function setOption($name, $value){
		if(isset($this->dbOptions)) $this->dbOptions[$name] = $value;
		if(isset($this->database)) $this->database->setOption($name, $value);
    }

    function setUserPassword($pass){ $this->userPassword = $pass; }
    function setDatabaseName($db){ $this->dbName = $db;	}
    function setDatabaseHost($host){ $this->dbHostName = $host;	}

    function getDataSourceName(){
		return 	$this->dbType. "://".$this->userName.":".$this->userPassword."@". $this->dbHostName . "/". $this->dbName;
    }

    function startTransaction() {
	    if($this->isPostgres()) return;
		$this->checkConnection();
		$this->println("TRANS Started");
		$this->database->StartTrans();
    }

    function completeTransaction() {
	    if($this->isPostgres()) return;
		if($this->database->HasFailedTrans()) $this->println("TRANS  Rolled Back");
		else $this->println("TRANS  Commited");

		$this->database->CompleteTrans();
		$this->println("TRANS  Completed");
    }

    function hasFailedTransaction(){ return $this->database->HasFailedTrans();   }

    function checkError($msg='', $dieOnError=false) {
		if($this->dieOnError || $dieOnError) {
			$bt = debug_backtrace();
			$ut = array();
			foreach ($bt as $t) {
				$ut[] = array('file'=>$t['file'],'line'=>$t['line'],'function'=>$t['function']);
			}
			echo '<pre>';
			var_export($ut);
			echo '</pre>';
		    $this->println("ADODB error ".$msg."->[".$this->database->ErrorNo()."]".$this->database->ErrorMsg());
		    die ($msg."ADODB error ".$msg."->".$this->database->ErrorMsg());
		} else {
		    $this->println("ADODB error ".$msg."->[".$this->database->ErrorNo()."]".$this->database->ErrorMsg());
		}
		return false;
    }

    function change_key_case($arr) {
		return is_array($arr)?array_change_key_case($arr):$arr;
    }

    var $req_flist;
    function checkConnection(){
		global $log;

		if(!isset($this->database)) {
		    $this->println("TRANS creating new connection");
		    $this->connect(false);
		} else {
		    //$this->println("checkconnect using old connection");
		}
    }

	/* SQLTime logging */
	protected $logSqlTimingID = false;
	function logSqlTiming($startat, $endat, $sql, $params=false) {
        if(!PerformancePrefs::getBoolean('SQL_LOG_INCLUDE_CALLER', false)) {
        	return;
        }

		$today  = date('Y-m-d H:i:s'); $logtable = 'vtiger_sqltimelog';
		$logsql = 'INSERT INTO '.$logtable.'(id, type, started, ended, data, loggedon) VALUES (?,?,?,?,?,?)';

		if ($this->logSqlTimingID === false) {
			$this->logSqlTimingID = $this->getUniqueID($logtable);

			$type = (php_sapi_name() == 'cli') ? 'CLI' : 'REQ';
			$data = '';
			if (isset($_SERVER['REQUEST_METHOD'])) {
				$uri  = $_SERVER['REQUEST_URI'];
				$qmarkIndex = strpos($_SERVER['REQUEST_URI'], '?');
				if ($qmarkIndex !== false) $uri = substr($uri, 0, $qmarkIndex);
				$data = $uri . '?'. http_build_query($_SERVER['REQUEST_METHOD'] == 'GET'? $_GET:$_POST);
			} else if ($argv) {
				$data = implode(' ', $argv);
			}

			$this->database->Execute($logsql, array($this->logSqlTimingID, $type, NULL, NULL, $data, $today));
		}

		$type = 'SQL';
		$data = trim($sql);
		if (is_array($params) && !empty($params)) {
			$data .= "\n[" . implode(",", $params) . "]";
		}
		$this->database->Execute($logsql, array($this->logSqlTimingID, $type, $startat, $endat, $data, $today));

		$type = 'CALLERS';
		$data = array();
		$callers = debug_backtrace();
		for ($calleridx = 0, $callerscount = count($callers); $calleridx < $callerscount; ++$calleridx) {
			if ($calleridx == 0) {
				continue;
			}
			if ($calleridx < $callerscount) {
				$callerfunc = $callers[$calleridx+1]['function'];
				if (!empty($callerfunc)) $callerfunc = " ($callerfunc) ";
			}
			$data[] = "CALLER: (" . $callers[$calleridx]['line'] . ') ' . $callers[$calleridx]['file'] . $callerfunc;
		}
		$this->database->Execute($logsql, array($this->logSqlTimingID, $type, NULL, NULL, implode("\n", $data), $today));
	}

	/**
	 * Execute SET NAMES UTF-8 on the connection based on configuration.
	 */
	function executeSetNamesUTF8SQL($force = false) {
		global $default_charset;
		static $DEFAULTCHARSET = null;
		if ($DEFAULTCHARSET === null) $DEFAULTCHARSET = strtoupper($default_charset);

		// Performance Tuning: If database default charset is UTF-8, we don't need this
		if($DEFAULTCHARSET == 'UTF-8' && ($force || !$this->isdb_default_utf8_charset)) {

			$sql_start_time = microtime(true);

			$setnameSql = "SET NAMES utf8";
			$this->database->Execute($setnameSql);
			$this->logSqlTiming($sql_start_time, microtime(true), $setnameSql);
		}
	}

	/**
	 * Execute query in a batch.
	 *
	 * For example:
	 * INSERT INTO TABLE1 VALUES (a,b);
	 * INSERT INTO TABLE1 VALUES (c,d);
	 *
	 * like: INSERT INTO TABLE1 VALUES (a,b), (c,d)
	 */
	function query_batch($prefixsql, $valuearray) {
		if(PerformancePrefs::getBoolean('ALLOW_SQL_QUERY_BATCH')) {
			$sql = $prefixsql;
			$suffixsql = $valuearray;
			if(!is_array($valuearray)) $suffixsql = implode(',', $valuearray);
			$this->query($prefixsql . $suffixsql);
		} else {
			if(is_array($valuearray) && !empty($valuearray)) {
				foreach($valuearray as $suffixsql) {
					$this->query($prefixsql . $suffixsql);
				}
			}
		}
	}

    function query($sql, $dieOnError=false, $msg='')
    {
	global $log, $default_charset;

	$log->debug('query being executed : '.$sql);
	$this->checkConnection();

	$this->executeSetNamesUTF8SQL();

	$sql_start_time = microtime(true);
	$result = & $this->database->Execute($sql);
	$this->logSqlTiming($sql_start_time, microtime(true), $sql);

	$this->lastmysqlrow = -1;
	if(!$result)$this->checkError($msg.' Query Failed:' . $sql . '::', $dieOnError);

	return $result;
    }

	/**
	 * Convert PreparedStatement to SQL statement
	 */
	function convert2Sql($ps, $vals) {
		if(empty($vals)) { return $ps; }
		// TODO: Checks need to be added array out of bounds situations
		for($index = 0; $index < count($vals); $index++) {
            // Package import pushes data after XML parsing, so type-cast it
            if(is_a($vals[$index], 'SimpleXMLElement')) {
                $vals[$index] = (string) $vals[$index];
            }
			if(is_string($vals[$index])) {
				if($vals[$index] == '') {
					$vals[$index] = $this->database->Quote($vals[$index]);
				}
				else {
					$vals[$index] = "'".$this->sql_escape_string($vals[$index]). "'";
				}
			}
			if($vals[$index] === null) {
				$vals[$index] = "NULL";
			}
		}
		$sql = preg_replace_callback("/('[^']*')|(\"[^\"]*\")|([?])/", array(new PreparedQMark2SqlValue($vals),"call"), $ps);
		return $sql;
	}

  	/* ADODB prepared statement Execution
   	* @param $sql -- Prepared sql statement
   	* @param $params -- Parameters for the prepared statement
   	* @param $dieOnError -- Set to true, when query execution fails
   	* @param $msg -- Error message on query execution failure
   	*/
	function pquery($sql, $params=array(), $dieOnError=false, $msg='') {
		global $log, $default_charset;
		$log->debug('Prepared sql query being executed : '.$sql);
		$this->checkConnection();

		$this->executeSetNamesUTF8SQL();

		$sql_start_time = microtime(true);
		$params = $this->flatten_array($params);
		if (count($params) > 0) {
			$log->debug('Prepared sql query parameters : [' . implode(",", $params) . ']');
		}

		if($this->avoidPreparedSql || empty($params)) {
			$sql = $this->convert2Sql($sql, $params);
			$result = $this->database->Execute($sql);
		} else {
			$result = $this->database->Execute($sql, $params);
		}
		$sql_end_time = microtime(true);
		$this->logSqlTiming($sql_start_time, $sql_end_time, $sql, $params);

		$this->lastmysqlrow = -1;
		if(!$result)$this->checkError($msg.' Query Failed:' . $sql . '::', $dieOnError);

		return $result;
	}

	/**
	 * Flatten the composite array into single value.
	 * Example:
	 * $input = array(10, 20, array(30, 40), array('key1' => '50', 'key2'=>array(60), 70));
	 * returns array(10, 20, 30, 40, 50, 60, 70);
	 */
	function flatten_array($input, $output=null) {
		if($input == null) return null;
		if($output == null) $output = array();
		foreach($input as $value) {
			if(is_array($value)) {
				$output = $this->flatten_array($value, $output);
			} else {
				array_push($output, $value);
			}
		}
		return $output;
	}

    function getEmptyBlob($is_string=true)
    {
	//if(dbType=="oci8") return 'empty_blob()';
	//else return 'null';
	if (is_string) return 'null';
	return null;
    }

    function updateBlob($tablename, $colname, $id, $data)
    {
	$this->println("updateBlob t=".$tablename." c=".$colname." id=".$id);
	$this->checkConnection();
	$this->executeSetNamesUTF8SQL();

	$sql_start_time = microtime(true);
	$result = $this->database->UpdateBlob($tablename, $colname, $data, $id);
	$this->logSqlTiming($sql_start_time, microtime(true), "Update Blob $tablename, $colname, $id");

	$this->println("updateBlob t=".$tablename." c=".$colname." id=".$id." status=".$result);
	return $result;
    }

    function updateBlobFile($tablename, $colname, $id, $filename)
    {
	$this->println("updateBlobFile t=".$tablename." c=".$colname." id=".$id." f=".$filename);
	$this->checkConnection();
	$this->executeSetNamesUTF8SQL();

	$sql_start_time = microtime(true);
	$result = $this->database->UpdateBlobFile($tablename, $colname, $filename, $id);
	$this->logSqlTiming($sql_start_time, microtime(true), "Update Blob $tablename, $colname, $id");

	$this->println("updateBlobFile t=".$tablename." c=".$colname." id=".$id." f=".$filename." status=".$result);
	return $result;
    }

    function limitQuery($sql,$start,$count, $dieOnError=false, $msg='')
    {
	global $log;
	//$this->println("ADODB limitQuery sql=".$sql." st=".$start." co=".$count);
	$log->debug(' limitQuery sql = '.$sql .' st = '.$start .' co = '.$count);
	$this->checkConnection();

	$this->executeSetNamesUTF8SQL();

	$sql_start_time = microtime(true);
	$result =& $this->database->SelectLimit($sql,$count,$start);
	$this->logSqlTiming($sql_start_time, microtime(true), "$sql LIMIT $count, $start");

	if(!$result) $this->checkError($msg.' Limit Query Failed:' . $sql . '::', $dieOnError);
	return $result;
    }

    function getOne($sql, $dieOnError=false, $msg='')
    {
	$this->println("ADODB getOne sql=".$sql);
	$this->checkConnection();

	$this->executeSetNamesUTF8SQL();

	$sql_start_time = microtime(true);
	$result =& $this->database->GetOne($sql);
	$this->logSqlTiming($sql_start_time, microtime(true), "$sql GetONE");

	if(!$result) $this->checkError($msg.' Get one Query Failed:' . $sql . '::', $dieOnError);
	return $result;
    }

    function getFieldsDefinition(&$result)
    {
	//$this->println("ADODB getFieldsArray");
	$field_array = array();
	if(! isset($result) || empty($result))
	{
		return 0;
	}

	$i = 0;
	$n = $result->FieldCount();
	while ($i < $n)
	{
		$meta = $result->FetchField($i);
		if (!$meta)
		{
			return 0;
		}
		array_push($field_array,$meta);
		$i++;
	}

	//$this->println($field_array);
	return $field_array;
    }

    function getFieldsArray(&$result)
    {
	//$this->println("ADODB getFieldsArray");
	$field_array = array();
	if(! isset($result) || empty($result))
	{
	    return 0;
	}

	$i = 0;
	$n = $result->FieldCount();
	while ($i < $n)
	{
	    $meta = $result->FetchField($i);
	    if (!$meta)
	    {
		return 0;
	    }
	    array_push($field_array,$meta->name);
	    $i++;
	}

	//$this->println($field_array);
	return $field_array;
    }

    function getRowCount(&$result){
		global $log;
		if(isset($result) && !empty($result))
		    $rows= $result->RecordCount();
		return $rows;
    }

    /* ADODB newly added. replacement for mysql_num_rows */
    function num_rows(&$result) {
		return $this->getRowCount($result);
    }

    /* ADODB newly added. replacement form mysql_num_fields */
    function num_fields(&$result) {
		return $result->FieldCount();
    }

    /* ADODB newly added. replacement for mysql_fetch_array() */
    function fetch_array(&$result) {
		if($result->EOF) {
		    //$this->println("ADODB fetch_array return null");
		    return NULL;
		}
		$arr = $result->FetchRow();
        if(is_array($arr))
			$arr = array_map('to_html', $arr);
        return $this->change_key_case($arr);
    }

    ## adds new functions to the PearDatabase class to come around the whole
    ## broken query_result() idea
    ## Code-Contribution given by weigelt@metux.de - Starts
    function run_query_record_html($query) {
	    if (!is_array($rec = $this->run_query_record($query)))
	    	return $rec;
	    foreach ($rec as $walk => $cur)
	    	$r[$walk] = to_html($cur);
	    return $r;
    }

    function sql_quote($data) {
		if (is_array($data)) {
			switch($data{'type'}) {
			case 'text':
			case 'numeric':
			case 'integer':
			case 'oid':
				return $this->quote($data{'value'});
				break;
			case 'timestamp':
				return $this->formatDate($data{'value'});
				break;
			default:
				throw new Exception("unhandled type: ".serialize($cur));
			}
		} else
			return $this->quote($data);
    }

    function sql_insert_data($table, $data) {
		if (!$table)
			throw new Exception("missing table name");
		if (!is_array($data))
			throw new Exception("data must be an array");
		if (!count($table))
	    	throw new Exception("no data given");

		$sql_fields = '';
		$sql_data = '';
		foreach($data as $walk => $cur) {
			$sql_fields .= ($sql_fields?',':'').$walk;
			$sql_data   .= ($sql_data?',':'').$this->sql_quote($cur);
		}
		return 'INSERT INTO '.$table.' ('.$sql_fields.') VALUES ('.$sql_data.')';
    }

    function run_insert_data($table,$data) {
	    $query = $this->sql_insert_data($table,$data);
	    $res = $this->query($query);
	    $this->query("commit;");
    }

    function run_query_record($query) {
	    $result = $this->query($query);
	    if (!$result)
	    	return;
	    if (!is_object($result))
	    	throw new Exception("query \"$query\" failed: ".serialize($result));
	    $res = $result->FetchRow();
	    $rowdata = $this->change_key_case($res);
	    return $rowdata;
    }

    function run_query_allrecords($query) {
	    $result = $this->query($query);
	    $records = array();
	    $sz = $this->num_rows($result);
	    for ($i=0; $i<$sz; $i++)
			$records[$i] = $this->change_key_case($result->FetchRow());
	    return $records;
    }

    function run_query_field($query,$field='') {
	    $rowdata = $this->run_query_record($query);
	    if(isset($field) && $field != '')
	    	return $rowdata{$field};
	    else
	    	return array_shift($rowdata);
    }

    function run_query_list($query,$field){
	    $records = $this->run_query_allrecords($query);
	    foreach($records as $walk => $cur)
			$list[] = $cur{$field};
    }

    function run_query_field_html($query,$field){
	    return to_html($this->run_query_field($query,$field));
    }

    function result_get_next_record($result){
	    return $this->change_key_case($result->FetchRow());
    }

    // create an IN expression from an array/list
    function sql_expr_datalist($a) {
	    if (!is_array($a))
	    	throw new Exception("not an array");
	    if (!count($a))
	    	throw new Exception("empty arrays not allowed");

	    foreach($a as $walk => $cur)
	    	$l .= ($l?',':'').$this->quote($cur);
	    return ' ( '.$l.' ) ';
    }

    // create an IN expression from an record list, take $field within each record
    function sql_expr_datalist_from_records($a,$field) {
	    if (!is_array($a))
	    	throw new Exception("not an array");
	    if (!$field)
	    	throw new Exception("missing field");
	    if (!count($a))
	    	throw new Exception("empty arrays not allowed");

	    foreach($a as $walk => $cur)
	    	$l .= ($l?',':'').$this->quote($cur{$field});

	    return ' ( '.$l.' ) ';
    }

    function sql_concat($list) {
	    switch ($this->dbType) {
		    case 'mysql':
			    return 'concat('.implode(',',$list).')';
                    case 'mysqli':
                            return 'concat('.implode(',',$list).')';
		    case 'pgsql':
			    return '('.implode('||',$list).')';
		    default:
			    throw new Exception("unsupported dbtype \"".$this->dbType."\"");
	    }
    }
    ## Code-Contribution given by weigelt@metux.de - Ends

    /* ADODB newly added. replacement for mysql_result() */
    function query_result(&$result, $row, $col=0) {
		if (!is_object($result))
	                throw new Exception("result is not an object");
		$result->Move($row);
		$rowdata = $this->change_key_case($result->FetchRow());
		//$this->println($rowdata);
		//Commented strip_selected_tags and added to_html function for HTML tags vulnerability
		if($col == 'fieldlabel') $coldata = $rowdata[$col];
		else $coldata = to_html($rowdata[$col]);
		return $coldata;
    }

	// Function to get particular row from the query result
	function query_result_rowdata(&$result, $row=0) {
		if (!is_object($result))
                throw new Exception("result is not an object");
		$result->Move($row);
		$rowdata = $this->change_key_case($result->FetchRow());

		foreach($rowdata as $col => $coldata) {
			if($col != 'fieldlabel')
				$rowdata[$col] = to_html($coldata);
		}
		return $rowdata;
	}

	/**
	 * Get an array representing a row in the result set
	 * Unlike it's non raw siblings this method will not escape
	 * html entities in return strings.
	 *
	 * The case of all the field names is converted to lower case.
	 * as with the other methods.
	 *
	 * @param &$result The query result to fetch from.
	 * @param $row The row number to fetch. It's default value is 0
	 *
	 */
	function raw_query_result_rowdata(&$result, $row=0) {
		if (!is_object($result))
                throw new Exception("result is not an object");
		$result->Move($row);
		$rowdata = $this->change_key_case($result->FetchRow());
		return $rowdata;
	}

    function getAffectedRowCount(&$result){
		global $log;
		$log->debug('getAffectedRowCount');
		$rows =$this->database->Affected_Rows();
		$log->debug('getAffectedRowCount rows = '.$rows);
		return $rows;
    }

    function requireSingleResult($sql, $dieOnError=false,$msg='', $encode=true) {
		$result = $this->query($sql, $dieOnError, $msg);

		if($this->getRowCount($result ) == 1)
	    	return $result;
		$this->log->error('Rows Returned:'. $this->getRowCount($result) .' More than 1 row returned for '. $sql);
		return '';
    }
	/* function which extends requireSingleResult api to execute prepared statment
	 */

    function requirePsSingleResult($sql, $params, $dieOnError=false,$msg='', $encode=true) {
		$result = $this->pquery($sql, $params, $dieOnError, $msg);

		if($this->getRowCount($result ) == 1)
	    	return $result;
		$this->log->error('Rows Returned:'. $this->getRowCount($result) .' More than 1 row returned for '. $sql);
		return '';
    }

    function fetchByAssoc(&$result, $rowNum = -1, $encode=true) {
		if($result->EOF) {
		    $this->println("ADODB fetchByAssoc return null");
		    return NULL;
		}
		if(isset($result) && $rowNum < 0) {
		    $row = $this->change_key_case($result->GetRowAssoc(false));
		    $result->MoveNext();
		    if($encode&& is_array($row))
				return array_map('to_html', $row);
		    return $row;
		}

		if($this->getRowCount($result) > $rowNum) {
		    $result->Move($rowNum);
		}
		$this->lastmysqlrow = $rowNum;
		$row = $this->change_key_case($result->GetRowAssoc(false));
		$result->MoveNext();
		$this->println($row);

		if($encode&& is_array($row))
			return array_map('to_html', $row);
		return $row;
    }

    function getNextRow(&$result, $encode=true){
		global $log;
		$log->info('getNextRow');
		if(isset($result)){
	    	$row = $this->change_key_case($result->FetchRow());
		    if($row && $encode&& is_array($row))
				return array_map('to_html', $row);
	    	return $row;
		}
		return null;
    }

    function fetch_row(&$result, $encode=true) {
		return $this->getNextRow($result);
    }

    function field_name(&$result, $col) {
		return $result->FetchField($col);
    }

    function getQueryTime(){
		return $this->query_time;
    }

    function connect($dieOnError = false) {
		global $dbconfigoption,$dbconfig;
		if(!isset($this->dbType)) {
		    $this->println("ADODB Connect : DBType not specified");
		    return;
		}
		$this->database = ADONewConnection($this->dbType);

		$result = $this->database->PConnect($this->dbHostName, $this->userName, $this->userPassword, $this->dbName);
		if ($result) {
			$this->database->LogSQL($this->enableSQLlog);

			// 'SET NAMES UTF8' needs to be executed even if database has default CHARSET UTF8
			// as mysql server might be running with different charset!
			// We will notice problem reading UTF8 characters otherwise.
			if($this->isdb_default_utf8_charset) {
				$this->executeSetNamesUTF8SQL(true);
			}
		}
	}

	/**
	 * Constructor
	 */
    function PearDatabase($dbtype='',$host='',$dbname='',$username='',$passwd='') {
		global $currentModule;
		$this->log = LoggerManager::getLogger('PearDatabase_'. $currentModule);
		$this->resetSettings($dbtype,$host,$dbname,$username,$passwd);

		// Initialize performance parameters
		$this->isdb_default_utf8_charset = PerformancePrefs::getBoolean('DB_DEFAULT_CHARSET_UTF8');
		// END

	if(!isset($this->dbType))
	{
	    $this->println("ADODB Connect : DBType not specified");
	    return;
	}

    }

    function resetSettings($dbtype,$host,$dbname,$username,$passwd){
		global $dbconfig, $dbconfigoption;

		if($host == '') {
		    $this->disconnect();
		    $this->setDatabaseType($dbconfig['db_type']);
	    	$this->setUserName($dbconfig['db_username']);
		    $this->setUserPassword($dbconfig['db_password']);
		    $this->setDatabaseHost( $dbconfig['db_hostname']);
	    	$this->setDatabaseName($dbconfig['db_name']);
		    $this->dbOptions = $dbconfigoption;
		    if($dbconfig['log_sql'])
	    		$this->enableSQLlog = ($dbconfig['log_sql'] == true);
		} else {
		    $this->disconnect();
		    $this->setDatabaseType($dbtype);
	    	$this->setDatabaseName($dbname);
		    $this->setUserName($username);
		    $this->setUserPassword($passwd);
	    	$this->setDatabaseHost( $host);
		}
    }

    function quote($string){
		return $this->database->qstr($string);
    }

    function disconnect() {
		$this->println("ADODB disconnect");
		if(isset($this->database)){
	    	if($this->dbType == "mysql"){
			mysql_close($this->database->_connectionID);
	    }else if($this->dbType=="mysqli"){
                mysqli_close($this->database->_connectionID);
            }
            else {
			$this->database->disconnect();
	    }
	    unset($this->database);
		}
    }

    function setDebug($value) {
		$this->database->debug = $value;
    }

    // ADODB newly added methods
    function createTables($schemaFile, $dbHostName=false, $userName=false, $userPassword=false, $dbName=false, $dbType=false) {
		$this->println("ADODB createTables ".$schemaFile);
		if($dbHostName!=false) $this->dbHostName=$dbHostName;
		if($userName!=false) $this->userName=$userPassword;
		if($userPassword!=false) $this->userPassword=$userPassword;
		if($dbName!=false) $this->dbName=$dbName;
		if($dbType!=false) $this->dbType=$dbType;

		$this->checkConnection();
		$db = $this->database;
		$schema = new adoSchema( $db );
		//Debug Adodb XML Schema
		$schema->XMLS_DEBUG = TRUE;
		//Debug Adodb
		$schema->debug = true;
		$sql = $schema->ParseSchema( $schemaFile );

		$this->println("--------------Starting the table creation------------------");
		$result = $schema->ExecuteSchema( $sql, $this->continueInstallOnError );
		if($result) print $db->errorMsg();
		// needs to return in a decent way
		$this->println("ADODB createTables ".$schemaFile." status=".$result);
		return $result;
    }

    function createTable($tablename, $flds) {
		$this->println("ADODB createTable table=".$tablename." flds=".$flds);
		$this->checkConnection();
		$dict = NewDataDictionary($this->database);
		$sqlarray = $dict->CreateTableSQL($tablename, $flds);
		$result = $dict->ExecuteSQLArray($sqlarray);
		$this->println("ADODB createTable table=".$tablename." flds=".$flds." status=".$result);
		return $result;
    }

    function alterTable($tablename, $flds, $oper) {
		$this->println("ADODB alterTableTable table=".$tablename." flds=".$flds." oper=".$oper);
		$this->checkConnection();
		$dict = NewDataDictionary($this->database);

		if($oper == 'Add_Column') {
		    $sqlarray = $dict->AddColumnSQL($tablename, $flds);
		} else if($oper == 'Delete_Column') {
		    $sqlarray = $dict->DropColumnSQL($tablename, $flds);
		}
		$this->println("sqlarray");
		$this->println($sqlarray);

		$result = $dict->ExecuteSQLArray($sqlarray);

		$this->println("ADODB alterTableTable table=".$tablename." flds=".$flds." oper=".$oper." status=".$result);
		return $result;
    }

    function getColumnNames($tablename) {
		$this->println("ADODB getColumnNames table=".$tablename);
		$this->checkConnection();
		$adoflds = $this->database->MetaColumns($tablename);
		$i=0;
		foreach($adoflds as $fld) {
		    $colNames[$i] = $fld->name;
		    $i++;
		}
		return $colNames;
    }

    function formatString($tablename,$fldname, $str) {
		$this->checkConnection();
		$adoflds = $this->database->MetaColumns($tablename);

		foreach ( $adoflds as $fld ) {
		    if(strcasecmp($fld->name,$fldname)==0) {
				$fldtype =strtoupper($fld->type);
				if(strcmp($fldtype,'CHAR')==0 || strcmp($fldtype,'VARCHAR') == 0 || strcmp($fldtype,'VARCHAR2') == 0 || strcmp($fldtype,'LONGTEXT')==0 || strcmp($fldtype,'TEXT')==0) {
				    return $this->database->Quote($str);
				} else if(strcmp($fldtype,'DATE') ==0 || strcmp($fldtype,'TIMESTAMP')==0) {
				    return $this->formatDate($str);
				} else {
				    return $str;
				}
		    }
		}
		$this->println("format String Illegal field name ".$fldname);
		return $str;
    }

    function formatDate($datetime, $strip_quotes=false) {
		$this->checkConnection();
		$db = &$this->database;
		$date = $db->DBTimeStamp($datetime);
		/* remove single quotes to use the date as parameter for Prepared statement */
		if($strip_quotes == true) {
			return trim($date, "'");
		}
		return $date;
    }

    function getDBDateString($datecolname) {
		$this->checkConnection();
		$db = &$this->database;
		$datestr = $db->SQLDate("Y-m-d, H:i:s" ,$datecolname);
		return $datestr;
    }

    function getUniqueID($seqname) {
		$this->checkConnection();
		return $this->database->GenID($seqname."_seq",1);
	}

    function get_tables() {
		$this->checkConnection();
		$result = & $this->database->MetaTables('TABLES');
		$this->println($result);
		return $result;
    }

	//To get a function name with respect to the database type which escapes strings in given text
	function sql_escape_string($str)
	{
		if($this->isMySql()){
			$result_data = ($this->dbType=='mysqli')?mysqli_real_escape_string($this->database->_connectionID,$str):mysql_real_escape_string($str);
                }
		elseif($this->isPostgres())
			$result_data = pg_escape_string($str);
		return $result_data;
	}

	// Function to get the last insert id based on the type of database
	function getLastInsertID($seqname = '') {
		if($this->isPostgres()) {
			$result = pg_query("SELECT currval('".$seqname."_seq')");
			if($result)
			{
				$row = pg_fetch_row($result);
				$last_insert_id = $row[0];
			}
		} else {
			$last_insert_id = $this->database->Insert_ID();
		}
		return $last_insert_id;
	}

	// Function to escape the special characters in database name based on database type.
	function escapeDbName($dbName='') {
		if ($dbName == '')  $dbName = $this->dbName;
		if($this->isMySql()) {
			$dbName = "`{$dbName}`";
		}
		return $dbName;
	}

	function check_db_utf8_support() {
		global $db_type;
		if($db_type == 'pgsql')
			return true;
		$dbvarRS = $this->database->Execute("show variables like '%_database' ");
		$db_character_set = null;
		$db_collation_type = null;
		while(!$dbvarRS->EOF) {
			$arr = $dbvarRS->FetchRow();
			$arr = array_change_key_case($arr);
			switch($arr['variable_name']) {
				case 'character_set_database' : $db_character_set = $arr['value']; break;
				case 'collation_database'     : $db_collation_type = $arr['value']; break;
			}
			// If we have all the required information break the loop.
			if($db_character_set != null && $db_collation_type != null) break;
		}
		return (stristr($db_character_set, 'utf8') && stristr($db_collation_type, 'utf8'));
	}

	function get_db_charset() {
		global $db_type;
		if($db_type == 'pgsql')
			return 'UTF8';
		$dbvarRS = $this->database->query("show variables like '%_database' ");
		$db_character_set = null;
		while(!$dbvarRS->EOF) {
			$arr = $dbvarRS->FetchRow();
			$arr = array_change_key_case($arr);
			if($arr['variable_name'] == 'character_set_database') {
				$db_character_set = $arr['value'];
				break;
			}
		}
		return $db_character_set;
	}
} /* End of class */

if(empty($adb)) {
	$adb = new PearDatabase();
	$adb->connect();
}
//$adb->database->setFetchMode(ADODB_FETCH_BOTH);
?>


text:
// ==========================================================================
//  Squidex Headless CMS
// ==========================================================================
//  Copyright (c) Squidex UG (haftungsbeschränkt)
//  All rights reserved. Licensed under the MIT license.
// ==========================================================================

using System.Collections.Generic;
using System.Threading.Tasks;
using FluentAssertions;
using Squidex.Domain.Apps.Core.ValidateContent.Validators;
using Xunit;

namespace Squidex.Domain.Apps.Core.Operations.ValidateContent.Validators
{
    public class CollectionValidatorTests
    {
        private readonly List<string> errors = new List<string>();

        [Fact]
        public async Task Should_not_add_error_if_value_is_valid()
        {
            var sut = new CollectionValidator(true, 1, 3);

            await sut.ValidateAsync(new List<int> { 1, 2 }, errors);

            Assert.Empty(errors);
        }

        [Fact]
        public async Task Should_not_add_error_if_optional()
        {
            var sut = new CollectionValidator(true, 1, 3);

            await sut.ValidateOptionalAsync(null, errors);

            Assert.Empty(errors);
        }

        [Fact]
        public async Task Should_add_error_if_value_is_null()
        {
            var sut = new CollectionValidator(true, 1, 3);

            await sut.ValidateAsync(null, errors);

            errors.Should().BeEquivalentTo(
                new[] { "Field is required." });
        }

        [Fact]
        public async Task Should_add_error_if_collection_has_too_few_items()
        {
            var sut = new CollectionValidator(true, 2, 3);

            await sut.ValidateAsync(new List<int> { 1 }, errors);

            errors.Should().BeEquivalentTo(
                new[] { "Must have at least 2 item(s)." });
        }

        [Fact]
        public async Task Should_add_error_if_collection_has_too_many_items()
        {
            var sut = new CollectionValidator(true, 2, 3);

            await sut.ValidateAsync(new List<int> { 1, 2, 3, 4 }, errors);

            errors.Should().BeEquivalentTo(
                new[] { "Must have not more than 3 item(s)." });
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
/**
 */
package qualities;

/**
 *
 * A representation of the model object 'Learnability'.
 *
 *
 *
 * @see qualities.QualitiesPackage#getLearnability()
 * @model
 * @generated
 */
public interface Learnability extends Usability {
} // Learnability


text:
        <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 100 100" enable-background="new 0 0 100 100" xml:space="preserve" style="
                width: 24px; height: 24px;">
          <path d="M 50 0 L 100 14 L 92 80 Z" fill="rgba(139, 195, 74, 0.5)"></path>
          <path d="M 92 80 L 50 0 L 50 100 Z" fill="rgba(139, 195, 74, 0.8)"></path>
          <path d="M 8 80 L 50 0 L 50 100 Z" fill="#fff"></path>
          <path d="M 50 0 L 8 80 L 0 14 Z" fill="rgba(255, 255, 255, 0.6)"></path>
        </svg>
        Reset Password

      <form name="resetPassword" ng-submit="resetsubmit()" novalidate>

          <input type="password" class="md-input" name="password" ng-model="reset.password" required maxlength="10">
          New Password

          Password is required.

          <input type="password" class="md-input" name="confirmpassword" ng-model="reset.confirmpassword" pw-check='password' required maxlength="10"  ui-validate=" '$value==reset.password' " ui-validate-watch=" 'password' ">
          Confirm Password

            Passwords do not match!
               Confirm Password is required.

        <button md-ink-ripple type="submit" class="md-btn md-raised pink btn-block p-h-md" >Save Password and Login</button>
      </form>

Return to <button ui-sref="access.login" class="md-btn">Sign in</button>


text:
import Ember from 'ember';

export default Ember.Mixin.create({
  pollInterval: 2000,

  growl: Ember.inject.service(),

  pollTimer: null,

  setupController() {
    this._super(...arguments);
    this.scheduleTimer();
  },

  deactivate() {
    this.cancelTimer();
  },

  scheduleTimer() {
    Ember.run.cancel(this.get('pollTimer'));
    this.set('pollTimer', Ember.run.later(() => {
      let controller = this.controller;
      let qp = {};
      (controller.get('queryParams')||[]).forEach((param) => {
        qp[param] = controller.get(param);
      });
      this.model(qp).then((model) => {
        this.controller.set('model', model);

        if ( this.get('pollTimer') ) {
          this.scheduleTimer();
        }
      }).catch((err) => {
        this.get('growl').fromError(err);
      });
    }, this.get('pollInterval')));
  },

  cancelTimer() {
    Ember.run.cancel(this.get('pollTimer'));
    // This prevents scheduleTimer from rescheduling if deactivate happened at just the wrong time.
    this.set('pollTimer', null);
  }
});


text:
/* -*-C++-*-
 *****************************************************************************
 *
 * File:         CharInfo.cpp
 * Description:  The implementation for the CharInfo class. This class defines
 *   	 	 and provides features/information about character sets,
 *		 collations and coercibility that are supported by SQL/MX.
 *
 *
 * Created:      7/8/98
 * Modified:     $Date: 2006/11/01 01:38:09 $ (GMT)
 * Language:     C++
 * Status:       $State: Exp $
 *
 *
 *
 *****************************************************************************
 */

#include "NAWinNT.h"

#include "BaseTypes.h"
#include "charinfo.h"
#include "ComASSERT.h"
#include "ComMPLoc.h"
#include "dfs2rec.h"		// for LOCALE stuff: REC_xBYTE_LOCALE_*
#include "SQLCLIdev.h"		// for LOCALE stuff: SQLCHARSETCODE_*
#include "str.h"
#include "wstr.h"
#include "SQLTypeDefs.h"
#include "CmpMessage.h"
#include "CmpConnection.h"
#include "CmpContext.h"
#include "CmpCommon.h"

#ifdef NA_STD_NAMESPACE
using namespace std;
#endif

//****************************************************************************
// CHARSET stuff
//****************************************************************************

#ifdef NA_WIDE_CHARACTER
  #define IF_WIDE TRUE
#else
  #define IF_WIDE FALSE
#endif

  #define IF_NSK FALSE

struct mapCS {
  CharInfo::CharSet cs;
  const char*       name;
  size_t	    namelen;		// len(SQLCHARSETSTRING_xxx)
  NABoolean	    supported;
  NABoolean	    fully_supported;
  Int32             minBytesPerChar;
  Int32             maxBytesPerChar;
  const char*       replacementChar;
};

// Arranged as an array, starting with CHARSET_MIN and ending with CHARSET_MAX
static const struct mapCS mapCSArray[] = {
  // CharSet enum value              string value of charset    name  supp.    fully   min / max  rep.
  //                                                            len            supp.   bytes/char char
  { /*-2*/ CharInfo::KSC5601_MP,     SQLCHARSETSTRING_KSC5601,     7, IF_NSK,  IF_NSK, 2,    2, NULL },
  { /*-1*/ CharInfo::KANJI_MP,       SQLCHARSETSTRING_KANJI,       5, IF_NSK,  IF_NSK, 2,    2, NULL },
  { /* 0*/ CharInfo::UnknownCharSet, SQLCHARSETSTRING_UNKNOWN,     9, FALSE,   FALSE,  1,    1, "?" },

  { /* 1*/ CharInfo::ISO88591,       SQLCHARSETSTRING_ISO88591,    8, TRUE,    TRUE,   1,    1, "?" },
  { /* 2*/ CharInfo::ISO88592,       SQLCHARSETSTRING_ISO88592,    8, FALSE,   FALSE,  1,    1, "?" },
  { /* 3*/ CharInfo::ISO88593,       SQLCHARSETSTRING_ISO88593,    8, FALSE,   FALSE,  1,    1, "?" },
  { /* 4*/ CharInfo::ISO88594,       SQLCHARSETSTRING_ISO88594,    8, FALSE,   FALSE,  1,    1, "?" },
  { /* 5*/ CharInfo::ISO88595,       SQLCHARSETSTRING_ISO88595,    8, FALSE,   FALSE,  1,    1, "?" },
  { /* 6*/ CharInfo::ISO88596,       SQLCHARSETSTRING_ISO88596,    8, FALSE,   FALSE,  1,    1, "?" },
  { /* 7*/ CharInfo::ISO88597,       SQLCHARSETSTRING_ISO88597,    8, FALSE,   FALSE,  1,    1, "?" },
  { /* 8*/ CharInfo::ISO88598,       SQLCHARSETSTRING_ISO88598,    8, FALSE,   FALSE,  1,    1, "?" },
  { /* 9*/ CharInfo::ISO88599,       SQLCHARSETSTRING_ISO88599,    8, FALSE,   FALSE,  1,    1, "?" },
  { /*10*/ CharInfo::SJIS,           SQLCHARSETSTRING_SJIS,        4, TRUE,    FALSE,  1,    2, "?" },
  { /*11*/ CharInfo::UCS2,           SQLCHARSETSTRING_UCS2,        4, IF_WIDE, IF_WIDE,2,    2, "\xff\xfd" },
  { /*12*/ CharInfo::EUCJP,          SQLCHARSETSTRING_EUCJP,       5, TRUE,    FALSE,  1,    3, "?" },
  { /*13*/ CharInfo::BIG5,           SQLCHARSETSTRING_BIG5,        4, TRUE,    FALSE,  1,    2, "?" },
  { /*14*/ CharInfo::GB18030,        SQLCHARSETSTRING_GB18030,     7, FALSE,   FALSE,  1,    4, "?" },
  { /*15*/ CharInfo::UTF8,           SQLCHARSETSTRING_UTF8,        4, TRUE,    TRUE,   1,    4, "\xef\xbf\xbd" },
  { /*16*/ CharInfo::KSC5601,        SQLCHARSETSTRING_MB_KSC5601, 10, TRUE,    FALSE,  1,    2, "?" },
  { /*17*/ CharInfo::GB2312,         SQLCHARSETSTRING_GB2312,      6, TRUE,    FALSE,  1,    2, "?" },
  { /*18*/ CharInfo::GBK,            SQLCHARSETSTRING_GBK,         3, TRUE,    FALSE,  1,    2, "?" },
};

static const size_t SIZEOF_CS = sizeof(mapCSArray)/sizeof(mapCS);

const char* CharInfo::getCharSetName(CharSet cs, NABoolean retUnknownAsBlank)
{
  if (cs >= CHARSET_MIN && cs <= CHARSET_MAX)
    {
      if (cs != CharInfo::UnknownCharSet)
	return mapCSArray[cs-CHARSET_MIN].name;
    }

  return retUnknownAsBlank ? "" : SQLCHARSETSTRING_UNKNOWN;
}

CharInfo::CharSet CharInfo::getCharSetEnum(const char* name)
{
  if (*name == '\0' || *name == ' ')		// fastpath: if name is empty
    return CharInfo::UnknownCharSet;		// or all blanks (begins w/ ' ')

  for (size_t i = 0; i < SIZEOF_CS; i++) {
    const mapCS *map = &mapCSArray[i];
    if (name == map->name)			// fastpath: pointers identical
      return map->cs;
    else {
      // Can't use plain old strcmp here, because we want both
      //	"SJIS"  and  "SJIS  "
      // to be matched (see smdio/CmColumnsRow.cpp).
      // ##Note that this will fail if given an Ansi delimited identifier
      // ##(in a USER-DEFINED collation name, of course) w/ an embedded space!
      // ##
      // ##As no user-defined collations are allowed in NSK Rel 1,
      // ##we are not fixing this now...
      //
      size_t len = map->namelen;
      if (strncmp(name, map->name, len) == 0 &&
          (name[len] == '\0' || name[len] == ' '))	//##fails if "My Coll"!
	return map->cs;
      }
    }

  // handle alias names for charsets, those are the exception
  const char *alias = SQLCHARSETSYNONYM_SQL_TEXT;
  size_t aliasLen = strlen(alias);

  if (strncmp(name, alias, aliasLen) == 0 &&
      (name[aliasLen] == '\0' || name[aliasLen] == ' '))
    {
      return CharInfo::SQL_TEXT;
    }

  return CharInfo::UnknownCharSet;
}

NABoolean CharInfo::isCharSetSupported(CharSet cs)
{
  if (cs >= CHARSET_MIN && cs <= CHARSET_MAX)
    {
      // Special for running regress/fullstack/TEST001 on NSK:
#ifdef NA_DEBUG_C_RUNTIME
      if (IF_WIDE == FALSE &&
          mapCSArray[cs-CHARSET_MIN].maxBytesPerChar > 1 &&	// SJIS or UNICODE
          getenv("NCHAR_SJIS_DEBUG"))
        return TRUE;
#endif
      return mapCSArray[cs-CHARSET_MIN].supported;
    }

  return FALSE;
}

NABoolean CharInfo::isCharSetFullySupported(CharSet cs)
{
  if (cs >= CHARSET_MIN && cs <= CHARSET_MAX)
    {
      // Special for running regress/fullstack/TEST001 on NSK:
#ifdef NA_DEBUG_C_RUNTIME
      if (IF_WIDE == FALSE &&
          mapCSArray[cs-CHARSET_MIN].maxBytesPerChar > 1 &&	// SJIS or UNICODE
          getenv("NCHAR_SJIS_DEBUG"))
        return TRUE;
#endif
      return mapCSArray[cs-CHARSET_MIN].fully_supported;
    }

  return FALSE;
}

NABoolean CharInfo::isHexFormatSupported(CharSet cs) {
  return ( (cs == CharInfo::ISO88591) || (cs == CharInfo::UNICODE) ||
           (cs == CharInfo::UTF8) ||
           (is_NCHAR_MP(cs))
         );
}

NABoolean CharInfo::isTerminalCharSetSupported(CharSet cs) {
  return ((cs == CharInfo::ISO88591) || (cs == CharInfo::SJIS)   ||
          (cs == CharInfo::EUCJP)    || (cs == CharInfo::BIG5)   ||
          (cs == CharInfo::GB18030)  || (cs == CharInfo::GB2312) ||
                                        (cs == CharInfo::GBK   ) ||
          (cs == CharInfo::KSC5601)  || (cs == CharInfo::UTF8)) ;
}

NABoolean CharInfo::isMsgCharSetSupported(CharSet cs) {
  return ( (cs == CharInfo::UTF8) || (cs == CharInfo::UNICODE) );
}

//LCOV_EXCL_START :rfi
// see TESTCHARSET in CmpMain.cpp
void CharInfo::toggleCharSetSupport(CharSet cs)
{
#ifdef NA_DEBUG_C_RUNTIME
    size_t i;
    for (i = 0; i < SIZEOF_CS; i++)
      if (cs == mapCSArray[i].cs)
	break;
    cerr << "toggleCharSetSupport: " << getCharSetName(cs) << " ";
    if (cs == UnknownCharSet || i >= SIZEOF_CS)
      cerr << "*not* toggled: "<< (Int32)cs << ", " << i << endl;
    else {
      cerr << "toggled from " << mapCSArray[i].supported
		    << " to " << !mapCSArray[i].supported << endl;
      NABoolean *nonconstSupported = (NABoolean *)&mapCSArray[i].supported;
      *nonconstSupported = !*nonconstSupported;
    }
#endif
}
//LCOV_EXCL_STOP

// for R2 FCS.
CharInfo::CharSet CharInfo::getEncoding(const CharInfo::CharSet x)
{
   switch (x)
   {
     case CharInfo::ISO88591:
     case CharInfo::UNICODE:
        return x;
        break;

     case CharInfo::SJIS:
     case CharInfo::KANJI_MP:
     case CharInfo::KSC5601_MP:
        return CharInfo::ISO88591;
        break;

     default:
        return x;
        break;
   }
}

Int32 CharInfo::minBytesPerChar(CharSet cs)
{
  ComASSERT(cs >= CHARSET_MIN && cs <= CHARSET_MAX);

  return mapCSArray[cs-CHARSET_MIN].minBytesPerChar;
}

Int32 CharInfo::maxBytesPerChar(CharSet cs)
{
  ComASSERT(cs >= CHARSET_MIN && cs <= CHARSET_MAX);

  return mapCSArray[cs-CHARSET_MIN].maxBytesPerChar;
}

Int32 CharInfo::getFSTypeFixedChar(CharSet cs)
{
  if (cs == UCS2)
    return REC_BYTE_F_DOUBLE;

  return REC_BYTE_F_ASCII;
}

Int32 CharInfo::getFSTypeANSIChar(CharSet cs)
{
  if (cs == UCS2)
    return REC_BYTE_V_ANSI_DOUBLE;

  return REC_BYTE_V_ANSI;
}

const char* CharInfo::getReplacementCharacter(CharSet cs)
{
  ComASSERT(cs >= CHARSET_MIN && cs <= CHARSET_MAX);

  return mapCSArray[cs-CHARSET_MIN].replacementChar;
}

NABoolean CharInfo::isVariableWidthMultiByteCharSet(CharSet cs)
{
  if (cs >= CHARSET_MIN && cs <= CHARSET_MAX)
    {
      return (mapCSArray[cs-CHARSET_MIN].minBytesPerChar !=
              mapCSArray[cs-CHARSET_MIN].maxBytesPerChar);
    }

  return FALSE;
}

NABoolean
CharInfo::checkCodePoint(const NAWchar* inputStr, Int32 inputLen, CharInfo::CharSet cs)
{
  if (!inputStr || (inputLen <= 0) ) return TRUE;

  if (cs == CharInfo::UNICODE) {
     for (Int32 i = 0; i < inputLen; i++) {
       if (!unicode_char_set::isValidUCS2CodePoint(inputStr[i]))
          return FALSE;
     }
     return TRUE;
  }
  return FALSE;
}

//****************************************************************************
// COLLATION stuff:  CollationInfo methods
//
//	The design here, particularly the 4-part name, is because we need to
//	allow the Parser to lookup names, and it has no notion of
//	applying defaults to a possibly qualified identifier
//	(and, builtin/predefined system collations are 1-part and must take
//	precedence!).  This should probably be changed so that Parser need
//	do no lookup at all, that collation names be resolved later, in Binder!
//****************************************************************************

CollationInfo::CollationInfo(CollHeap *h,
			     CharInfo::Collation co,
			     const char *name,
			     CollationFlags flags,
			     size_t *siz)	  /* array[SIZEARRAY_SIZE] */
: co_(co), flags_(flags)
{
  ComASSERT(name);
  namelen_ = strlen(name);	// allowed to be 0 if siz[] not passed in
  if (siz) {
//LCOV_EXCL_START :cnu -- As of 8/30/2011, no support in SQ for Collations
    size_t cnt = siz[0];
#pragma nowarn(270)   // warning elimination
    ComASSERT(cnt >= 0 && cnt < MAX_NAME_PARTS);
#pragma warn(270)  // warning elimination
    ComASSERT(namelen_ > 0 && namelen_ == siz[1]);
    for (size_t off = 0; off < OFFSETARRAY_SIZE; off++) {
      synonymOffset_[off] = (off < cnt) ? siz[off+2] : 0;
    }
//LCOV_EXCL_STOP
  } else
    synonymOffset_[0] = synonymOffset_[1] = synonymOffset_[2] = 0;
  if (flags_ & NO_ALLOC_AND_COPY_IN_CTOR)
    name_ = name;
  else {
    name_ = new (h) char[namelen_+1];
    strcpy((char *)name_, name);
  }
}

//LCOV_EXCL_START :cnu -- As of 8/30/2011, no support in SQ for Collations
void CollationInfo::display() const
{
}
//LCOV_EXCL_STOP
//
CollationDB::CollationDB(CollHeap *h)
  : CollationDBSupertype(h), heap_(h), refreshNeeded_(TRUE)
{
    if (this == &CharInfo::builtinCollationDB_) return;
    cmpCurrentContext->getCollationDBList()->insert(this);
}

CollationDB::CollationDB(CollHeap *h, const CollationInfo *co, size_t count)
  : CollationDBSupertype(h), heap_(h), refreshNeeded_(!!count)
{
   while (count--) CollationDBSupertype::insert(co++);
   if (this == &CharInfo::builtinCollationDB_) return;
   cmpCurrentContext->getCollationDBList()->insert(this);
}

CollationDB::~CollationDB()
{
   if (this == &CharInfo::builtinCollationDB_) return;
   clearAndReset();
   cmpCurrentContext->getCollationDBList()->remove(this);
}

//LCOV_EXCL_START :cnu -- As of 8/30/2011, no support in SQ for Collations
void CollationDB::display() const
{
}
//LCOV_EXCL_STOP

void CollationDB::Display()
{
  CollationDBList *CDBlist = cmpCurrentContext->getCollationDBList();
  CollIndex i, n = CDBlist->entries();
  for (i = 0; i < n; i++)
    (*CDBlist)[i]->display();
}

//****************************************************************************
// COLLATION stuff:  CollationDB data and methods
//
// Collations may be simple 1-part names for system predefined collations;
// they are also allowed to be user-defined, hence qualified names
// (3-part Ansi, or 4-part NSK).
//
//	The insert methods and their static data are implemented in
//	../optimizer/SchemaDB.cpp instead of here, because
//	one method uses a QualifiedName, which is defined in ../optimizer --
//	#include and DLL-link problems occur if we try to implement
//	here in ../common.
//	The self-maintaining CDB-chain and the static CharInfo::getCollation*()
//	caller interface make this work.
//****************************************************************************

inline
CollationDB * CollationDB::nextCDB() const
{
  // If this is in the CDB chain [should always be true -- defensive prog'ing],
  // return the next CDB in the chain, if there is one.
  CollationDBList *CDBlist = cmpCurrentContext->getCollationDBList();

  CollIndex i = CDBlist->index((CollationDB *)this);
  if (i != NULL_COLL_INDEX)				// [defensive prog'ing]
    for (CollIndex n = CDBlist->entries(); ++i < n; )
      if ((*CDBlist)[i] && (*CDBlist)[i] != this)		// [defensive prog'ing]
        return (*CDBlist)[i];

  return NULL;
}

const CollationInfo* CollationDB::getCollationInfo(CharInfo::Collation co) const
{
  CollIndex i, n = entries();
  for (i = 0; i < n; i++)
    if (co == at(i)->co_)
      return at(i);

  CollationDB *next = nextCDB();
  return next ? next->getCollationInfo(co) : NULL;
}

const char* CollationDB::getCollationName(CharInfo::Collation co,
					  NABoolean retUnknownAsBlank) const
{
  if (co != CharInfo::UNKNOWN_COLLATION) {
    const CollationInfo *ci = getCollationInfo(co);
    if (ci) return ci->name_;
  }

  return retUnknownAsBlank ? "" : SQLCOLLATIONSTRING_UNKNOWN;
}

Int32 CollationDB::getCollationFlags(CharInfo::Collation co) const
{
  const CollationInfo *ci = getCollationInfo(co);
  if (ci) return ci->flags_;

  return CollationInfo::ALL_NEGATIVE_SYNTAX_FLAGS;
}

// We need the namlen arg here, unlike CharInfo::getCharSetEnum(),
// because whereas CHARSETs are SQL simple identifiers
// (must begin with a Latin letter, a regular not "delimited" identifier),
// COLLATIONs are SQL identifiers
// (can be delimited and contain spaces).
//
// So we must check that any spaces are *trailing* spaces only.
//
// The smdio/CmColumnsRow.cpp and sqlcat/ReadTableDef.cpp
// callers do not have a '\0'-terminated string,
// hence our needing this length arg to pass in.
//
// We can't use plain old strcmp here, because we want both
//	"SJIS"  and  "SJIS  "
// to be matched.  The public caller CharInfo::getCollationEnum()
// inputs to us a correct namlen in either case (4, for the SJIS example).
//
CharInfo::Collation CollationDB::getCollationEnum(const char* name,
						  NABoolean formatNSK,
						  size_t namlen) const
{
  ComASSERT(namlen);

  CollIndex n = entries();
  for (CollIndex i = 0; i < n; i++) {
    const CollationInfo *map = at(i);

    if (name == map->name_)			// fastpath: pointers identical
      return map->co_;

    // If we want NSK format and this i'th name is not NSK, or
    // if we don't want NSK fmt and this name is NSK,
    // then skip this name.
    // Exception is that the builtin collations are always compared.
    if (map->co_ >= CharInfo::FIRST_USER_DEFINED_COLLATION &&
        formatNSK XOR HasMPLocPrefix(map->name_))
      continue;

    size_t off = 0;
    for (size_t j = 0; ; j++) {
      size_t len = map->namelen_ - off;
      if (len == namlen) {
        if (strncmp(name, &map->name_[off], len) == 0)
	  return map->co_;
        else break;
      }
      if (len < namlen) break;
      if (j == CollationInfo::OFFSETARRAY_SIZE) break;
      off = map->synonymOffset_[j];
      if (off == 0) break;
    } // loop j

  } // loop i

  CollationDB *next = nextCDB();
  return next ? next->getCollationEnum(name, formatNSK, namlen)
  	      : CharInfo::UNKNOWN_COLLATION;

} // CollationDB::getCollationEnum()

//****************************************************************************
// COLLATION stuff:  CharInfo methods
//****************************************************************************

#define STATIC_STR	CollationInfo::NO_ALLOC_AND_COPY_IN_CTOR
#define STATIC_NEG	CollationInfo::ALL_NEGATIVE_PLUS_STATIC
static const CollationInfo mapCOArray[] = {
  CollationInfo(NULL, CharInfo::DefaultCollation,   SQLCOLLATIONSTRING_DEFAULT,
  			STATIC_STR),
  CollationInfo(NULL, CharInfo::CZECH_COLLATION,   SQLCOLLATIONSTRING_CZECH,
  			STATIC_STR),
  CollationInfo(NULL, CharInfo::CZECH_COLLATION_CI,   SQLCOLLATIONSTRING_CZECH_CI,
  			STATIC_STR),
  CollationInfo(NULL, CharInfo::UNKNOWN_COLLATION,  SQLCOLLATIONSTRING_UNKNOWN,
  			STATIC_NEG)
};
static const size_t SIZEOF_CO = sizeof(mapCOArray)/sizeof(CollationInfo);
const CollationDB CharInfo::builtinCollationDB_(NULL, mapCOArray, SIZEOF_CO);

CharInfo::Collation CharInfo::getCollationEnum(const char* name,
					       NABoolean formatNSK,
					       size_t namlen)
{
  if (namlen == 0)
    namlen = strlen(name);
  else {
    const char *n = &name[namlen-1];
    for (;
         name < n && (*n == ' ' || *n == '\0');
	 n--)
      ;
    namlen = (*n == ' ' || *n == '\0') ? 0 : n - name + 1;
  }
  if (namlen == 0)				// fastpath: if name is empty
    return CharInfo::UNKNOWN_COLLATION;

  // Collapse any nonzero formatNSK to single bit, for XOR
  return builtinCollationDB_.getCollationEnum(name, !!formatNSK, namlen);
}

const char* CharInfo::getCollationName(Collation co,
				       NABoolean retUnknownAsBlank)
{
  return builtinCollationDB_.getCollationName(co, retUnknownAsBlank);
}

Int32 CharInfo::getCollationFlags(Collation co)
{
  return builtinCollationDB_.getCollationFlags(co);
}

//****************************************************************************
// COERCIBILITY stuff
//****************************************************************************

//LCOV_EXCL_START :cnu -- As of 8/30/2011, no support in SQ for Collations
const char* CharInfo::getCoercibilityText(Coercibility ce)
{
  // These are not keywords, not tokens, not part of Ansi syntax.
  // They are part of Ansi concepts; cf. Ansi 4.2.3.
  switch (ce) {
    case IMPLICIT:		return "implicit";
    case EXPLICIT:		return "explicit";
    case COERCIBLE:		return "coercible";
    case NO_COLLATING_SEQUENCE:	return "no-collating-sequence";
    default:			return "unknown";
  }
}
//LCOV_EXCL_STOP

// "Which coercibility wins?"
// Returns 0 if they're equal, 1 if the first one wins, 2 if the second.
// This follows the strict Ansi precedence of
//      COERCIBLE < IMPLICIT < NO_COLLATING_SEQUENCE < EXPLICIT
//
// ## (As an aside, note that CharType::computeCoAndCo()
// ## could be pulled out into a static CharInfo:: method placed here.)
//
//LCOV_EXCL_START :cnu -- As of 8/30/2011, no support in SQ for Collations
Int32 CharInfo::compareCoercibility(CharInfo::Coercibility ce1,
				  CharInfo::Coercibility ce2)
{
  if (ce1 == ce2) return 0;

  if (ce1 == CharInfo::COERCIBLE) return 2;		// 1 yields to 2
  if (ce2 == CharInfo::COERCIBLE) return 1;		// 2 yields to 1

  if (ce1 == CharInfo::EXPLICIT) return 1;
  if (ce2 == CharInfo::EXPLICIT) return 2;

  if (ce1 == CharInfo::NO_COLLATING_SEQUENCE) return 1;
  if (ce2 == CharInfo::NO_COLLATING_SEQUENCE) return 2;

  ComASSERT(FALSE);			// ceN IMPLICIT already handled above!
  return -1;
}
//LCOV_EXCL_STOP

//****************************************************************************
// LOCALE stuff
//****************************************************************************

const char* const CharInfo::localeCharSet_ = NULL;

Lng32 CharInfo::findLocaleCharSet()
{
  return SQLCHARSETCODE_ISO88591;

}

//LCOV_EXCL_START :cnu -- As of 8/30/2011, only caller is #if'd out
const char* CharInfo::getLocaleCharSetAsString()
{
   if (!localeCharSet_) {
      switch ( findLocaleCharSet() ) {
        case SQLCHARSETCODE_ISO88591:
          return SQLCHARSETSTRING_ISO88591;

        case SQLCHARSETCODE_UCS2:
          return SQLCHARSETSTRING_UNICODE;

        case SQLCHARSETCODE_SJIS:
          return SQLCHARSETSTRING_SJIS;

        default:
          return SQLCHARSETSTRING_UNKNOWN;
     }
   } else
     return localeCharSet_;

#pragma nowarn(203)   // warning elimination
   return SQLCHARSETSTRING_UNKNOWN;
#pragma warn(203)  // warning elimination
}
//LCOV_EXCL_STOP

Int32 CharInfo::getTargetCharTypeFromLocale()
{

  return REC_SBYTE_LOCALE_F;
}

Int32 CharInfo::getMaxConvertedLenInBytes(CharSet sourceCS,
                                          Int32   sourceLenInBytes,
                                          CharSet targetCS)
{
  if (sourceCS == targetCS)
    {
      // trivial case, no conversion
      return sourceLenInBytes;
    }
  else if (targetCS == UTF8)
    {
      // optimize some cases where we can exploit knowledge about
      // the UTF-8 encoding

      if (sourceCS == UCS2)
        {
          // Worst case is each 2 byte UCS2 char resulting in a 3 byte
          // UTF8 char. Note that no UCS2 char requires a 4 byte UTF8
          // representation.
          // 2 UTF-16 surrogate pairs (4 bytes) will be translated to
          // a 4-byte UTF-8 character, which is not the worst case.
          return 3 * sourceLenInBytes/2;
        }

      if (sourceCS == ISO88591)
        {
          // Worst case is all upper-half ISO characters, which
          // result in 2 byte UTF-8 characters. No ISO8859-1 character
          // takes up more than 2 bytes in UTF-8.
          return 2 * sourceLenInBytes;
        }
    }

  // General case, assume max number of chars in input,
  // and all of them convert to the longest output char.
  // NOTE: This also works for UTF8 to UCS2 conversions
  // and back, even though those conversions really
  // treat UCS2 as UTF16.
  return ((sourceLenInBytes/minBytesPerChar(sourceCS)) *
          maxBytesPerChar(targetCS));
}


text:
'''
 Author: Hans Erik Heggem
 Email: hans.erik.heggem@gmail.com
 Project: Master's Thesis - Autonomous Inspection Of Wind Blades
 Repository: Master's Thesis - CV (Computer Vision)
'''
import sys, warnings, unittest
from Test_main_ImportTestScripts.ImportDroneVisionScripts import ImportDroneVisionScripts
from Test_main_ImportTestScripts.ImportMasterSlaveScripts import ImportMasterSlaveScripts
from Test_main_ImportTestScripts.ImportDroneMasterSlaveScripts import ImportDroneMasterSlaveScripts
from Test_main_ImportTestScripts.ImportDataBaseScripts import ImportDataBaseScripts
from Test_main_ImportTestScripts.ImportBinScripts import ImportBinScripts

class Test_main():
	def __init__(self):
		'''CONSTRUCTOR'''
		self.SetAllKey()
		self.__run_test = False

		#warnings.filterwarnings('error') # Raise all warnings as exceptions

	def SetAllKey(self, all_key='all'):
		'''
		 @brief Set all key

		 @param all_key (default='all')
		'''
		self.__all_key = all_key

	def GetAllKey(self):
		'''
		 @brief Get all key
		'''
		return self.__all_key

	def CheckAllTests(self):
		'''
		 @brief Check if all tests are initiated

		 @return True/False
		'''
		all_tests = False
		if self.GetAllKey() in sys.argv:
			all_tests = True
		return all_tests

	def ImportTestScipts(self):
		'''
		 @brief Import test scripts
		 	- Continue adding new test scripts in the list
		'''
		self.__all_test_scripts = {'DroneVision': ImportDroneVisionScripts(), \
									'MasterSlave': ImportMasterSlaveScripts(), \
									'DroneMasterSlave': ImportDroneMasterSlaveScripts(), \
									'bin': ImportBinScripts(), \
									'DataBase': ImportDataBaseScripts()}

	def StartTest(self):
		'''
		 @brief Main start test function.
		 	Starts test as specified by user input.
		'''
		loader 	= unittest.TestLoader()
		suite 	= unittest.TestSuite()
		for test_scripts_key in self.__all_test_scripts:
			self.CheckTests(self.__all_test_scripts[test_scripts_key], suite, loader)

		if self.__run_test:
			unittest.TextTestRunner(verbosity=2).run(suite)
		else:
			for test_scripts_key in self.__all_test_scripts:
				self.PrintTestPossibilities(test_scripts_key)
			print '\nNo test input detected. Please append name of script to test, or "all" to test every script.'

	def CheckTests(self, test_scripts, suite, loader):
		'''
		 @brief Check if user specifies to test a unit from the given package.

		 @param test_scripts (dictionary)
		 @param suite (testtunits suite)
		 @param loader (testtunits loader)
		'''
		for key in test_scripts:
			if key in sys.argv or self.CheckAllTests():
				self.__run_test = True
				suite.addTest(loader.loadTestsFromTestCase(test_scripts[key]))

	def PrintTestPossibilities(self, test_scripts_key):
		'''
		 @brief Print possible test keys

		 @param test_scripts_key
		'''
		print 'Possible test units from ' + test_scripts_key + ':'
		for test_script_key in self.__all_test_scripts[test_scripts_key]:
			print test_script_key
		print '\n'


text:
/**
 * Determine the variables introduced by this assignee (array destructure,
 * object destructure, rest, etc.).
 */
import {
  ArrayInitialiser,
  AssignOp,
  Identifier,
  Node,
  ObjectInitialiser,
  ObjectInitialiserMember,
  Rest,
  Spread
} from 'decaffeinate-parser/dist/nodes';

export default function getAssigneeBindings(node: Node): Array<string> {
  if (node instanceof Identifier) {
    return [node.data];
  } else if (node instanceof ArrayInitialiser) {
    let bindings = [];
    for (let member of node.members) {
      bindings.push(...getAssigneeBindings(member));
    }
    return bindings;
  } else if (node instanceof ObjectInitialiser) {
    let bindings = [];
    for (let member of node.members) {
      bindings.push(...getAssigneeBindings(member));
    }
    return bindings;
  } else if (node instanceof ObjectInitialiserMember) {
    return getAssigneeBindings(node.expression || node.key);
  } else if (node instanceof AssignOp) {
    return getAssigneeBindings(node.assignee);
  } else if (node instanceof Spread || node instanceof Rest) {
    return getAssigneeBindings(node.expression);
  }
  return [];
}


text:
package cloudflare

import (
	"bytes"
	"encoding/json"
	"io"
	"io/ioutil"
	"net/http"

	"github.com/pkg/errors"
)

const apiURL = "https://api.cloudflare.com/client/v4"

// API holds the configuration for the current API client. A client should not
// be modified concurrently.
type API struct {
	APIKey     string
	APIEmail   string
	BaseURL    string
	headers    http.Header
	httpClient *http.Client
}

// New creates a new Cloudflare v4 API client.
func New(key, email string, opts ...Option) (*API, error) {
	if key == "" || email == "" {
		return nil, errors.New(errEmptyCredentials)
	}

	api := &API{
		APIKey:   key,
		APIEmail: email,
		BaseURL:  apiURL,
		headers:  make(http.Header),
	}

	err := api.parseOptions(opts...)
	if err != nil {
		return nil, errors.Wrap(err, "options parsing failed")
	}

	// Fall back to http.DefaultClient if the package user does not provide
	// their own.
	if api.httpClient == nil {
		api.httpClient = http.DefaultClient
	}

	return api, nil
}

// ZoneIDByName retrieves a zone's ID from the name.
func (api *API) ZoneIDByName(zoneName string) (string, error) {
	res, err := api.ListZones(zoneName)
	if err != nil {
		return "", errors.Wrap(err, "ListZones command failed")
	}
	for _, zone := range res {
		if zone.Name == zoneName {
			return zone.ID, nil
		}
	}
	return "", errors.New("Zone could not be found")
}

// makeRequest makes a HTTP request and returns the body as a byte slice,
// closing it before returnng. params will be serialized to JSON.
func (api *API) makeRequest(method, uri string, params interface{}) ([]byte, error) {
	// Replace nil with a JSON object if needed
	var reqBody io.Reader
	if params != nil {
		json, err := json.Marshal(params)
		if err != nil {
			return nil, errors.Wrap(err, "error marshalling params to JSON")
		}
		reqBody = bytes.NewReader(json)
	} else {
		reqBody = nil
	}

	resp, err := api.request(method, uri, reqBody)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, errors.Wrap(err, "could not read response body")
	}

	switch resp.StatusCode {
	case http.StatusOK:
		break
	case http.StatusUnauthorized:
		return nil, errors.Errorf("HTTP status %d: invalid credentials", resp.StatusCode)
	case http.StatusForbidden:
		return nil, errors.Errorf("HTTP status %d: insufficient permissions", resp.StatusCode)
	case http.StatusServiceUnavailable, http.StatusBadGateway, http.StatusGatewayTimeout,
		522, 523, 524:
		return nil, errors.Errorf("HTTP status %d: service failure", resp.StatusCode)
	default:
		var s string
		if body != nil {
			s = string(body)
		}
		return nil, errors.Errorf("HTTP status %d: content %q", resp.StatusCode, s)
	}

	return body, nil
}

// request makes a HTTP request to the given API endpoint, returning the raw
// *http.Response, or an error if one occurred. The caller is responsible for
// closing the response body.
func (api *API) request(method, uri string, reqBody io.Reader) (*http.Response, error) {
	req, err := http.NewRequest(method, api.BaseURL+uri, reqBody)
	if err != nil {
		return nil, errors.Wrap(err, "HTTP request creation failed")
	}

	// Apply any user-defined headers first.
	req.Header = cloneHeader(api.headers)
	req.Header.Set("X-Auth-Key", api.APIKey)
	req.Header.Set("X-Auth-Email", api.APIEmail)

	resp, err := api.httpClient.Do(req)
	if err != nil {
		return nil, errors.Wrap(err, "HTTP request failed")
	}

	return resp, nil
}

// cloneHeader returns a shallow copy of the header.
// copied from https://godoc.org/github.com/golang/gddo/httputil/header#Copy
func cloneHeader(header http.Header) http.Header {
	h := make(http.Header)
	for k, vs := range header {
		h[k] = vs
	}
	return h
}

// ResponseInfo contains a code and message returned by the API as errors or
// informational messages inside the response.
type ResponseInfo struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
}

// Response is a template.  There will also be a result struct.  There will be a
// unique response type for each response, which will include this type.
type Response struct {
	Success  bool           `json:"success"`
	Errors   []ResponseInfo `json:"errors"`
	Messages []ResponseInfo `json:"messages"`
}

// ResultInfo contains metadata about the Response.
type ResultInfo struct {
	Page    int `json:"page"`
	PerPage int `json:"per_page"`
	Count   int `json:"count"`
	Total   int `json:"total_count"`
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: vize
 * Date: 2016/4/24
 * Time: 11:23
 */
namespace app\models;
use yii\db\ActiveRecord;
class Test extends ActiveRecord{

}


text:
from common import *
import json
import base64
import requests
import os
import os.path
from ordereddict import OrderedDict

# Delete table if it exists
request = requests.get(baseurl + "/" + tablename + "/schema")

if issuccessful(request):
	request = requests.delete(baseurl + "/" + tablename + "/schema")

	if issuccessful(request):
		print "Deleted table " + tablename
	else:
		print "Errored out.  Status code was " + str(request.status_code) + "\n" + request.text

# Create Messages Table
content =  '<?xml version="1.0" encoding="UTF-8"?>'
content += '<TableSchema name="' + tablename + '">'
content += '  <ColumnSchema name="' + cfname + '" />'
content += '</TableSchema>'

# This JSON may work for table creation, but I haven't tried it
# {"name":"test5", "column_families":[{
#>              "name":"columnfam1",
#>              "bloomfilter":true,
#>              "time_to_live":10,
#>              "in_memory":false,
#>              "max_versions":2,
#>              "compression":"",
#>              "max_value_length":50,
#>              "block_cache_enabled":true
#>           }
#> ]}

request = requests.post(baseurl + "/" + tablename + "/schema", data=content, headers={"Content-Type" : "text/xml", "Accept" : "text/xml"})

if issuccessful(request):
	print "Created table " + tablename
else:
	print "Errored out while creating table.  Status code was " + str(request.status_code) + "\n" + request.text
	quit()

# Create a message  for every work of Shakespeare
sourceDir = "shakespeare"

for filename in os.listdir(sourceDir):
	shakespeare = open(os.path.join(sourceDir, filename), "rb")

	lineNumber = 0;

	rows = []
	jsonOutput = { "Row" : rows }

	for line in shakespeare:
		rowKey = username + "-" + filename + "-" + str(lineNumber).zfill(6)
		rowKeyEncoded = base64.b64encode(rowKey)

		line = base64.b64encode(line.strip())
		lineNumberEncoded = encode(lineNumber)
		usernameEncoded = base64.b64encode(username)

		cell = OrderedDict([
			("key", rowKeyEncoded),
			("Cell",
			[
				{ "column" : messagecolumnencoded, "$" : line },
				{ "column" : usernamecolumnencoded, "$" : usernameEncoded },
				{ "column" : linenumbercolumnencoded, "$" : lineNumberEncoded },
			])
		])

		rows.append(cell)

		lineNumber = lineNumber + 1

	# Submit JSON to REST server
	request = requests.post(baseurl + "/" + tablename + "/" + rowKey, data=json.dumps(jsonOutput), headers={"Content-Type" : "application/json", "Accept" : "application/json"})

	if issuccessful(request):
		print "Added messages for " + filename
	else:
		print "Errored out while loading data.  Status code was " + str(request.status_code) + "\n" + request.text
		quit()


text:
author: alex
categories:
- basededatos
date: '2016-01-01'
lastmod: 2017-03-30T17:17:30+01:00
mainclass: BaseDeDatos
url: /consulta-de-datos-clausula-where/
title: "Consulta de Datos - Cláusula WHERE"
---

La cláusula WHERE se utiliza para seleccionar aquellos registros que cumplen una o más condiciones. Su sintaxis es:

```sql
WHERE <search_condition>
```

Selecciona aquellas filas que cumplen la condición especificada por esta orden. La condición de búsqueda o de selección de registros se puede conformar utilizando columnas de la tabla, constantes, funciones y/o expresiones y operadores.

Los operadores más utilizados en las condiciones de selección son:

| Operador             	| Definición                                                  	|
|-----------------------|---------------------------------------------------------------|
| =, !=, <>            	| Igual a, distinto de, distinto de                           	|
| >, >=, <, <=         	| Mayor que, Mayor o igual que, menor que, menor o igual que  	|
| BETWEEN … AND …      	| Chequea un rango incluyendo los dos valores                 	|
| LIKE                 	| Compara una cadena de caracteres con un patrón o formato    	|
| IN ( ), NOT IN ( )   	| Comprueba que un campo o expresión tenga valores o no en un 	|
| conjunto de valores  	|                                                             	|
| IS NULL, IS NOT NULL 	| Comprueba que un campo o expresión sea nula o no            	|

# Operador BETWEEN:

Para indicar que deseamos recuperar los registros según el intervalo de valores de un campo emplearemos el operador BETWEEN cuya sintaxis es:

```sql
Columna o Expresión [Not] Between valor1 And valor2
```

en este caso la consulta devolvería los registros que contengan en columna o expresión un valor incluido en el intervalo valor1, valor2 (ambos inclusive). Si anteponemos el operador NOT devolverá aquellos valores no incluidos en el intervalo.

# Operador LIKE:

Este operador se utiliza para realizar comprobaciones de columnas o expresiones con patrones de caracteres. Su sintaxis es:

```sql
expresión_a_comparar [ NOT ] LIKE patrón
```

Los símbolos utilizados en el patrón son:

| %             | Cualquier cadena de cero o más caracteres. | WHERE title LIKE '%computer%' busca todos los títulos de libros que contengan la palabra 'computer' en cualquier parte del título. |
|---------------|--------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------|
| _ (subrayado) | Cualquier carácter individual              | WHERE au_fname LIKE '_ean' busca todos los nombres de cuatro letras que finalicen con ean (Dean, Sean, etc.).                      |

# Operador IN:

Se utiliza para comprobar si un valor pertenece a una lista de valores. Su sintaxis es:

```sql
expresion [ NOT ] IN ( subconsulta | expresion o valor [ ,...n ])
```

La lista de valores se puede obtener a partir de una setencia select o bien indicando el
 conjunto de valores separados por comas

# Operador IS NULL:

En SQL el valor nulo tiene un valor diferente a 0 y a cadena vacía. Por tanto, para preguntar
 si un atributo contiene, o no, un valor nulo, hay que utilizar el predicado IS [NOT] NULL.

# Siguiente tema

Siguiente Tema: Consulta de Datos. Cláusula GROUP BY


text:
from typing import Dict
from unittest import mock

from conductor.tests import TestCase
from conductor.vendor._google import GoogleGateway

@mock.patch("conductor.vendor._google.discovery")
class TestGoogleGateway(TestCase):
    def setup_mock_for_sheets(self, mock_discovery: mock.MagicMock) -> None:
        """Set up the mocks to pretend to be the discovery API.

        This is a maze.
        """
        response = mock.MagicMock()
        self.spreadsheets = mock.Mock()
        self.spreadsheets.create.return_value = response
        service = mock.Mock()
        service.spreadsheets.return_value = self.spreadsheets
        mock_discovery.build.return_value = service

    def get_create_data(self) -> Dict:
        """Get the data sent to create out of the mock."""
        return self.spreadsheets.create.call_args_list[0][1]["body"]

    def test_sheet_title(self, mock_discovery: mock.MagicMock) -> None:
        """Title contains the student name."""
        self.setup_mock_for_sheets(mock_discovery)
        student = self.StudentFactory.create()
        credentials = mock.Mock()
        gateway = GoogleGateway(credentials)

        gateway.generate_schedule(student)

        expected_title = "{} - Application Status".format(student)
        data = self.get_create_data()
        self.assertEqual(expected_title, data["properties"]["title"])


text:
namespace sudoku {
    template<int size>
    class QuickSolve : public SolveMethod<size>, Indexing<size> {
    public:
        QuickSolve(int maxSolnCount = 1);
        ~QuickSolve();

        int solve(AbstractBoard<size> &board);
        void set_max_soln_count(int count);

    private:
        int backtrack_solve(AbstractBoard<size> &board);
        int find_single(AbstractBoard<size> &board, cell_t &pos, bitmask_t &value);

    protected: // Make sure we can see imported symbols
        using Indexing<size>::BOX;
        using Indexing<size>::UNIT;
        using Indexing<size>::GRID;
        using Indexing<size>::MASK;
        using Indexing<size>::ref_for;
        using Indexing<size>::iterate;

    private:
        int maxSolnCount;
    };
}

#endif //CSUDOKU_QUICKSOLVE_H


text:
id: perf
title: Performance Tools
permalink: docs/perf.html
prev: pure-render-mixin.html
next: shallow-compare.html
---

React is usually quite fast out of the box. However, in situations where you need to squeeze every ounce of performance out of your app, it provides a [shouldComponentUpdate](/react/docs/component-specs.html#updating-shouldcomponentupdate) hook where you can add optimization hints to React's diff algorithm.

In addition to giving you an overview of your app's overall performance, ReactPerf is a profiling tool that tells you exactly where you need to put these hooks.

See these two articles by the [Benchling Engineering Team](http://benchling.engineering) for a in-depth introduction to performance tooling: ["Performance Engineering with React"](http://benchling.engineering/performance-engineering-with-react/) and ["A Deep Dive into React Perf Debugging"](http://benchling.engineering/deep-dive-react-perf-debugging/)!

## Development vs. Production Builds

If you're benchmarking or seeing performance problems in your React apps, make sure you're testing with the [minified production build](/react/downloads.html). The development build includes extra warnings that are helpful when building your apps, but it is slower due to the extra bookkeeping it does.

However, the perf tools described on this page only work when using the development build of React. Therefore, the profiler only serves to indicate the _relatively_ expensive parts of your app.

## General API

The `Perf` object documented here is exposed as `require('react-addons-perf')` and can be used with React in development mode only. You should not include this bundle when building your app for production.

### `Perf.start()` and `Perf.stop()`
Start/stop the measurement. The React operations in-between are recorded for analyses below. Operations that took an insignificant amount of time are ignored.

After stopping, you will need `Perf.getLastMeasurements()` (described below) to get the measurements.

### `Perf.printInclusive(measurements)`
Prints the overall time taken. If no argument's passed, defaults to all the measurements from the last recording. This prints a nicely formatted table in the console, like so:

![](/react/img/docs/perf-inclusive.png)

### `Perf.printExclusive(measurements)`
"Exclusive" times don't include the times taken to mount the components: processing props, `getInitialState`, call `componentWillMount` and `componentDidMount`, etc.

![](/react/img/docs/perf-exclusive.png)

### `Perf.printWasted(measurements)`

**The most useful part of the profiler**.

"Wasted" time is spent on components that didn't actually render anything, e.g. the render stayed the same, so the DOM wasn't touched.

![](/react/img/docs/perf-wasted.png)

### `Perf.printOperations(measurements)`
Prints the underlying DOM manipulations, e.g. "set innerHTML" and "remove".

![](/react/img/docs/perf-dom.png)

### `Perf.printDOM(measurements)`

This method has been renamed to `printOperations()` which is described in the previous paragraph. Currently `printDOM()` still exists as an alias but it prints a deprecation warning and will eventually be removed.

## Advanced API

The above print methods use `Perf.getLastMeasurements()` to pretty-print the result.

### `Perf.getLastMeasurements()`
Get the opaque data structure describing measurements from the last start-stop session. You can save it and pass it to the methods above to analyze past measurements.

Don't rely on the exact format of the return value because it may change in minor releases. We will update the documentation if the return value format becomes a supported part of the public API.


text:
{% extends "base.html" %}
{% load staticfiles %}

{% load i18n %}
{% load url from future %}

{% block head_title %}pinax-project-zero{% endblock %}

{% block body_class %}home{% endblock %}

{% block body_base %}

			 Create category
			 Refesh
			{% if object_list %}

								Category name
								Modify

							{% for q in object_list %}

									{{ q.value.name }}

							{% endfor %}

					{% if is_paginated %}

								{% if page_obj.has_previous %}
									previous
								{% endif %}

									Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.

								{% if page_obj.has_next %}
									next
								{% endif %}

					{% endif %}

			{% else %}

					There are not any category in list

			{% endif %}

{% endblock %}

{% block extra_script %}

{% endblock %}


text:
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using MOE.Common.Models.Repositories;

namespace MOE.Common.Models
{
    public partial class Approach
    {
        [NotMapped]
        public string Index { get; set; }

        [NotMapped]
        public string ApproachRouteDescription => Signal.SignalDescription + " " +
                                                  DirectionType.Description + " Phase " + ProtectedPhaseNumber;

        public List<Detector> GetAllDetectorsOfDetectionType(int detectionTypeID)
        {
            if (Detectors != null)
            {
                foreach (var d in Detectors)
                    if (d.DetectionTypeIDs == null)
                    {
                        d.DetectionTypeIDs = new List<int>();
                        foreach (var dt in d.DetectionTypes)
                            d.DetectionTypeIDs.Add(dt.DetectionTypeID);
                    }
                return Detectors
                    .Where(d => d.DetectionTypeIDs.Contains(detectionTypeID))
                    .ToList();
            }
            return new List<Detector>();
        }

        public bool Equals(Approach approachToCompare)
        {
            return CompareApproachProperties(approachToCompare);
        }

        private bool CompareApproachProperties(Approach approachToCompare)
        {
            if (approachToCompare != null
                && SignalID == approachToCompare.SignalID
                && ApproachID == approachToCompare.ApproachID
                && DirectionTypeID == approachToCompare.DirectionTypeID
                && Description == approachToCompare.Description
                && MPH == approachToCompare.MPH
                && Detectors == approachToCompare.Detectors
                && ProtectedPhaseNumber == approachToCompare.ProtectedPhaseNumber
                && IsProtectedPhaseOverlap == approachToCompare.IsProtectedPhaseOverlap
                && PermissivePhaseNumber == approachToCompare.PermissivePhaseNumber
                && PedestrianPhaseNumber == approachToCompare.PedestrianPhaseNumber
                && IsPedestrianPhaseOverlap == approachToCompare.IsPedestrianPhaseOverlap
                && PedestrianDetectors == approachToCompare.PedestrianDetectors
            )
                return true;
            return false;
        }

        public static Approach CreateNewApproachWithDefaultValues(Signal signal, DirectionType dir, SPM db)
        {
            var appr = new Approach();
            appr.Description = signal.SignalID + dir.Abbreviation;
            appr.DirectionTypeID = dir.DirectionTypeID;
            appr.SignalID = signal.SignalID;
            appr.MPH = 0;
            return appr;
        }

        public static void AddDefaultObjectsToApproach(Approach appr, SPM db)
        {
            var D = new Detector();

            var basic = (from r in db.DetectionTypes
                where r.DetectionTypeID == 1
                select r).FirstOrDefault();

            D.LaneTypeID = 1;
            D.MovementTypeID = 1;
            //D.Description = appr.Description + "Thru (Phase Only)";
            appr.Detectors.Add(D);

            //LeftTurn
            var D2 = new Detector();
            D2.LaneTypeID = 1;
            D2.MovementTypeID = 3;
            //LG2.Description = appr.Description + "Left (Phase Only)";
            appr.Detectors.Add(D2);
        }

        public static Approach CopyApproachCommonProperties(Approach approachToCopy, bool isVersionOrSignalCopy)
        {
            var newApproach = new Approach();
            newApproach.SignalID = approachToCopy.SignalID;
            newApproach.VersionID = approachToCopy.VersionID;
            newApproach.DirectionTypeID = approachToCopy.DirectionTypeID;
            if (!isVersionOrSignalCopy)
                newApproach.Description = approachToCopy.Description + " Copy";
            else
                newApproach.Description = approachToCopy.Description;
            newApproach.MPH = approachToCopy.MPH;
            newApproach.ProtectedPhaseNumber = approachToCopy.ProtectedPhaseNumber;
            newApproach.IsProtectedPhaseOverlap = approachToCopy.IsProtectedPhaseOverlap;
            newApproach.IsPermissivePhaseOverlap = approachToCopy.IsPermissivePhaseOverlap;
            newApproach.PermissivePhaseNumber = approachToCopy.PermissivePhaseNumber;
            newApproach.PedestrianPhaseNumber = approachToCopy.PedestrianPhaseNumber;
            newApproach.IsPedestrianPhaseOverlap = approachToCopy.IsPedestrianPhaseOverlap;
            newApproach.PedestrianDetectors = approachToCopy.PedestrianDetectors;
            newApproach.Detectors = new List<Detector>();
            return newApproach;
        }

        public static Approach CopyApproach(int approachIDToCopy)
        {
            var approachRepository =
                ApproachRepositoryFactory.Create();
            var approachToCopy = approachRepository.GetApproachByApproachID(approachIDToCopy);
            var newApproach = CopyApproachCommonProperties(approachToCopy, false);
            if (approachToCopy.Detectors != null)
            {
                foreach (var d in approachToCopy.Detectors)
                {
                    var
                        dForNewApproach =
                            Detector.CopyDetector(d.ID,
                                true); //need to increase DetChannel if not copying the whole signal.
                    newApproach.Detectors.Add(dForNewApproach);
                }
                if (newApproach.Detectors.Count > 1)
                    newApproach = SetDetChannelWhenMultipleDetectorsExist(newApproach);
            }
            return newApproach;
        }

        private static Approach SetDetChannelWhenMultipleDetectorsExist(Approach newApproach)
        {
            var detChannel = newApproach.Detectors.ToList()[0].DetChannel + 1;
            for (var i = 1; i < newApproach.Detectors.Count; i++)
            {
                newApproach.Detectors.ToList()[i].DetChannel = detChannel;
                newApproach.Detectors.ToList()[i].DetectorID = newApproach.SignalID +
                                                               detChannel;
                detChannel++;
            }
            return newApproach;
        }

        public static Approach CopyApproachForSignal(Approach approachToCopy)
        {
            var newApproach = CopyApproachCommonProperties(approachToCopy, true);
            foreach (var d in approachToCopy.Detectors)
            {
                var dForNewApproach = Detector.CopyDetector(d.ID, false);
                newApproach.Detectors.Add(dForNewApproach);
            }
            return newApproach;
        }

        public List<Detector> GetDetectorsForMetricType(int metricTypeID)
        {
            var detectorsForMetricType = new List<Detector>();
            if (Detectors != null)
            {
                foreach (var d in Detectors)
                {
                    if (d.DetectorSupportsThisMetric(metricTypeID))
                    {
                        detectorsForMetricType.Add(d);
                    }
                }
            }
            return detectorsForMetricType;
        }
    }
}


text: Small, simple maps that connects to the cids system and can be embedded in CMS


text:
<?php

namespace Majora\Framework\Model;

/**
 * Interface for enable / disable models
 */
interface EnablableInterface
{
    /**
     * enable entity
     *
     * @return self
     */
    public function enable();

    /**
     * disable entity
     *
     * @return self
     */
    public function disable();

    /**
     * tests if entity is enabled
     *
     * @return boolean
     */
    public function isEnabled();
}


text:
.styleSans86.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 86.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans11.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 11.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans10.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 10.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans28.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 28.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans9.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 9.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans18.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 18.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans186.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 186.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans522.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 522.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans15.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 15.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 7.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans41.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 41.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans12.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 12.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans5.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 5.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans49.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 49.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 8.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans23.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 23.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans1.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 1.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans725.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 725.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans726.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 726.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans727.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 727.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}


text:
package es.ucm.fdi.iw.validation;

import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import javax.validation.constraints.Digits;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.format.annotation.DateTimeFormat;

public class StockForm {

	@NotEmpty(message = Patrones.menVacio)
	private String medicamento;
	@NotNull(message = Patrones.menVacio)
	@Min(value = 0)
	@Max(value = 1000)
	@Digits(message = Patrones.menNumero, fraction = 0, integer = 1000)
	private int cantidad;
	@NotEmpty(message = Patrones.menVacio)
	@DateTimeFormat(pattern="MM/dd/yyyy")
	private String fechaCaducidad;
	public String getMedicamento() {
		return medicamento;
	}
	public void setMedicamento(String medicamento) {
		this.medicamento = medicamento;
	}
	public int getCantidad() {
		return cantidad;
	}
	public void setCantidad(int cantidad) {
		this.cantidad = cantidad;
	}
	public String getFechaCaducidad() {
		return fechaCaducidad;
	}
	public void setFechaCaducidad(String fechaCaducidad) {
		this.fechaCaducidad = fechaCaducidad;
	}
	public Date getFechaFormateada() {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

		try {
			return new Date(format.parse(this.fechaCaducidad).getTime());
		} catch (ParseException e) {
			e.printStackTrace();
		}

		return null;
	}
}


text:
/* global Polymer */
'use strict';

// MODULES //

var Print = require( './print.js' );

// POLYMER //

Polymer( 'polymer-print', Print.prototype );


text:
<?php

use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = array(
            new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
            new Symfony\Bundle\SecurityBundle\SecurityBundle(),
            new Symfony\Bundle\TwigBundle\TwigBundle(),
            new Symfony\Bundle\MonologBundle\MonologBundle(),
            new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
            new Symfony\Bundle\AsseticBundle\AsseticBundle(),
            new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
            new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
            new Omea\BusinessSocleBundle\OmeaBusinessSocleBundle(),
            new SoapClientBundle\SoapClientBundle(),
            new Omea\GestionTelco\PatesBundle\OmeaGestionTelcoPatesBundle(),
            new Omea\GestionTelco\SfrLightMvnoBundle\SfrLightMvnoBundle(),
            new Omea\GestionTelco\EvenementsBundle\OmeaGestionTelcoEvenementsBundle(),
        );

        if (in_array($this->getEnvironment(), array('dev', 'test'))) {
            $bundles[] = new Symfony\Bundle\DebugBundle\DebugBundle();
            $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
            $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
            $bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
            $bundles[] = new h4cc\AliceFixturesBundle\h4ccAliceFixturesBundle();
        }

        return $bundles;
    }

    public function registerContainerConfiguration(LoaderInterface $loader)
    {
        $loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml');
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="content-type" content="text/html; charset=utf-8" >
<title>Warsaw 2015
 - Program</title>
<meta name="author" content="" >

<link rel="alternate" type="application/rss+xml" title="devopsdays RSS Feed" href="http://www.devopsdays.org/feed/" >

<link rel="stylesheet" href="/css/devops.min.css" type="text/css" media="screen, projection">
<link rel="stylesheet" href="/css/blueprint/print.css" type="text/css" media="print">

      Home

      Contact

      Events

      Presentations

      Blog

Warsaw 2015
 - Program

Gold partners

    Welcome
    Location
    Register
    Program
    Ignites
    Partners
    Contact
    Code of Conduct

  Conference program is already published on our website. Also feel free to check out our speakers.

Main Partner

Platinum Partner

Gold Partner

Regeneration Zone Partner

Sponsor

Partners

   Become one!