text:
<?php

/**
 * This is a utility class for holding criteria information for a query.
 *
 * BasePeer constructs SQL statements based on the values in this class.
 *
 * @author     Hans Lellelid <hans@xmpl.org> (Propel)
 * @author     Kaspars Jaudzems <kaspars.jaudzems@inbox.lv> (Propel)
 * @author     Frank Y. Kim <frank.kim@clearink.com> (Torque)
 * @author     John D. McNally <jmcnally@collab.net> (Torque)
 * @author     Brett McLaughlin <bmclaugh@algx.net> (Torque)
 * @author     Eric Dobbs <eric@dobbse.net> (Torque)
 * @author     Henning P. Schmiedehausen <hps@intermeta.de> (Torque)
 * @author     Sam Joseph <sam@neurogrid.com> (Torque)
 * @version    $Revision: 1262 $
 * @package    propel.util
 */
class Criteria implements IteratorAggregate {

	/** Comparison type. */
	const EQUAL = "=";

	/** Comparison type. */
	const NOT_EQUAL = "<>";

	/** Comparison type. */
	const ALT_NOT_EQUAL = "!=";

	/** Comparison type. */
	const GREATER_THAN = ">";

	/** Comparison type. */
	const LESS_THAN = "<";

	/** Comparison type. */
	const GREATER_EQUAL = ">=";

	/** Comparison type. */
	const LESS_EQUAL = "<=";

	/** Comparison type. */
	const LIKE = " LIKE ";

	/** Comparison type. */
	const NOT_LIKE = " NOT LIKE ";

	/** PostgreSQL comparison type */
	const ILIKE = " ILIKE ";

	/** PostgreSQL comparison type */
	const NOT_ILIKE = " NOT ILIKE ";

	/** Comparison type. */
	const CUSTOM = "CUSTOM";

	/** Comparison type for update */
	const CUSTOM_EQUAL = "CUSTOM_EQUAL";

	/** Comparison type. */
	const DISTINCT = "DISTINCT ";

	/** Comparison type. */
	const IN = " IN ";

	/** Comparison type. */
	const NOT_IN = " NOT IN ";

	/** Comparison type. */
	const ALL = "ALL ";

	/** Comparison type. */
	const JOIN = "JOIN";

	/** Binary math operator: AND */
	const BINARY_AND = "&";

	/** Binary math operator: OR */
	const BINARY_OR = "|";

	/** "Order by" qualifier - ascending */
	const ASC = "ASC";

	/** "Order by" qualifier - descending */
	const DESC = "DESC";

	/** "IS NULL" null comparison */
	const ISNULL = " IS NULL ";

	/** "IS NOT NULL" null comparison */
	const ISNOTNULL = " IS NOT NULL ";

	/** "CURRENT_DATE" ANSI SQL function */
	const CURRENT_DATE = "CURRENT_DATE";

	/** "CURRENT_TIME" ANSI SQL function */
	const CURRENT_TIME = "CURRENT_TIME";

	/** "CURRENT_TIMESTAMP" ANSI SQL function */
	const CURRENT_TIMESTAMP = "CURRENT_TIMESTAMP";

	/** "LEFT JOIN" SQL statement */
	const LEFT_JOIN = "LEFT JOIN";

	/** "RIGHT JOIN" SQL statement */
	const RIGHT_JOIN = "RIGHT JOIN";

	/** "INNER JOIN" SQL statement */
	const INNER_JOIN = "INNER JOIN";

	private $ignoreCase = false;
	private $singleRecord = false;
	private $selectModifiers = array();
	private $selectColumns = array();
	private $orderByColumns = array();
	private $groupByColumns = array();
	private $having = null;
	private $asColumns = array();
	private $joins = array();

	/** The name of the database. */
	private $dbName;

	/**
	 * The primary table for this Criteria.
	 * Useful in cases where there are no select or where
	 * columns.
	 * @var        string
	 */
	private $primaryTableName;

	/** The name of the database as given in the contructor. */
	private $originalDbName;

	/**
	 * To limit the number of rows to return.  0 means return all
	 * rows.
	 */
	private $limit = 0;

	/** To start the results at a row other than the first one. */
	private $offset = 0;

	// flag to note that the criteria involves a blob.
	private $blobFlag = null;

	private $aliases = array();

	private $useTransaction = false;

	/**
	 * Primary storage of criteria data.
	 * @var        array
	 */
	private $map = array();

	/**
	 * Creates a new instance with the default capacity which corresponds to
	 * the specified database.
	 *
	 * @param      dbName The dabase name.
	 */
	public function __construct($dbName = null)
	{
		$this->setDbName($dbName);
		$this->originalDbName = $dbName;
	}

	/**
	 * Implementing SPL IteratorAggregate interface.  This allows
	 * you to foreach () over a Criteria object.
	 */
	public function getIterator()
	{
		return new CriterionIterator($this);
	}

	/**
	 * Get the criteria map.
	 * @return     array
	 */
	public function getMap()
	{
		return $this->map;
	}

	/**
	 * Brings this criteria back to its initial state, so that it
	 * can be reused as if it was new. Except if the criteria has grown in
	 * capacity, it is left at the current capacity.
	 * @return     void
	 */
	public function clear()
	{
		$this->map = array();
		$this->ignoreCase = false;
		$this->singleRecord = false;
		$this->selectModifiers = array();
		$this->selectColumns = array();
		$this->orderByColumns = array();
		$this->groupByColumns = array();
		$this->having = null;
		$this->asColumns = array();
		$this->joins = array();
		$this->dbName = $this->originalDbName;
		$this->offset = 0;
		$this->limit = -1;
		$this->blobFlag = null;
		$this->aliases = array();
		$this->useTransaction = false;
	}

	/**
	 * Add an AS clause to the select columns. Usage:
	 *
	 *
	 * Criteria myCrit = new Criteria();
	 * myCrit->addAsColumn("alias", "ALIAS(".MyPeer::ID.")");
	 *
	 *
	 * @param      string $name Wanted Name of the column (alias).
	 * @param      string $clause SQL clause to select from the table
	 *
	 * If the name already exists, it is replaced by the new clause.
	 *
	 * @return     Criteria A modified Criteria object.
	 */
	public function addAsColumn($name, $clause)
	{
		$this->asColumns[$name] = $clause;
		return $this;
	}

	/**
	 * Get the column aliases.
	 *
	 * @return     array An assoc array which map the column alias names
	 * to the alias clauses.
	 */
	public function getAsColumns()
	{
		return $this->asColumns;
	}

		/**
	 * Returns the column name associated with an alias (AS-column).
	 *
	 * @param      string $alias
	 * @return     string $string
	 */
	public function getColumnForAs($as)
	{
		if (isset($this->asColumns[$as])) {
			return $this->asColumns[$as];
		}
	}

	/**
	 * Allows one to specify an alias for a table that can
	 * be used in various parts of the SQL.
	 *
	 * @param      string $alias
	 * @param      string $table
	 * @return     void
	 */
	public function addAlias($alias, $table)
	{
		$this->aliases[$alias] = $table;
	}

	/**
	 * Returns the table name associated with an alias.
	 *
	 * @param      string $alias
	 * @return     string $string
	 */
	public function getTableForAlias($alias)
	{
		if (isset($this->aliases[$alias])) {
			return $this->aliases[$alias];
		}
	}

	/**
	 * Get the keys for the criteria map.
	 * @return     array
	 */
	public function keys()
	{
		return array_keys($this->map);
	}

	/**
	 * Does this Criteria object contain the specified key?
	 *
	 * @param      string $column [table.]column
	 * @return     boolean True if this Criteria object contain the specified key.
	 */
	public function containsKey($column)
	{
		// must use array_key_exists() because the key could
		// exist but have a NULL value (that'd be valid).
		return array_key_exists($column, $this->map);
	}

	/**
	 * Does this Criteria object contain the specified key and does it have a value set for the key
	 *
	 * @param      string $column [table.]column
	 * @return     boolean True if this Criteria object contain the specified key and a value for that key
	 */
	public function keyContainsValue($column)
	{
		// must use array_key_exists() because the key could
		// exist but have a NULL value (that'd be valid).
		return (array_key_exists($column, $this->map) && ($this->map[$column]->getValue() !== null) );
	}

	/**
	 * Will force the sql represented by this criteria to be executed within
	 * a transaction.  This is here primarily to support the oid type in
	 * postgresql.  Though it can be used to require any single sql statement
	 * to use a transaction.
	 * @return     void
	 */
	public function setUseTransaction($v)
	{
		$this->useTransaction = (boolean) $v;
	}

	/**
	 * Whether the sql command specified by this criteria must be wrapped
	 * in a transaction.
	 *
	 * @return     boolean
	 */
	public function isUseTransaction()
	{
		return $this->useTransaction;
	}

	/**
	 * Method to return criteria related to columns in a table.
	 *
	 * @param      string $column Column name.
	 * @return     null|Criterion A Criterion or null if $column is invalid.
	 */
	public function getCriterion($column)
	{
		if ( isset ( $this->map[$column] ) ) {
			return $this->map[$column];
		}
		return null;
	}

	/**
	 * Method to return criterion that is not added automatically
	 * to this Criteria.  This can be used to chain the
	 * Criterions to form a more complex where clause.
	 *
	 * @param      string $column Full name of column (for example TABLE.COLUMN).
	 * @param      mixed $value
	 * @param      string $comparison
	 * @return     Criterion
	 */
	public function getNewCriterion($column, $value, $comparison = null)
	{
		return new Criterion($this, $column, $value, $comparison);
	}

	/**
	 * Method to return a String table name.
	 *
	 * @param      string $name Name of the key.
	 * @return     null|string The value of the object at key.
	 */
	public function getColumnName($name)
	{
		if (isset($this->map[$name])) {
			return $this->map[$name]->getColumn();
		}
		return null;
	}

	/**
	 * Shortcut method to get an array of columns indexed by table.
	 * @return     array array(table => array(table.column1, table.column2))
	 */
	public function getTablesColumns()
	{
		$tables = array();
		foreach ( array_keys ( $this->map ) as $key) {
			$t = substr ( $key, 0, strrpos ( $key, '.' ) );
			if ( ! isset ( $tables[$t] ) ) {
				$tables[$t] = array( $key );
			} else {
				$tables[$t][] = $key;
			}
		}
		return $tables;
	}

	/**
	 * Method to return a comparison String.
	 *
	 * @param      string $key String name of the key.
	 * @return     null|string A String with the value of the object at key.
	 */
	public function getComparison($key)
	{
		if ( isset ( $this->map[$key] ) ) {
			return $this->map[$key]->getComparison();
		}
		return null;
	}

	/**
	 * Get the Database(Map) name.
	 *
	 * @return     string A String with the Database(Map) name.
	 */
	public function getDbName()
	{
		return $this->dbName;
	}

	/**
	 * Set the DatabaseMap name.  If null is supplied, uses value
	 * provided by Propel::getDefaultDB().
	 *
	 * @param      string $dbName The Database (Map) name.
	 * @return     void
	 */
	public function setDbName($dbName = null)
	{
		$this->dbName = ($dbName === null ? Propel::getDefaultDB() : $dbName);
	}

	/**
	 * Get the primary table for this Criteria.
	 *
	 * This is useful for cases where a Criteria may not contain
	 * any SELECT columns or WHERE columns.  This must be explicitly
	 * set, of course, in order to be useful.
	 *
	 * @return     string
	 */
	public function getPrimaryTableName()
	{
		return $this->primaryTableName;
	}

	/**
	 * Sets the primary table for this Criteria.
	 *
	 * This is useful for cases where a Criteria may not contain
	 * any SELECT columns or WHERE columns.  This must be explicitly
	 * set, of course, in order to be useful.
	 *
	 * @param      string $v
	 */
	public function setPrimaryTableName($tableName)
	{
		$this->primaryTableName = $tableName;
	}

	/**
	 * Method to return a String table name.
	 *
	 * @param      string $name The name of the key.
	 * @return     null|string The value of table for criterion at key.
	 */
	public function getTableName($name)
	{
		if (isset($this->map[$name])) {
			return $this->map[$name]->getTable();
		}
		return null;
	}

	/**
	 * Method to return the value that was added to Criteria.
	 *
	 * @param      string $name A String with the name of the key.
	 * @return     mixed The value of object at key.
	 */
	public function getValue($name)
	{
		if (isset($this->map[$name])) {
			return $this->map[$name]->getValue();
		}
		return null;
	}

	/**
	 * An alias to getValue() -- exposing a Hashtable-like interface.
	 *
	 * @param      string $key An Object.
	 * @return     mixed The value within the Criterion (not the Criterion object).
	 */
	public function get($key)
	{
		return $this->getValue($key);
	}

	/**
	 * Overrides Hashtable put, so that this object is returned
	 * instead of the value previously in the Criteria object.
	 * The reason is so that it more closely matches the behavior
	 * of the add() methods. If you want to get the previous value
	 * then you should first Criteria.get() it yourself. Note, if
	 * you attempt to pass in an Object that is not a String, it will
	 * throw a NPE. The reason for this is that none of the add()
	 * methods support adding anything other than a String as a key.
	 *
	 * @param      string $key
	 * @param      mixed $value
	 * @return     Criteria Instance of self.
	 */
	public function put($key, $value)
	{
		return $this->add($key, $value);
	}

	/**
	 * Copies all of the mappings from the specified Map to this Criteria
	 * These mappings will replace any mappings that this Criteria had for any
	 * of the keys currently in the specified Map.
	 *
	 * if the map was another Criteria, its attributes are copied to this
	 * Criteria, overwriting previous settings.
	 *
	 * @param      mixed $t Mappings to be stored in this map.
	 */
	public function putAll($t)
	{

		if (is_array($t)) {

			foreach ($t as $key=>$value) {

				if ($value instanceof Criterion) {

					$this->map[$key] = $value;

				} else {

					$this->put($key, $value);

				}

			}

		} elseif ($t instanceof Criteria) {

			$this->joins = $t->joins;

		}

	}

	/**
	 * This method adds a new criterion to the list of criterias.
	 * If a criterion for the requested column already exists, it is
	 * replaced. If is used as follow:
	 *
	 *

	 *
	 * $crit = new Criteria();
	 * $crit->add("column",
	 *                                      "value"
	 *                                      "Criteria::GREATER_THAN");
	 *
	 *
	 * Any comparison can be used.
	 *
	 * The name of the table must be used implicitly in the column name,
	 * so the Column name must be something like 'TABLE.id'. If you
	 * don't like this, you can use the add(table, column, value) method.
	 *
	 * @param      string $critOrColumn The column to run the comparison on, or Criterion object.
	 * @param      int|string|float|null|bool|array<int>|array<string>|\DateTimeInterface $value
	 * @param      string $comparison A String.
	 *
	 * @return     Criteria A modified Criteria object.
	 */
	public function add($p1, $value = null, $comparison = null)
	{
		if ($p1 instanceof Criterion) {
			$this->map[$p1->getTable() . '.' . $p1->getColumn()] = $p1;
		} else {
			$this->map[$p1] = new Criterion($this, $p1, $value, $comparison);
		}
		return $this;
	}

	/**
	 * This is the way that you should add a straight (inner) join of two tables.  For
	 * example:
	 *
	 *

	 * AND PROJECT.PROJECT_ID=FOO.PROJECT_ID
	 *

	 *
	 * left = PROJECT.PROJECT_ID
	 * right = FOO.PROJECT_ID
	 *
	 * @param      mixed $left A String with the left side of the join.
	 * @param      mixed $right A String with the right side of the join.
	 * @param      mixed $operator A String with the join operator e.g. LEFT JOIN, ...
   *
	 * @return     Criteria A modified Criteria object.
	 */
	public function addJoin($left, $right, $operator = null)
	{
		$join = new Join();
    if (!is_array($left)) {
      // simple join
      $join->addCondition($left, $right);
    } else {
      // join with multiple conditions
      // deprecated: use addMultipleJoin() instead
      foreach ($left as $key => $value)
      {
        $join->addCondition($value, $right[$key]);
      }
    }
		$join->setJoinType($operator);

		return $this->addJoinObject($join);
	}

	/**
	 * Add a join with multiple conditions
	 * see http://propel.phpdb.org/trac/ticket/167, http://propel.phpdb.org/trac/ticket/606
	 *
	 * Example usage:
	 * $c->addMultipleJoin(array(
	 *     array(LeftPeer::LEFT_COLUMN, RightPeer::RIGHT_COLUMN),  // if no third argument, defaults to Criteria::EQUAL
	 *     array(FoldersPeer::alias( 'fo', FoldersPeer::LFT ), FoldersPeer::alias( 'parent', FoldersPeer::RGT ), Criteria::LESS_EQUAL )
	 *   ),
	 *   Criteria::LEFT_JOIN
 	 * );
	 *
	 * @see        addJoin()
	 * @param      array $conditions An array of conditions, each condition being an array (left, right, operator)
	 * @param      string $joinType  A String with the join operator. Defaults to an implicit join.
	 *
	 * @return     Criteria A modified Criteria object.
	 */
	public function addMultipleJoin($conditions, $joinType = null)
  {
		$join = new Join();
		foreach ($conditions as $condition) {
		  $join->addCondition($condition[0], $condition[1], isset($condition[2]) ? $condition[2] : Criteria::EQUAL);
		}
		$join->setJoinType($joinType);

		return $this->addJoinObject($join);
	}

	/**
	 * Add a join object to the Criteria
	 *
	 * @param Join $join A join object
	 *
	 * @return Criteria A modified Criteria object
	 */
	public function addJoinObject(Join $join)
	{
	  if (!in_array($join, $this->joins)) { // compare equality, NOT identity
			$this->joins[] = $join;
		}
		return $this;
	}

	/**
	 * Get the array of Joins.
	 * @return     Join[]
	 */
	public function getJoins()
	{
		return $this->joins;
	}

	/**
	 * Adds "ALL" modifier to the SQL statement.
	 * @return     Criteria Modified Criteria object (for fluent API)
	 */
	public function setAll()
	{
		$this->selectModifiers[] = self::ALL;
		return $this;
	}

	/**
	 * Adds "DISTINCT" modifier to the SQL statement.
	 * @return     Criteria Modified Criteria object (for fluent API)
	 */
	public function setDistinct()
	{
		$this->selectModifiers[] = self::DISTINCT;
		return $this;
	}

	/**
	 * Sets ignore case.
	 *
	 * @param      boolean $b True if case should be ignored.
	 * @return     Criteria Modified Criteria object (for fluent API)
	 */
	public function setIgnoreCase($b)
	{
		$this->ignoreCase = (boolean) $b;
		return $this;
	}

	/**
	 * Is ignore case on or off?
	 *
	 * @return     boolean True if case is ignored.
	 */
	public function isIgnoreCase()
	{
		return $this->ignoreCase;
	}

	/**
	 * Set single record?  Set this to true if you expect the query
	 * to result in only a single result record (the default behaviour is to
	 * throw a PropelException if multiple records are returned when the query
	 * is executed).  This should be used in situations where returning multiple
	 * rows would indicate an error of some sort.  If your query might return
	 * multiple records but you are only interested in the first one then you
	 * should be using setLimit(1).
	 *
	 * @param      boolean $b Set to TRUE if you expect the query to select just one record.
	 * @return     Criteria Modified Criteria object (for fluent API)
	 */
	public function setSingleRecord($b)
	{
		$this->singleRecord = (boolean) $b;
		return $this;
	}

	/**
	 * Is single record?
	 *
	 * @return     boolean True if a single record is being returned.
	 */
	public function isSingleRecord()
	{
		return $this->singleRecord;
	}

	/**
	 * Set limit.
	 *
	 * @param      limit An int with the value for limit.
	 * @return     Criteria Modified Criteria object (for fluent API)
	 */
	public function setLimit($limit)
	{
		// TODO: do we enforce int here? 32bit issue if we do
		$this->limit = $limit;
		return $this;
	}

	/**
	 * Get limit.
	 *
	 * @return     int An int with the value for limit.
	 */
	public function getLimit()
	{
		return $this->limit;
	}

	/**
	 * Set offset.
	 *
	 * @param      int $offset An int with the value for offset.  (Note this values is
	 * 							cast to a 32bit integer and may result in truncatation)
	 * @return     Criteria Modified Criteria object (for fluent API)
	 */
	public function setOffset($offset)
	{
		$this->offset = (int) $offset;
		return $this;
	}

	/**
	 * Get offset.
	 *
	 * @return     int An int with the value for offset.
	 */
	public function getOffset()
	{
		return $this->offset;
	}

	/**
	 * Add select column.
	 *
	 * @param      string $name Name of the select column.
	 * @return     Criteria Modified Criteria object (for fluent API)
	 */
	public function addSelectColumn($name)
	{
		$this->selectColumns[] = $name;
		return $this;
	}

	/**
	 * Whether this Criteria has any select columns.
	 *
	 * This will include columns added with addAsColumn() method.
	 *
	 * @return     boolean
	 * @see        addAsColumn()
	 * @see        addSelectColumn()
	 */
	public function hasSelectClause()
	{
		return (!empty($this->selectColumns) || !empty($this->asColumns));
	}

	/**
	 * Get select columns.
	 *
	 * @return     array An array with the name of the select
	 * columns.
	 */
	public function getSelectColumns()
	{
		return $this->selectColumns;
	}

	/**
	 * Clears current select columns.
	 *
	 * @return     Criteria Modified Criteria object (for fluent API)
	 */
	public function clearSelectColumns() {
		$this->selectColumns = $this->asColumns = array();
		return $this;
	}

	/**
	 * Get select modifiers.
	 *
	 * @return     array An array with the select modifiers.
	 */
	public function getSelectModifiers()
	{
		return $this->selectModifiers;
	}

	/**
	 * Add group by column name.
	 *
	 * @param      string $groupBy The name of the column to group by.
	 * @return     Criteria A modified Criteria object.
	 */
	public function addGroupByColumn($groupBy)
	{
		$this->groupByColumns[] = $groupBy;
		return $this;
	}

	/**
	 * Add order by column name, explicitly specifying ascending.
	 *
	 * @param      name The name of the column to order by.
	 * @return     Criteria A modified Criteria object.
	 */
	public function addAscendingOrderByColumn($name)
	{
		$this->orderByColumns[] = $name . ' ' . self::ASC;
		return $this;
	}

	/**
	 * Add order by column name, explicitly specifying descending.
	 *
	 * @param      string $name The name of the column to order by.
	 * @return     Criteria Modified Criteria object (for fluent API)
	 */
	public function addDescendingOrderByColumn($name)
	{
		$this->orderByColumns[] = $name . ' ' . self::DESC;
		return $this;
	}

	/**
	 * Get order by columns.
	 *
	 * @return     array An array with the name of the order columns.
	 */
	public function getOrderByColumns()
	{
		return $this->orderByColumns;
	}

	/**
	 * Clear the order-by columns.
	 *
	 * @return     Criteria Modified Criteria object (for fluent API)
	 */
	public function clearOrderByColumns()
	{
		$this->orderByColumns = array();
		return $this;
	}

	/**
	 * Clear the group-by columns.
	 *
	 * @return     Criteria
	 */
	public function clearGroupByColumns()
	{
		$this->groupByColumns = array();
		return $this;
	}

	/**
	 * Get group by columns.
	 *
	 * @return     array
	 */
	public function getGroupByColumns()
	{
		return $this->groupByColumns;
	}

	/**
	 * Get Having Criterion.
	 *
	 * @return     Criterion A Criterion object that is the having clause.
	 */
	public function getHaving()
	{
		return $this->having;
	}

	/**
	 * Remove an object from the criteria.
	 *
	 * @param      string $key A string with the key to be removed.
	 * @return     mixed The removed value.
	 */
	public function remove($key)
	{
		if ( isset ( $this->map[$key] ) ) {
			$removed = $this->map[$key];
			unset ( $this->map[$key] );
			if ( $removed instanceof Criterion ) {
				return $removed->getValue();
			}
			return $removed;
		}
	}

	/**
	 * Build a string representation of the Criteria.
	 *
	 * @return     string A String with the representation of the Criteria.
	 */
	public function toString()
	{

		$sb = "Criteria:";
		try {

			$params = array();
			$sb .= "\nSQL (may not be complete): "
			  . BasePeer::createSelectSql($this, $params);

			$sb .= "\nParams: ";
			$paramstr = array();
			foreach ($params as $param) {
				$paramstr[] = $param['table'] . '.' . $param['column'] . ' => ' . var_export($param['value'], true);
			}
			$sb .= implode(", ", $paramstr);

		} catch (Exception $exc) {
			$sb .= "(Error: " . $exc->getMessage() . ")";
		}

		return $sb;
	}

	/**
	 * Returns the size (count) of this criteria.
	 * @return     int
	 */
	public function size()
	{
		return count($this->map);
	}

	/**
	 * This method checks another Criteria to see if they contain
	 * the same attributes and hashtable entries.
	 * @return     boolean
	 */
	public function equals($crit)
	{
		$isEquiv = false;
		if ($crit === null || !($crit instanceof Criteria)) {
			$isEquiv = false;
		} elseif ($this === $crit) {
			$isEquiv = true;
		} elseif ($this->size() === $crit->size()) {

			// Important: nested criterion objects are checked

			$criteria = $crit; // alias
			if ($this->offset === $criteria->getOffset()
				&& $this->limit === $criteria->getLimit()
				&& $this->ignoreCase === $criteria->isIgnoreCase()
				&& $this->singleRecord === $criteria->isSingleRecord()
				&& $this->dbName === $criteria->getDbName()
				&& $this->selectModifiers === $criteria->getSelectModifiers()
				&& $this->selectColumns === $criteria->getSelectColumns()
				&& $this->orderByColumns === $criteria->getOrderByColumns()
				&& $this->groupByColumns === $criteria->getGroupByColumns()
			   )
			{
				$isEquiv = true;
				foreach ($criteria->keys() as $key) {
					if ($this->containsKey($key)) {
						$a = $this->getCriterion($key);
						$b = $criteria->getCriterion($key);
						if (!$a->equals($b)) {
							$isEquiv = false;
							break;
						}
					} else {
						$isEquiv = false;
						break;
					}
				}
			}
		}
		return $isEquiv;
	}

	/**
	 * This method adds a prepared Criterion object to the Criteria as a having clause.
	 * You can get a new, empty Criterion object with the
	 * getNewCriterion() method.
	 *
	 *

	 *
	 * $crit = new Criteria();
	 * $c = $crit->getNewCriterion(BasePeer::ID, 5, Criteria::LESS_THAN);
	 * $crit->addHaving($c);
	 *
	 *
	 * @param      having A Criterion object
	 *
	 * @return     Criteria A modified Criteria object.
	 */
	public function addHaving(Criterion $having)
	{
		$this->having = $having;
		return $this;
	}

	/**
	 * This method adds a new criterion to the list of criterias.
	 * If a criterion for the requested column already exists, it is
	 * "AND"ed to the existing criterion.
	  *
	 * addAnd(column, value, comparison)
	 *
	 * $crit = $orig_crit->addAnd("column",
	 *                                      "value"
	 *                                      "Criterion::GREATER_THAN");
	 *
	 *
	 * addAnd(column, value)
	 *
	 * $crit = $orig_crit->addAnd("column", "value");
	 *
	 *
	 * addAnd(Criterion)
	 *
	 * $crit = new Criteria();
	 * $c = $crit->getNewCriterion(BasePeer::ID, 5, Criteria::LESS_THAN);
	 * $crit->addAnd($c);
	 *
	 *
	 * Any comparison can be used, of course.
	 *
	 *
	 * @return     Criteria A modified Criteria object.
	 */
	public function addAnd($p1, $p2 = null, $p3 = null)
	{
		if ($p3 !== null) {
			// addAnd(column, value, comparison)
			$oc = $this->getCriterion($p1);
			$nc = new Criterion($this, $p1, $p2, $p3);
			if ( $oc === null) {
				$this->map[$p1] = $nc;
			} else {
				$oc->addAnd($nc);
			}
		} elseif ($p2 !== null) {
			// addAnd(column, value)
			$this->addAnd($p1, $p2, self::EQUAL);
		} elseif ($p1 instanceof Criterion) {
			// addAnd(Criterion)
			$oc = $this->getCriterion($p1->getTable() . '.' . $p1->getColumn());
			if ($oc === null) {
				$this->add($p1);
			} else {
				$oc->addAnd($p1);
			}
		} elseif ($p2 === null && $p3 === null) {
			// client has not specified $p3 (comparison)
			// which means Criteria::EQUAL but has also specified $p2 == null
			// which is a valid combination we should handle by creating "IS NULL"
			$this->addAnd($p1, $p2, self::EQUAL);
		}
		return $this;
	}

	/**
	 * This method adds a new criterion to the list of criterias.
	 * If a criterion for the requested column already exists, it is
	 * "OR"ed to the existing criterion.
	 *
	 * Any comparison can be used.
	 *
	 * Supports a number of different signatures:
	 *
	 * addOr(column, value, comparison)
	 *
	 * $crit = $orig_crit->addOr("column",
	 *                                      "value"
	 *                                      "Criterion::GREATER_THAN");
	 *
	 *
	 * addOr(column, value)
	 *
	 * $crit = $orig_crit->addOr("column", "value");
	 *
	 *
	 * addOr(Criterion)
	 *
	 * @return     Criteria A modified Criteria object.
	 */
	public function addOr($p1, $p2 = null, $p3 = null)
	{
		if ($p3 !== null) {
			// addOr(column, value, comparison)
			$nc = new Criterion($this, $p1, $p2, $p3);
			$oc = $this->getCriterion($p1);
			if ($oc === null) {
				$this->map[$p1] = $nc;
			} else {
				$oc->addOr($nc);
			}
		} elseif ($p2 !== null) {
			// addOr(column, value)
			$this->addOr($p1, $p2, self::EQUAL);
		} elseif ($p1 instanceof Criterion) {
			// addOr(Criterion)
			$oc = $this->getCriterion($p1->getTable() . '.' . $p1->getColumn());
			if ($oc === null) {
				$this->add($p1);
			} else {
				$oc->addOr($p1);
			}
		} elseif ($p2 === null && $p3 === null) {
			// client has not specified $p3 (comparison)
			// which means Criteria::EQUAL but has also specified $p2 == null
			// which is a valid combination we should handle by creating "IS NULL"
			$this->addOr($p1, $p2, self::EQUAL);
		}

		return $this;
	}
}

// --------------------------------------------------------------------
// Criterion Iterator class -- allows foreach ($criteria as $criterion)
// --------------------------------------------------------------------

/**
 * Class that implements SPL Iterator interface.  This allows foreach () to
 * be used w/ Criteria objects.  Probably there is no performance advantage
 * to doing it this way, but it makes sense -- and simpler code.
 *
 * @author     Hans Lellelid <hans@xmpl.org>
 * @package    propel.util
 */
class CriterionIterator implements Iterator {

	private $idx = 0;
	private $criteria;
	private $criteriaKeys;
	private $criteriaSize;

	public function __construct(Criteria $criteria) {
		$this->criteria = $criteria;
		$this->criteriaKeys = $criteria->keys();
		$this->criteriaSize = count($this->criteriaKeys);
	}

	public function rewind() {
		$this->idx = 0;
	}

	public function valid() {
		return $this->idx < $this->criteriaSize;
	}

	public function key() {
		return $this->criteriaKeys[$this->idx];
	}

	public function current() {
		return $this->criteria->getCriterion($this->criteriaKeys[$this->idx]);
	}

	public function next() {
		$this->idx++;
	}

}

// --------------------------------------------------------------------
// Criterion "inner" class
// --------------------------------------------------------------------

/**
 * This is an "inner" class that describes an object in the criteria.
 *
 * In Torque this is an inner class of the Criteria class.
 *
 * @author     Hans Lellelid <hans@xmpl.org> (Propel)
 * @package    propel.util
 */
class Criterion  {

	const UND = " AND ";
	const ODER = " OR ";

	/** Value of the CO. */
	private $value;

	/** Comparison value.
	 * @var        SqlEnum
	 */
	private $comparison;

	/** Table name. */
	private $table;

	/** Real table name */
	private $realtable;

	/** Column name. */
	private $column;

	/** flag to ignore case in comparision */
	private $ignoreStringCase = false;

	/**
	 * The DBAdaptor which might be used to get db specific
	 * variations of sql.
	 */
	private $db;

	/**
	 * other connected criteria and their conjunctions.
	 */
	private $clauses = array();
	private $conjunctions = array();

	/** "Parent" Criteria class */
	private $parent;

	/**
	 * Create a new instance.
	 *
	 * @param      Criteria $parent The outer class (this is an "inner" class).
	 * @param      string $column TABLE.COLUMN format.
	 * @param      mixed $value
	 * @param      string $comparison
	 */
	public function __construct(Criteria $outer, $column, $value, $comparison = null)
	{
		$this->value = $value;
		$dotPos = strrpos($column,'.');
		if ($dotPos === false) {
			// no dot => aliased column
			$this->table = null;
			$this->column = $column;
		} else {
			$this->table = substr($column, 0, $dotPos);
			$this->column = substr($column, $dotPos+1, strlen($column));
		}
		$this->comparison = ($comparison === null ? Criteria::EQUAL : $comparison);
		$this->init($outer);
	}

	/**
	* Init some properties with the help of outer class
	* @param      Criteria $criteria The outer class
	*/
	public function init(Criteria $criteria)
	{
		//init $this->db
		try {
			$db = Propel::getDB($criteria->getDbName());
			$this->setDB($db);
		} catch (Exception $e) {
			// we are only doing this to allow easier debugging, so
			// no need to throw up the exception, just make note of it.
			Propel::log("Could not get a DBAdapter, sql may be wrong", Propel::LOG_ERR);
		}

		//init $this->realtable
		$realtable = $criteria->getTableForAlias($this->table);
		if (! strlen ( $realtable ) ) {
			$realtable = $this->table;
		}
		$this->realtable = $realtable;

	}

	/**
	 * Get the column name.
	 *
	 * @return     string A String with the column name.
	 */
	public function getColumn()
	{
		return $this->column;
	}

	/**
	 * Set the table name.
	 *
	 * @param      name A String with the table name.
	 * @return     void
	 */
	public function setTable($name)
	{
		$this->table = $name;
	}

	/**
	 * Get the table name.
	 *
	 * @return     string A String with the table name.
	 */
	public function getTable()
	{
		return $this->table;
	}

	/**
	 * Get the comparison.
	 *
	 * @return     string A String with the comparison.
	 */
	public function getComparison()
	{
		return $this->comparison;
	}

	/**
	 * Get the value.
	 *
	 * @return     mixed An Object with the value.
	 */
	public function getValue()
	{
		return $this->value;
	}

	/**
	 * Get the value of db.
	 * The DBAdapter which might be used to get db specific
	 * variations of sql.
	 * @return     DBAdapter value of db.
	 */
	public function getDB()
	{
		return $this->db;
	}

	/**
	 * Set the value of db.
	 * The DBAdapter might be used to get db specific variations of sql.
	 * @param      DBAdapter $v Value to assign to db.
	 * @return     void
	 */
	public function setDB(DBAdapter $v)
	{
		$this->db = $v;
		foreach ( $this->clauses as $clause ) {
			$clause->setDB($v);
		}
	}

	/**
	 * Sets ignore case.
	 *
	 * @param      boolean $b True if case should be ignored.
	 * @return     Criterion A modified Criterion object.
	 */
	public function setIgnoreCase($b)
	{
		$this->ignoreStringCase = (boolean) $b;
		return $this;
	}

	/**
	 * Is ignore case on or off?
	 *
	 * @return     boolean True if case is ignored.
	 */
	 public function isIgnoreCase()
	 {
		 return $this->ignoreStringCase;
	 }

	/**
	 * Get the list of clauses in this Criterion.
	 * @return     array
	 */
	private function getClauses()
	{
		return $this->clauses;
	}

	/**
	 * Get the list of conjunctions in this Criterion
	 * @return     array
	 */
	public function getConjunctions()
	{
		return $this->conjunctions;
	}

	/**
	 * Append an AND Criterion onto this Criterion's list.
	 */
	public function addAnd(Criterion $criterion)
	{
		$this->clauses[] = $criterion;
		$this->conjunctions[] = self::UND;
		return $this;
	}

	/**
	 * Append an OR Criterion onto this Criterion's list.
	 * @return     Criterion
	 */
	public function addOr(Criterion $criterion)
	{
		$this->clauses[] = $criterion;
		$this->conjunctions[] = self::ODER;
		return $this;
	}

	/**
	 * Appends a Prepared Statement representation of the Criterion
	 * onto the buffer.
	 *
	 * @param      string &$sb The string that will receive the Prepared Statement
	 * @param      array $params A list to which Prepared Statement parameters
	 * will be appended
	 * @return     void
	 * @throws     PropelException - if the expression builder cannot figure out how to turn a specified
	 *                           expression into proper SQL.
	 */
	public function appendPsTo(&$sb, array &$params)
	{
		if ($this->column === null) {
			return;
		}

		$db = $this->getDb();
		$sb .= str_repeat ( '(', count($this->clauses) );

		if (Criteria::CUSTOM === $this->comparison) {
			if ($this->value !== "") {
				$sb .= (string) $this->value;
			}
		} else {

			if  ($this->table === null) {
				$field = "`{$this->column}`";
			} else {
				$field = "`{$this->table}`.`{$this->column}`";
			}

			// Check to see if table is an alias & store real name, if so
			// (real table name is needed for the returned $params array)
			$realtable = $this->realtable;

			// There are several different types of expressions that need individual handling:
			// IN/NOT IN, LIKE/NOT LIKE, and traditional expressions.

			// OPTION 1:  table.column IN (?, ?) or table.column NOT IN (?, ?)
			if ($this->comparison === Criteria::IN || $this->comparison === Criteria::NOT_IN) {

				$_bindParams = array(); // the param names used in query building
				$_idxstart = count($params);
				$valuesLength = 0;
				foreach ( (array) $this->value as $value ) {
					$valuesLength++; // increment this first to correct for wanting bind params to start with :p1
					$params[] = array('table' => $realtable, 'column' => $this->column, 'value' => $value);
					$_bindParams[] = ':p'.($_idxstart + $valuesLength);
				}
				if ( $valuesLength !== 0 ) {
					$sb .= $field . $this->comparison . '(' . implode(',', $_bindParams) . ')';
				} else {
					$sb .= ($this->comparison === Criteria::IN) ? "1<>1" : "1=1";
				}
				unset ( $value, $valuesLength );

			// OPTION 2:  table.column LIKE ? or table.column NOT LIKE ?  (or ILIKE for Postgres)
			} elseif ($this->comparison === Criteria::LIKE || $this->comparison === Criteria::NOT_LIKE
				|| $this->comparison === Criteria::ILIKE || $this->comparison === Criteria::NOT_ILIKE) {
				// Handle LIKE, NOT LIKE (and related ILIKE, NOT ILIKE for Postgres)

				// If selection is case insensitive use ILIKE for PostgreSQL or SQL
				// UPPER() function on column name for other databases.
				if ($this->ignoreStringCase) {
					if ($db instanceof DBPostgres) {
						if ($this->comparison === Criteria::LIKE) {
							$this->comparison = Criteria::ILIKE;
						} elseif ($this->comparison === Criteria::NOT_LIKE) {
							$this->comparison = Criteria::NOT_ILIKE;
						}
					} else {
						$field = $db->ignoreCase($field);
					}
				}

				$params[] = array('table' => $realtable, 'column' => $this->column, 'value' => $this->value);

				$sb .= $field . $this->comparison;

				// If selection is case insensitive use SQL UPPER() function
				// on criteria or, if Postgres we are using ILIKE, so not necessary.
				if ($this->ignoreStringCase && !($db instanceof DBPostgres)) {
					$sb .= $db->ignoreCase(':p'.count($params));
				} else {
					$sb .= ':p'.count($params);
				}

			// OPTION 3:  table.column = ? or table.column >= ? etc. (traditional expressions, the default)
			} else {

				// NULL VALUES need special treatment because the SQL syntax is different
				// i.e. table.column IS NULL rather than table.column = null
				if ($this->value !== null) {

					// ANSI SQL functions get inserted right into SQL (not escaped, etc.)
					if ($this->value === Criteria::CURRENT_DATE || $this->value === Criteria::CURRENT_TIME || $this->value === Criteria::CURRENT_TIMESTAMP) {
						$sb .= $field . $this->comparison . $this->value;
					} else {

						$params[] = array('table' => $realtable, 'column' => $this->column, 'value' => $this->value);

						// default case, it is a normal col = value expression; value
						// will be replaced w/ '?' and will be inserted later using PDO bindValue()
						if ($this->ignoreStringCase) {
							$sb .= $db->ignoreCase($field) . $this->comparison . $db->ignoreCase(':p'.count($params));
						} else {
							$sb .= $field . $this->comparison . ':p'.count($params);
						}

					}
				} else {

					// value is null, which means it was either not specified or specifically
					// set to null.
					if ($this->comparison === Criteria::EQUAL || $this->comparison === Criteria::ISNULL) {
						$sb .= $field . Criteria::ISNULL;
					} elseif ($this->comparison === Criteria::NOT_EQUAL || $this->comparison === Criteria::ISNOTNULL) {
						$sb .= $field . Criteria::ISNOTNULL;
					} else {
						// for now throw an exception, because not sure how to interpret this
						throw new PropelException("Could not build SQL for expression: $field " . $this->comparison . " NULL");
					}

				}

			}
		}

		foreach ( $this->clauses as $key=>$clause ) {
			$sb .= $this->conjunctions[$key];
			$clause->appendPsTo($sb, $params);
			$sb .= ')';
		}
	}

	/**
	 * This method checks another Criteria to see if they contain
	 * the same attributes and hashtable entries.
	 * @return     boolean
	 */
	public function equals($obj)
	{
		// TODO: optimize me with early outs
		if ($this === $obj) {
			return true;
		}

		if (($obj === null) || !($obj instanceof Criterion)) {
			return false;
		}

		$crit = $obj;

		$isEquiv = ( ( ($this->table === null && $crit->getTable() === null)
			|| ( $this->table !== null && $this->table === $crit->getTable() )
						  )
			&& $this->column === $crit->getColumn()
			&& $this->comparison === $crit->getComparison());

		// check chained criterion

		$clausesLength = count($this->clauses);
		$isEquiv &= (count($crit->getClauses()) == $clausesLength);
		$critConjunctions = $crit->getConjunctions();
		$critClauses = $crit->getClauses();
		for ($i=0; $i < $clausesLength && $isEquiv; $i++) {
			$isEquiv &= ($this->conjunctions[$i] === $critConjunctions[$i]);
			$isEquiv &= ($this->clauses[$i] === $critClauses[$i]);
		}

		if ($isEquiv) {
			$isEquiv &= $this->value === $crit->getValue();
		}

		return $isEquiv;
	}

	/**
	 * Returns a hash code value for the object.
	 */
	public function hashCode()
	{
		$h = crc32(serialize($this->value)) ^ crc32($this->comparison);

		if ($this->table !== null) {
			$h ^= crc32($this->table);
		}

		if ($this->column !== null) {
			$h ^= crc32($this->column);
		}

		foreach ( $this->clauses as $clause ) {
			// TODO: i KNOW there is a php incompatibility with the following line
			// but i dont remember what it is, someone care to look it up and
			// replace it if it doesnt bother us?
			// $clause->appendPsTo($sb='',$params=array());
			$sb = '';
			$params = array();
			$clause->appendPsTo($sb,$params);
			$h ^= crc32(serialize(array($sb,$params)));
			unset ( $sb, $params );
		}

		return $h;
	}

	/**
	 * Get all tables from nested criterion objects
	 * @return     array
	 */
	public function getAllTables()
	{
		$tables = array();
		$this->addCriterionTable($this, $tables);
		return $tables;
	}

	/**
	 * method supporting recursion through all criterions to give
	 * us a string array of tables from each criterion
	 * @return     void
	 */
	private function addCriterionTable(Criterion $c, array &$s)
	{
		$s[] = $c->getTable();
		foreach ( $c->getClauses() as $clause ) {
			$this->addCriterionTable($clause, $s);
		}
	}

	/**
	 * get an array of all criterion attached to this
	 * recursing through all sub criterion
	 * @return     Criterion[]
	 */
	public function getAttachedCriterion()
	{
		$crits = array();
		$this->traverseCriterion($this, $crits);
		return $crits;
	}

	/**
	 * method supporting recursion through all criterions to give
	 * us an array of them
	 * @param      Criterion $c
	 * @param      array &$a
	 * @return     void
	 */
	private function traverseCriterion(Criterion $c, array &$a)
	{
		$a[] = $c;
		foreach ( $c->getClauses() as $clause ) {
			$this->traverseCriterion($clause, $a);
		}
	}
}


text:
namespace dreal {

using gc_type = cds::gc::HP;

template <typename T>
using Stack = cds::container::TreiberStack<gc_type, T>;

template <typename T, typename Comparator>
using PriorityQueue = cds::container::MSPriorityQueue<
    T, typename cds::container::mspriority_queue::make_traits<
           cds::opt::buffer<cds::opt::v::initialized_dynamic_buffer<char>>,
           cds::opt::compare<Comparator>>::type>;

class CdsScopeGuard {
 public:
  explicit CdsScopeGuard(bool use) : use_{use} {
    if (use_) {
      cds::threading::Manager::attachThread();
    }
  }
  CdsScopeGuard(const CdsScopeGuard&) = delete;
  CdsScopeGuard(CdsScopeGuard&&) = delete;
  CdsScopeGuard& operator=(const CdsScopeGuard&) = delete;
  CdsScopeGuard& operator=(CdsScopeGuard&&) = delete;

  ~CdsScopeGuard() {
    if (use_) {
      cds::threading::Manager::detachThread();
    }
  }

 private:
  const bool use_{};
};

class CdsInit {
 public:
  explicit CdsInit(bool use_lock_free_container) {
    // Initialize libcds
    cds::Initialize();
    hpGC_ = std::make_unique<gc_type>();
    if (use_lock_free_container) {
      cds::threading::Manager::attachThread();
    }
  }
  CdsInit(const CdsInit&) = delete;
  CdsInit(CdsInit&&) = delete;
  CdsInit& operator=(const CdsInit&) = delete;
  CdsInit& operator=(CdsInit&&) = delete;

  ~CdsInit() {
    // Terminate libcds
    cds::Terminate();
  }

 private:
  // Initialize Hazard Pointer singleton
  std::unique_ptr<gc_type> hpGC_;
};

}  // namespace dreal

redpajama_set_name: RedPajamaGithub


text:
package inmemorychannel

import (
	"context"
	"time"

	"go.uber.org/zap"

	"knative.dev/eventing/pkg/channel/multichannelfanout"
	"knative.dev/eventing/pkg/kncloudevents"
)

type MessageDispatcher interface {
	GetHandler(ctx context.Context) multichannelfanout.MultiChannelMessageHandler
}

type InMemoryMessageDispatcher struct {
	handler              multichannelfanout.MultiChannelMessageHandler
	httpBindingsReceiver *kncloudevents.HTTPMessageReceiver
	writeTimeout         time.Duration
	logger               *zap.Logger
}

type InMemoryMessageDispatcherArgs struct {
	Port                       int
	ReadTimeout                time.Duration
	WriteTimeout               time.Duration
	Handler                    multichannelfanout.MultiChannelMessageHandler
	Logger                     *zap.Logger
	HTTPMessageReceiverOptions []kncloudevents.HTTPMessageReceiverOption
}

// GetHandler gets the current multichannelfanout.MessageHandler to delegate all HTTP
// requests to.
func (d *InMemoryMessageDispatcher) GetHandler(ctx context.Context) multichannelfanout.MultiChannelMessageHandler {
	return d.handler
}

// Start starts the inmemory dispatcher's message processing.
// This is a blocking call.
func (d *InMemoryMessageDispatcher) Start(ctx context.Context) error {
	return d.httpBindingsReceiver.StartListen(kncloudevents.WithShutdownTimeout(ctx, d.writeTimeout), d.handler)
}

// WaitReady blocks until the dispatcher's server is ready to receive requests.
func (d *InMemoryMessageDispatcher) WaitReady() {
	<-d.httpBindingsReceiver.Ready
}

func NewMessageDispatcher(args *InMemoryMessageDispatcherArgs) *InMemoryMessageDispatcher {
	// TODO set read timeouts?
	bindingsReceiver := kncloudevents.NewHTTPMessageReceiver(
		args.Port,
		args.HTTPMessageReceiverOptions...,
	)

	dispatcher := &InMemoryMessageDispatcher{
		handler:              args.Handler,
		httpBindingsReceiver: bindingsReceiver,
		logger:               args.Logger,
		writeTimeout:         args.WriteTimeout,
	}

	return dispatcher
}


text:
import { makeStyles } from '@material-ui/core/styles'

export const PublishDialogStyles = makeStyles((theme) => ({
  root: {
    flexGrow: 1,
    width: '100%',
    backgroundColor: theme.palette.background.paper,
  },
}))


text:
package org.ops4j.pax.wicket.spi.blueprint.injection.blueprint;

import org.apache.aries.blueprint.ParserContext;
import org.apache.aries.blueprint.mutable.MutableBeanMetadata;
import org.ops4j.pax.wicket.api.PaxWicketBeanInjectionSource;
import org.ops4j.pax.wicket.spi.support.BundleInjectionProviderHelperDecorator;
import org.w3c.dom.Element;

public class BlueprintInjectionResolverDefinitionParser extends AbstractBlueprintBeanDefinitionParser {

    @Override
    public Class<?> getRuntimeClass() {
        return BundleInjectionProviderHelperDecorator.class;
    }

    @Override
    protected void extractRemainingMetaData(Element element, ParserContext context, MutableBeanMetadata beanMetadata)
        throws Exception {
        addPropertyValueFromElement("applicationName", element, context, beanMetadata);
        beanMetadata.addProperty("injectionSource",
            createStringValue(context, PaxWicketBeanInjectionSource.INJECTION_SOURCE_BLUEPRINT));
    }

}


text:
---
layout: default
title: API Documetation
---

General

Introduction

Components

Endpoints

Security

Issues

Content Analysis

Introduction

Endpoints

Linked Data

Introduction

Endpoints

Semantic Search

Introduction

Redlink API Documentation

                The Redlink API provides a set of RESTful web services, grouped according
                their purpose: content analysis, semantic search and linked data publishing.

                This pages provides documentation for the old
                version 1.0-BETA of the API;
                please, check the latest version.

General

Introduction

                  The Redlink Platform consists of a number of services that are offered to users through a REST
                  API. The Platform provides three main services: Redlink Content Analysis, Redlink Linked Data
                  Publishing and Redlink Semantic Search.

                  The Redlink Platform is implemented as "software as a service" (SaaS) running on a distributed cloud infrastructure. Users
                  can access the system here through a uniform web service API using a private key to identify themselves. For the most
                  common web frameworks, we will provide plugins providing out-of-the-box services. All requests to the API are handled
                  by a single gateway which takes care of accounting and forwards the requests to backend clusters providing
                  the necessary functionality.

                  We are currently in public beta, so you can register at
                  my.redlink.io
                  for getting free access to the platform for a trial period of 42 days
                  (pricing details).

Components

                  The Redlink API is organized in three major components:

                      component
                      description
                      available

                        Content Analysis

                        Semantic Content Analysis, Interlinking and Enrichement

                        since 1.0-ALPHA

                        Linked Data

                        Publish and query Linked Data, huge public datasets (DBPedia, Freebase, and many more) as
                        well as your personal.

                        since 1.0-ALPHA

                        Semantic Search

                        Combine the two above to turn search into find!

                        planned (version 1.0)

Endpoints

                  All endpoints are available under the following schema:

https://api.redlink.io/1.0-BETA/{ENDPOINT}?key={KEY}&...

                  where:

{ENDPOINT}

is the concrete REST endpoint to call

{KEY}

is your key for using the API

                  Note: Take into account that all requests
                  to all endpoints to the API require the key parameter. Therefore it'll be
                  not mentioned further on their concrete documentations.

                  You can play around with our API console.

                  The API provides a special endpoint at the root:

https://api.redlink.io/1.0-BETA?key={KEY}

                  which returns some information about the usage of a concrete key.

{
  "accessible": true,   //provided key is valid and enabled
  "limit": 10000,       //request limit/credit (within the current reporting period)
  "requests": 521,      //requests sent/credit used so far
  "bytes": 345657,      //bytes sent so far
  "seconds": 42         //total processing time
  "owner": "007",       //user-id the key belongs to
  "analyses": [         //analysis services enabled for this key
    "my-analysis"
  ],
  "datasets": [         //datasets enabled for this key
    "my-dataset1",
    "my-dataset2"
  ]
}

Security

                  Keeping your data safe is important for us here at redlink, that's why the redlink API is only
                  available using the https protocol. Therefore clients need to deal
                  with TLS/SSL.

                  All SDKs for this API provided by us come with TLS/SSL support enabled. You
                  should not trust clients that do not use the certificate to access the API.

Issues

                  Do you have any issue or question about the API? Please,
                  contact us.

Content Analysis

Introduction

                  Redlink Content Analysis offers fact extraction, topic classification, and fact
                  linking from textual and media documents in different languages. Users will be able to send text
                  (and in the future media content) and get back facts and entities that have been identified automatically.
                  In addition, the service will provide references to existing datasets (public datasets like Dbpedia
                  and Freebase, as well as custom user-created vocabularies like a product database) about the entities
                  identified in the content. Users will be able to create their own custom configurations with some simple
                  steps, e.g. for adding advanced natural language processing features or commercial datasets.

Endpoints

                  Before using an analysis endpoint, the service must be configured in
                  my.redlink.io and assigned to an
                  application.

                    post
                    /analysis/{analysis}/enhance

                      Performs an analysis of the content posted in the request body, getting
                      enhancements results in the requested format. The {analysis} in the
                      path bounds to the analysis to a concrete service previously configured.

                      Parameters

                          name
                          description
                          required
                          restricted value/s

                          in

                            Format used for encode the content to analyze

                            optional (when missing, different heuristics are applied)

                            text,
                            pdf,
                            html,
                            office

                          out

                            Format preferred to get the enhacement results

                            optional (when missing, HTTP content negotiation is applied)

                            json,
                            xml,
                            jsonld,
                            rdfxml,
                            rdfjson
                            turtle
                            nt

                          summary

                            Request content summary

                            optional

                            true/false

                          thumbnail

                            Request Thumbnail URLs

                            optional

                            true/false

                      The response could come in RDF (for jsonld, rdfxml
                      and turtle formats) using
                      this structure;
                      or using a simplied version (for json and xml formats)
                      which follows the following schema:

{

    "languages": [ // Detected languages
        "en"
    ],

    "entities": [ // if no entity-extraction was done (e.g. because not activated in the analysis)
                  // this property is completely omitted.
        {
            "dataset": "dbpedia", // The configured dataset (id/name/...) this entity comes from
            "reference": "http://dbpedia.org/resource/Saturday_Night_Live", // this is the URI of the entity
            "confidence": 1.0, // the maximum confidence of all mentions

            "properties": { // (1) basic properties, for every entity, always present
                "name": "name",
                "summary": "short summary",

                "type": [ // list of types, used to know which specific props are available (see below)
                    "creative work",
                    "event",
                    "organisation",
                    "person",
                    "place",
                    "product",
                    "other"
                ],
                "sameAs": [ // sameAs links of the "reference"
                    "http://rdf.freebase.com/ns/m.xxxxx",
                    "http://yago-knowledge.org/resource/xxxx"
                ],

                //
                "image": [ (2) optional basic properties, might come with every entity
                ],

                "homepage": "http://example.org/", // optional

                // (3) type specific properties

                // (3.1) creative work
                "creator": "...",
                "genre": "...", //
                "publisher": "...",
                "datePublished": "2015-01-01",

                // (3.2) event
                "startDate": "2014-08-26T10:00:00Z",
                "endDate": "2014-08-26T12:30:00Z", // optional

                // (3.3) organisation
                /* nothing extra here */

                // (3.4) person
                "gender": "male",
                "birth": "1974-04-01",
                "death": "2013-11-09", // optional ;-)
                "nationality": "de",

                // (3.5) place
                /* nothing extra here */

                // (3.6) product
                "brand": "Apple",
                "manufacturer": "Foxconn",

                // (3.7) other
                /* nothing extra here */

                // (3.8) Shared
                // (3.8.1) place || event || organisation (headquarter)
                "location": {
                    "lat": 43.3333,
                    "lon": 13.3333
                }

            }, /* END properties */
            "mentions": [
                {
                    "prefix": "c died on ", // 10 chars before the text
                    "text": "Saturday",     // aka anchor
                    "suffix": " at the ag", // 10 chars after the text
                    "context": " the context where the entity was recognized ",
                    "confidence": 0.9,
                    "start": 104,
                    "end": 112
                },
                { /* more mentions ... */ }
            ] /* END mentions */
        }, /* END entity */
        { /* more entities ... */ }
    ], /* END entities */

    "facts": [ // if no fact-extraction was done (e.g. because not activated in the analysis)
               // this property is completely omitted.
        {
            "name": "Product Weight", // preferred label of the fact-def. in the lang of the text
            "reference": "http://example.com/foo/ProductWeight", // URI of the fact-definition
            "type": "numeric", // enum, entity, numeric, range, dimension, date, duration, event
            "value": [
                "foo", "bar"
            ],
            "mentions": [
                {
                    "prefix": "x50x15 mm ",
                    "text": "Weight: 0.3 kg",
                    "suffix": " Shipping ",
                    "context": "...",
                    "start": 15,
                    "end": 26
                },
                { /* more mentions ... */}
            ]
        },
        { /* more facts */ }
    ], /* END facts */

    "categories": [ // if no classification was done (e.g. because not activated in the analysis)
                    // this property is completely omitted.
        {
            "dataset": "dbpedia",
            "component": "machine-linking",
            "reference": "http://dbpedia.org/resource/xxxx",
            "confidence": 0.1234563,
            "properties": {
                "name": "...",
                "summary": "...",
                "image": [
                    "http://..."
                ]
            }
        },
        { /* more categories */ }
    ], /* END categories */

    "sentiments": { // if no sentiment analysis was done (e.g. because not activated in the analysis)
                    //  this property is completely omitted.
        "positive": 0.6213,
        "negative": 0.2112
    } /* END sentiments */

}

Linked Data

Introduction

                  Redlink Linked Data Publishing offers data management, data publication,
                  and data integration for enterprise data using open standards and technologies (RDF and
                  Linked Data); legacy proprietary data can be transformed into a standardized data model
                  and integrated with data from other sources. The service will allow users to create their
                  own Linked Data servers for managing vocabularies or publishing their own datasets (e.g.
                  in Open Data projects). Datasets managed in this way can also be made available for content
                  analysis and linking, and they can be either private (Linked Enterprise Data) or public
                  (Linked Open Data).

Endpoints

                  Remember to enable your favourite datasets for the application (key) you are using!

                  Endpoints which have the dataset as part of the address restrict the operation
                  to that dataset. Endpoints without a dataset in the path operate on all datasets
                  configured for this application.

                    get
                    /data/{dataset}

                      Export the dataset to the RDF serialization requested
                      (using http content negotiation).

                    post
                    /data/{dataset}

                      Import the raw RDF sent in the request body into the current dataset.

                    put
                    /data/{dataset}

                      Import the raw RDF sent in the request body replacing
                      the current dataset (i.e., removing all data before importing).

                    delete
                    /data/{dataset}

                      Remove all data from the dataset (but it does not remove the dataset itself).

                    get
                    /data/{dataset}/resource

                      Get a concrete resource in the RDF serialization requested
                      (http content negotiation).

                      Parameters

                          name
                          description
                          required
                          restricted value/s

                          uri

                            Resource URI

                            mandatory

                            valid URI

                    post
                    /data/{dataset}/resource

                      Add the raw data if the request body to this concrete resource.
                      All triples with different subject will be ignored.
                      Format is detected using content negotiation.

                      Parameters

                          name
                          description
                          required
                          restricted value/s

                          uri

                            Resource URI

                            mandatory

                            valid URI

                    put
                    /data/{dataset}/resource

                      Replace the current resource with the raw data in the request body.
                      All triples with different subject will be ignored.
                      Format is detected using content negotiation.

                      Parameters

                          name
                          description
                          required
                          restricted value/s

                          uri

                            Resource URI

                            mandatory

                            valid URI

                    delete
                    /data/{dataset}/resource

                      Remove a concrete resource from the dataset.

                      Parameters

                          name
                          description
                          required
                          restricted value/s

                          uri

                            Resource URI

                            mandatory

                            valid URI

                    get
                    /data/resource

                      Get a concrete resource from all datasets in the RDF
                      serialization requested (http content negotiation).

                      Parameters

                          name
                          description
                          required
                          restricted value/s

                          uri

                            Resource URI

                            mandatory

                            valid URI

                    get
                    /data/{dataset}/sparql/select

                      Evaluates a SPARQL SELECT or ASK query over a dataset.

                      Parameters

                          name
                          description
                          required
                          restricted value/s

                          query

                            Query string

                            mandatory

                            n/a

                          in

                            Format used to send data in the request

                            optional (when missing, regular HTTP mechanisms are applied)

                          out

                            Format preferred to get the results

                            optional (when missing, HTTP content negotiation is applied)

                            json,
                            xml,
                            tabs,
                            csv

                    post
                    /data/{dataset}/sparql/select

                      Evaluates a SPARQL SELECT or ASK query over a dataset.

                      Parameters

                          name
                          description
                          required
                          restricted value/s

                          query

                            Query string

                            optional (if missing, a application/x-www-form-urlencoded
                            should be sent and query will be read from the request body)

                            n/a

                          in

                            Format used to send data in the request

                            optional (when missing, regular HTTP mechanisms are applied)

                          out

                            Format preferred to get the results

                            optional (when missing, HTTP content negotiation is applied)

                            json,
                            xml,
                            tabs,
                            csv

                    get
                    /data/{dataset}/sparql/update

                      Evaluates a SPARQL UPDATE query over a dataset.

                      Parameters

                          name
                          description
                          required
                          restricted value/s

                          update

                            Query string.

                            mandatory

                            n/a

                          in

                            Format used to send data in the request

                            optional (when missing, regular HTTP mechanisms are applied)

                          out

                            Format preferred to get the results

                            optional (when missing, HTTP content negotiation is applied)

                            json,
                            xml,
                            tabs,
                            csv

                    post
                    /data/{dataset}/sparql/update

                      Evaluates a SPARQL UPDATE query on the data.

                      Parameters

                          name
                          description
                          required
                          restricted value/s

                          update

                            Query string. When missing a application/x-www-form-urlencoded
                            should be sent and query qould be ready from the request body.

                            optional

                            n/a

                          in

                            Format used to send data in the request

                            optional (when missing, regular HTTP mechanisms are applied)

                          out

                            Format preferred to get the results

                            optional (when missing, HTTP content negotiation is applied)

                            json,
                            xml,
                            tabs,
                            csv

                    get
                    /data/sparql

                      Evaluates a SPARQL SELECT or ASK query over all datasets.

                      Parameters

                          name
                          description
                          required
                          restricted value/s

                          query

                            Query string

                            mandatory

                            n/a

                          in

                            Format used to send data in the request

                            optional (when missing, regular HTTP mechanisms are applied)

                          out

                            Format preferred to get the results

                            optional (when missing, HTTP content negotiation is applied)

                            json,
                            xml,
                            tabs,
                            csv

                    post
                    /data/sparql

                      Evaluates a SPARQL SELECT or ASK query over all datasets.

                      Parameters

                          name
                          description
                          required
                          restricted value/s

                          query

                            Query string

                            optional (hen missing, a application/x-www-form-urlencoded
                            should be sent and query will be read from the request body)

                            n/a

                          in

                            Format used to send data in the request

                            optional (when missing, regular HTTP mechanisms are applied)

                          out

                            Format preferred to get the results

                            optional (when missing, HTTP content negotiation is applied)

                            json,
                            xml,
                            tabs,
                            csv

                    get
                    /data/{dataset}/ldpath

                      Evaluates a LDPath program over a dataset.

                      Parameters

                          name
                          description
                          required
                          restricted value/s

                          program

                            Program string

                            mandatory

                            n/a

                          uri

                            Resource where to start to evaluate the program

                            mandatory

                            valid URI

                    post
                    /data/{dataset}/ldpath

                      Evaluates a LDPath program over a dataset.

                      Parameters

                          name
                          description
                          required
                          restricted value/s

                          program

                            Program string

                            mandatory

                            n/a

                          uri

                            Resource where to start to evaluate the program

                            mandatory

                            valid URI

                    get
                    /data/ldpath

                      Evaluates a LDPath program over all datasets.

                      Parameters

                          name
                          description
                          required
                          restricted value/s

                          program

                            Program string

                            mandatory

                            n/a

                          uri

                            Resource where to start to evaluate the program

                            mandatory

                            valid URI

                    post
                    /data/ldpath

                      Evaluates a LDPath program over all datasets.

                      Parameters

                          name
                          description
                          required
                          restricted value/s

                          program

                            Program string

                            mandatory

                            n/a

                          uri

                            Resource where to start to evaluate the program

                            mandatory

                            valid URI

                  In addition, all resources in a dataset explicitly published by the user will be
                  publicly available according the Linked Data principles
                  through our data hub (data.redlink.io) under the following schema:

http://data.redlink.io/{USER}/{DATASET}/...

Semantic Search

Introduction

                    Redlink Semantic Search offers high performance faceted and semantic search
                    over enterprise content, different ranking algorithms, auto completion, thesaurus/vocabulary
                    integration, etc.; the service will provide advanced search functionalities based on Content
                    Analysis and Linked Data. Users will be able to create their own search configurations, upload
                    documents, analyse and link them with datasets and vocabularies, and provide powerful search
                    functionalities, e.g. browsing documents by (automatically detected) categories, persons occurring
                    in the text, etc.

                    Semantic Search is not yet part of the public API, only available for premium customers; but
                    it will be included in the next versions, so stay tuned... In the meantime, you can check either
                    our Search Engine or use
                    the Redlink Solr plugin
                    to semantically enrich your current search.


text:
/* DO NOT EDIT */
/* This file was generated from team_member_space_limits.stone */

package com.dropbox.core.v2.team;

import com.dropbox.core.stone.StoneDeserializerLogger;
import com.dropbox.core.stone.StoneSerializers;
import com.dropbox.core.stone.StructSerializer;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;

import java.io.IOException;
import java.util.Arrays;

/**
 * User and their custom quota in GB (1 TB = 1024 GB).  No quota returns if the
 * user has no custom quota set.
 */
public class UserCustomQuotaResult {
    // struct team.UserCustomQuotaResult (team_member_space_limits.stone)

    protected final UserSelectorArg user;
    protected final Long quotaGb;

    /**
     * User and their custom quota in GB (1 TB = 1024 GB).  No quota returns if
     * the user has no custom quota set.
     *
     * @param user  Must not be {@code null}.
     * @param quotaGb  Must be greater than or equal to 15.
     *
     * @throws IllegalArgumentException  If any argument does not meet its
     *     preconditions.
     */
    public UserCustomQuotaResult(UserSelectorArg user, Long quotaGb) {
        if (user == null) {
            throw new IllegalArgumentException("Required value for 'user' is null");
        }
        this.user = user;
        if (quotaGb != null) {
            if (quotaGb < 15L) {
                throw new IllegalArgumentException("Number 'quotaGb' is smaller than 15L");
            }
        }
        this.quotaGb = quotaGb;
    }

    /**
     * User and their custom quota in GB (1 TB = 1024 GB).  No quota returns if
     * the user has no custom quota set.
     *
     * <p> The default values for unset fields will be used. </p>
     *
     * @param user  Must not be {@code null}.
     *
     * @throws IllegalArgumentException  If any argument does not meet its
     *     preconditions.
     */
    public UserCustomQuotaResult(UserSelectorArg user) {
        this(user, null);
    }

    /**
     *
     * @return value for this field, never {@code null}.
     */
    public UserSelectorArg getUser() {
        return user;
    }

    /**
     *
     * @return value for this field, or {@code null} if not present.
     */
    public Long getQuotaGb() {
        return quotaGb;
    }

    @Override
    public int hashCode() {
        int hash = Arrays.hashCode(new Object [] {
            user,
            quotaGb
        });
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == this) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        // be careful with inheritance
        else if (obj.getClass().equals(this.getClass())) {
            UserCustomQuotaResult other = (UserCustomQuotaResult) obj;
            return ((this.user == other.user) || (this.user.equals(other.user)))
                && ((this.quotaGb == other.quotaGb) || (this.quotaGb != null && this.quotaGb.equals(other.quotaGb)))
                ;
        }
        else {
            return false;
        }
    }

    @Override
    public String toString() {
        return Serializer.INSTANCE.serialize(this, false);
    }

    /**
     * Returns a String representation of this object formatted for easier
     * readability.
     *
     * <p> The returned String may contain newlines. </p>
     *
     * @return Formatted, multiline String representation of this object
     */
    public String toStringMultiline() {
        return Serializer.INSTANCE.serialize(this, true);
    }

    /**
     * For internal use only.
     */
    static class Serializer extends StructSerializer<UserCustomQuotaResult> {
        public static final Serializer INSTANCE = new Serializer();

        @Override
        public void serialize(UserCustomQuotaResult value, JsonGenerator g, boolean collapse) throws IOException, JsonGenerationException {
            if (!collapse) {
                g.writeStartObject();
            }
            g.writeFieldName("user");
            UserSelectorArg.Serializer.INSTANCE.serialize(value.user, g);
            if (value.quotaGb != null) {
                g.writeFieldName("quota_gb");
                StoneSerializers.nullable(StoneSerializers.uInt32()).serialize(value.quotaGb, g);
            }
            if (!collapse) {
                g.writeEndObject();
            }
        }

        @Override
        public UserCustomQuotaResult deserialize(JsonParser p, boolean collapsed) throws IOException, JsonParseException {
            UserCustomQuotaResult value;
            String tag = null;
            if (!collapsed) {
                expectStartObject(p);
                tag = readTag(p);
            }
            if (tag == null) {
                UserSelectorArg f_user = null;
                Long f_quotaGb = null;
                while (p.getCurrentToken() == JsonToken.FIELD_NAME) {
                    String field = p.getCurrentName();
                    p.nextToken();
                    if ("user".equals(field)) {
                        f_user = UserSelectorArg.Serializer.INSTANCE.deserialize(p);
                    }
                    else if ("quota_gb".equals(field)) {
                        f_quotaGb = StoneSerializers.nullable(StoneSerializers.uInt32()).deserialize(p);
                    }
                    else {
                        skipValue(p);
                    }
                }
                if (f_user == null) {
                    throw new JsonParseException(p, "Required field \"user\" missing.");
                }
                value = new UserCustomQuotaResult(f_user, f_quotaGb);
            }
            else {
                throw new JsonParseException(p, "No subtype found that matches tag: \"" + tag + "\"");
            }
            if (!collapsed) {
                expectEndObject(p);
            }
            StoneDeserializerLogger.log(value, value.toStringMultiline());
            return value;
        }
    }
}


text:
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser.continuous_search;

import static org.chromium.base.test.util.Batch.PER_CLASS;

import android.os.Handler;
import android.support.test.InstrumentationRegistry;

import androidx.test.filters.MediumTest;

import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import org.chromium.base.Log;
import org.chromium.base.test.util.Batch;
import org.chromium.base.test.util.CallbackHelper;
import org.chromium.base.test.util.CommandLineFlags;
import org.chromium.base.test.util.Restriction;
import org.chromium.chrome.browser.flags.ChromeFeatureList;
import org.chromium.chrome.browser.flags.ChromeSwitches;
import org.chromium.chrome.browser.tab.EmptyTabObserver;
import org.chromium.chrome.browser.tab.Tab;
import org.chromium.chrome.browser.tab.TabObserver;
import org.chromium.chrome.test.ChromeJUnit4ClassRunner;
import org.chromium.chrome.test.ChromeTabbedActivityTestRule;
import org.chromium.chrome.test.util.browser.Features;
import org.chromium.components.embedder_support.util.UrlConstants;
import org.chromium.content_public.browser.LoadUrlParams;
import org.chromium.content_public.browser.test.util.TestThreadUtils;
import org.chromium.content_public.common.ContentSwitches;
import org.chromium.net.NetError;
import org.chromium.net.test.EmbeddedTestServer;
import org.chromium.ui.test.util.UiRestriction;
import org.chromium.url.GURL;

import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * Integration tests for the {@link ContinuousSearchTabHelper} class.
 *
 * To serve a https://www.google.com/search?q= URL we need to set flags so that the {@link
 * EmbeddedTestServer} serves the files properly and {@link SearchUrlHelper} can work without
 * being mocked. It is also necessary to ignore port numbers as only 80 and 443 are expected, but
 * the {@link EmbeddedTestServer} will use any open port.
 */
@RunWith(ChromeJUnit4ClassRunner.class)
@Features.EnableFeatures({ChromeFeatureList.CONTINUOUS_SEARCH})
@CommandLineFlags.Add({ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE, "ignore-google-port-numbers",
        "ignore-certificate-errors", ContentSwitches.HOST_RESOLVER_RULES + "=MAP * 127.0.0.1"})
@Batch(PER_CLASS)
public class ContinuousSearchTabHelperTest {
    private static final String TAG = "CSTHT";
    private static final String TEST_SERVER_DIR = "chrome/browser/continuous_search/testdata";
    private static final String TEST_URL = "/search";

    @Rule
    public ChromeTabbedActivityTestRule mActivityTestRule = new ChromeTabbedActivityTestRule();

    private EmbeddedTestServer mServer;

    /**
     * Whether the device had a proxy error while running the test. If this happens we skip the rest
     * of the test as it only happens on some devices on specific bots.
     * TODO(crbug/1176268): Find out why this failure happens and remove this condition.
     */
    private boolean mHadProxyError;

    /**
     * Fake implementation of {@link SearchResultProducer} that returns the data passed to it and no
     * results.
     */
    public class FakeSearchResultProducer extends SearchResultProducer {
        private String mQuery;
        private GURL mSearchUrl;

        FakeSearchResultProducer(Tab tab, SearchResultListener listener) {
            super(tab, listener);
        }

        @Override
        public void fetchResults(GURL url, String query) {
            mSearchUrl = url;
            mQuery = query;
            new Handler().postDelayed(() -> {
                mListener.onResult(new ContinuousNavigationMetadata(mSearchUrl, mQuery,
                        new ContinuousNavigationMetadata.Provider(0, null, 0),
                        new ArrayList<PageGroup>()));
            }, 300);
        }

        @Override
        public void cancel() {}
    }

    /**
     * A {@link ContinuousNavigationUserDataObserver} used to wait on events.
     */
    public class WaitableContinuousNavigationUserDataObserver
            implements ContinuousNavigationUserDataObserver {
        public CallbackHelper mInvalidateCallbackHelper = new CallbackHelper();
        public CallbackHelper mOnUpdateCallbackHelper = new CallbackHelper();
        public ContinuousNavigationMetadata mMetadata;
        public GURL mUrl;
        public boolean mOnSrp;

        @Override
        public void onInvalidate() {
            mInvalidateCallbackHelper.notifyCalled();
        }

        @Override
        public void onUpdate(ContinuousNavigationMetadata metadata) {
            mMetadata = metadata;
            mOnUpdateCallbackHelper.notifyCalled();
        }

        @Override
        public void onUrlChanged(GURL url, boolean onSrp) {
            mUrl = url;
            mOnSrp = onSrp;
        }
    }

    @Before
    public void setUp() {
        mHadProxyError = false;
        SearchResultProducerFactory.overrideFactory((Tab tab, SearchResultListener listener) -> {
            return new FakeSearchResultProducer(tab, listener);
        });
        mServer = new EmbeddedTestServer();
        mServer.initializeNative(InstrumentationRegistry.getContext(),
                EmbeddedTestServer.ServerHTTPSSetting.USE_HTTP);
        mServer.addDefaultHandlers(TEST_SERVER_DIR);
        Assert.assertTrue(mServer.start());
        mActivityTestRule.startMainActivityOnBlankPage();
    }

    @After
    public void tearDown() {
        mServer.stopAndDestroyServer();
    }

    /**
     * Loads a tab with a provided set of params. Will exit via {@link Assert#fail()} if the tab
     * fails to load, crashes, or exceeds the a certain timeout window. Otherwise, the tab will
     * be successfully loaded upon returning.
     * @param tab The tab to load.
     * @param params The URL and loading type for the tab.
     */
    private void loadUrl(Tab tab, LoadUrlParams params) {
        final CallbackHelper startedCallback = new CallbackHelper();
        final CallbackHelper loadedCallback = new CallbackHelper();

        TabObserver observer = new EmptyTabObserver() {
            @Override
            public void onPageLoadStarted(Tab tab, GURL url) {
                startedCallback.notifyCalled();
            }

            @Override
            public void onPageLoadFinished(Tab tab, GURL url) {
                loadedCallback.notifyCalled();
            }

            @Override
            public void onPageLoadFailed(Tab tab, int errorCode) {
                if (errorCode == NetError.ERR_PROXY_CONNECTION_FAILED) {
                    Log.e(TAG, "Page load failed due to proxy connection.");
                    mHadProxyError = true;
                } else {
                    Assert.fail("Tab failed to load: " + errorCode);
                }
            }

            @Override
            public void onCrash(Tab tab) {
                Assert.fail("Tab never started loading.");
            }
        };
        TestThreadUtils.runOnUiThreadBlocking(() -> tab.addObserver(observer));

        InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> { tab.loadUrl(params); });

        // Ensure the tab loads.
        try {
            startedCallback.waitForCallback(0, 1);
        } catch (TimeoutException e) {
            Assert.fail("Tab never started loading.");
        }
        try {
            loadedCallback.waitForCallback(0, 1);
        } catch (TimeoutException e) {
            Assert.fail("Tab timed out while loading.");
        }

        TestThreadUtils.runOnUiThreadBlocking(() -> tab.removeObserver(observer));
    }

    @Test
    @MediumTest
    @Restriction({UiRestriction.RESTRICTION_TYPE_PHONE})
    public void testContinuousSearchFakeResults() throws TimeoutException {
        WaitableContinuousNavigationUserDataObserver observer =
                new WaitableContinuousNavigationUserDataObserver();

        // Load a SRP URL.
        final Tab tab = mActivityTestRule.getActivity().getActivityTab();
        InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> {
            ContinuousNavigationUserDataImpl continuousNavigationUserData =
                    ContinuousNavigationUserDataImpl.getOrCreateForTab(tab);
            Assert.assertNotNull(continuousNavigationUserData);
            continuousNavigationUserData.addObserver(observer);
        });
        loadUrl(tab,
                new LoadUrlParams(
                        mServer.getURLWithHostName("www.google.com", TEST_URL + "?q=cat+dog")));
        // TODO(crbug/1176268): Find out why the proxy connection fails for some
        // android-arm-official-tests only.
        if (mHadProxyError) {
            Log.e(TAG, "Tab failed to load due to proxy error. Skipping...");
            return;
        }
        observer.mOnUpdateCallbackHelper.waitForFirst(
                "Timed out waiting for SearchResultUserDataObserver#onUpdate", 5000,
                TimeUnit.MILLISECONDS);

        // Check the returned data.
        Assert.assertEquals("cat dog", observer.mMetadata.getQuery());
        InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> {
            ContinuousNavigationUserDataImpl continuousNavigationUserData =
                    ContinuousNavigationUserDataImpl.getOrCreateForTab(tab);
            Assert.assertTrue(continuousNavigationUserData.isValid());
            String url = mServer.getURLWithHostName("www.google.com", TEST_URL + "?q=cat+dog");
            Assert.assertTrue(observer.mMetadata.getRootUrl().getSpec().startsWith(url));
            Assert.assertTrue(observer.mUrl.getSpec().startsWith(url));
            Assert.assertTrue(observer.mOnSrp);
        });

        // Invalidate the data.
        loadUrl(tab, new LoadUrlParams(UrlConstants.ABOUT_URL));
        observer.mInvalidateCallbackHelper.waitForCallback(
                "Timed out waiting for SearchResultUserDataObserver#onInvalidate", 0, 1, 5000,
                TimeUnit.MILLISECONDS);
    }
}


text:
<?php

namespace NS\SearchBundle\Transformer;

use FOS\ElasticaBundle\Doctrine\AbstractElasticaToModelTransformer;
use Doctrine\ORM\Query;

class ElasticaToArticleTransformer extends AbstractElasticaToModelTransformer
{
    /**
     * Fetch Article from Doctrine for the given Elasticsearch identifiers
     *
     * @param array $identifierValues ids values
     * @param Boolean $hydrate whether or not to hydrate the objects, false returns arrays
     * @return array of objects or arrays
     */
    protected function findByIdentifiers(array $identifierValues, $hydrate)
    {
        if (empty($identifierValues)) {
            return array();
        }

        $hydrationMode = $hydrate ? Query::HYDRATE_OBJECT : Query::HYDRATE_ARRAY;
        $qb = $this->registry
            ->getManagerForClass('NSSearchBundle:Article')
            ->getRepository('NSSearchBundle:Article')
            ->createQueryBuilder('a');

        $qb
            ->select('a,aut,c')
            ->join('a.authors', 'aut')
            ->join('a.category', 'c')
            ->where($qb->expr()->in('a.'.$this->options['identifier'], ':values'))
            ->setParameter('values', $identifierValues)
        ;

        return $qb->getQuery()->setHydrationMode($hydrationMode)->execute();
    }
}


text:
@interface APLExpandableSectionFlowLayout : APLSectionTopToBottomFlowLayout

@end


text:
<?xml version="1.0" encoding="utf-8"?>
<com.example.bobby.viperdemo.HomeView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/home_view"
    tools:context="com.example.bobby.viperdemo.HomeActivity">
    <ListView
        android:id="@+id/list_timeline"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</com.example.bobby.viperdemo.HomeView>


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
Mem. New York Bot. Gard. 65:354. 1991

#### Original name
Mimosa paludosa Benth.

### Remarks
null


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Cat. Lich. Univers. 1: 529 (1922)

#### Original name
Porina dilatata Vain.

### Remarks
null


text:
angular.module('gustav.buildingSaving.i18n', ['pascalprecht.translate']).run(function($translatePartialLoader) {
    $translatePartialLoader.addPart('plugins/buildingSaving');
});


text:
module Main where

import Diagrams.Prelude
import Diagrams.Backend.SVG.CmdLine
import Lib

main :: IO ()
--main = someFunc
--
main = mainWith (circle 1 :: Diagram B)


text:
<?php
/**
 * This file is automatically @generated by {@link BuildMetadataPHPFromXml}.
 * Please don't modify it directly.
 */

return array (
  'generalDesc' =>
  array (
    'NationalNumberPattern' => '[25679]\\d{8}',
    'PossibleNumberPattern' => '\\d{7,9}',
  ),
  'fixedLine' =>
  array (
    'NationalNumberPattern' => '
          (?:
            2[1345]|
            5[1347]|
            6[123479]|
            71
          )\\d{7}
        ',
    'PossibleNumberPattern' => '\\d{7,9}',
    'ExampleNumber' => '212345678',
  ),
  'mobile' =>
  array (
    'NationalNumberPattern' => '9[1-6]\\d{7}',
    'PossibleNumberPattern' => '\\d{9}',
    'ExampleNumber' => '912345678',
  ),
  'tollFree' =>
  array (
    'NationalNumberPattern' => 'NA',
    'PossibleNumberPattern' => 'NA',
  ),
  'premiumRate' =>
  array (
    'NationalNumberPattern' => 'NA',
    'PossibleNumberPattern' => 'NA',
  ),
  'sharedCost' =>
  array (
    'NationalNumberPattern' => 'NA',
    'PossibleNumberPattern' => 'NA',
  ),
  'personalNumber' =>
  array (
    'NationalNumberPattern' => 'NA',
    'PossibleNumberPattern' => 'NA',
  ),
  'voip' =>
  array (
    'NationalNumberPattern' => 'NA',
    'PossibleNumberPattern' => 'NA',
  ),
  'pager' =>
  array (
    'NationalNumberPattern' => 'NA',
    'PossibleNumberPattern' => 'NA',
  ),
  'uan' =>
  array (
    'NationalNumberPattern' => 'NA',
    'PossibleNumberPattern' => 'NA',
  ),
  'emergency' =>
  array (
    'NationalNumberPattern' => 'NA',
    'PossibleNumberPattern' => 'NA',
  ),
  'voicemail' =>
  array (
    'NationalNumberPattern' => 'NA',
    'PossibleNumberPattern' => 'NA',
  ),
  'shortCode' =>
  array (
    'NationalNumberPattern' => 'NA',
    'PossibleNumberPattern' => 'NA',
  ),
  'standardRate' =>
  array (
    'NationalNumberPattern' => 'NA',
    'PossibleNumberPattern' => 'NA',
  ),
  'carrierSpecific' =>
  array (
    'NationalNumberPattern' => 'NA',
    'PossibleNumberPattern' => 'NA',
  ),
  'noInternationalDialling' =>
  array (
    'NationalNumberPattern' => 'NA',
    'PossibleNumberPattern' => 'NA',
  ),
  'id' => 'LY',
  'countryCode' => 218,
  'internationalPrefix' => '00',
  'nationalPrefix' => '0',
  'nationalPrefixForParsing' => '0',
  'sameMobileAndFixedLinePattern' => false,
  'numberFormat' =>
  array (
    0 =>
    array (
      'pattern' => '([25679]\\d)(\\d{7})',
      'format' => '$1-$2',
      'leadingDigitsPatterns' =>
      array (
      ),
      'nationalPrefixFormattingRule' => '0$1',
      'domesticCarrierCodeFormattingRule' => '',
    ),
  ),
  'intlNumberFormat' =>
  array (
  ),
  'mainCountryForCode' => false,
  'leadingZeroPossible' => false,
  'mobileNumberPortableRegion' => false,
);
/* EOF */


text:
<?php

declare(strict_types=1);

namespace Arcanedev\LogViewer\Contracts;

/**
 * Interface  Table
 *
 * @author    ARCANEDEV <arcanedev.maroc@gmail.com>
 */
interface Table
{
    /* -----------------------------------------------------------------
     |  Getters & Setters
     | -----------------------------------------------------------------
     */

    /**
     * Get table header.
     *
     * @return array
     */
    public function header();

    /**
     * Get table rows.
     *
     * @return array
     */
    public function rows();

    /**
     * Get table footer.
     *
     * @return array
     */
    public function footer();
}


text:
"use strict"

let parallelize = require("./lib/parallelize")

var exports = module.exports = parallelize
exports.parallelize = parallelize
exports.mapreduce = parallelize // synonym


text:
DIR=$(dirname "$0")
cd "$DIR"

. ../scripts/functions.sh

SOURCE="$(realpath -m .)"
DESTINATION="$(realpath -m ~/.config/karabiner)"

info "Setting up Karabiner Elements..."

substep_info "Creating Karabiner Elements folder..."
mkdir -p $DESTINATION

find * -name "*.json" | while read fn; do
    symlink "$SOURCE/$fn" "$DESTINATION/$fn"
done
clear_broken_symlinks "$DESTINATION"

success "Finished setting up Karabiner Elements."


text:
Check your code with sniffers
=====

To check your code with sniffers use `runsniffers.sh` command whithin `/var/www/docroot` directory.
If you do not want to update software every time and save your time, plese use `-n` argument. *Note*, the first run of the command should be without any arguments to download the dependencies.
Example:
```
./runsniffers.sh -n
```


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/1998/REC-html40-19980424/loose.dtd">

<title>SMActivityFeedViewCell.h</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="generator" content="HeaderDoc">
<meta name="xcode-display" content="render">
<link rel="stylesheet" type="text/css" href="http://devdoc.sessionm.com/ios/docs.css">

<link rel="stylesheet" type="text/css" href="http://devdoc.sessionm.com/ios/docs.css">

iOS SDK Documentation

SMActivityFeedViewCell.h

Includes:

<UIKit/UIKit.h>
"SMFeedMessageData.h"

Introduction

Use the links in the table of contents to the left to access the documentation.

Classes

<tt>SMActivityFeedViewCell</tt>

A standard implementation for the table view cells in an instance of SMActivityFeedViewController.

© 2013 SessionM, Inc. Patents pending.

Last Updated: 09/12/2016