text:
<?php

declare(strict_types=1);

namespace Atk4\Ui\Tests;

use Atk4\Core\Phpunit\TestCase;
use Atk4\Ui\AbstractView;
use Atk4\Ui\App;
use Atk4\Ui\Callback;
use Atk4\Ui\CallbackLater;
use Atk4\Ui\Layout;
use Atk4\Ui\View;
use Atk4\Ui\VirtualPage;

class AppMock extends App
{
    /**
     * Overriden to allow multiple App::run() calls, prevent sending headers when headers are already sent.
     */
    protected function outputResponse(string $data, array $headers): void
    {
        echo $data;
    }
}

class CallbackTest extends TestCase
{
    /** @var string */
    private $htmlDoctypeRegex = '~^<!DOCTYPE~';

    /** @var App */
    public $app;

    protected function setUp(): void
    {
        parent::setUp();

        $this->app = new AppMock(['alwaysRun' => false, 'catchExceptions' => false]);
        $this->app->initLayout([Layout\Centered::class]);
    }

    protected function tearDown(): void
    {
        unset($_GET);
        unset($_POST);

        parent::tearDown();
    }

    /**
     * @param Callback|VirtualPage $cb
     */
    protected function simulateCallbackTriggering(AbstractView $cb): void
    {
        $_GET[Callback::URL_QUERY_TRIGGER_PREFIX . $cb->getUrlTrigger()] = '1';
    }

    public function testCallback(): void
    {
        $cb = Callback::addTo($this->app);

        $this->simulateCallbackTriggering($cb);

        $var = null;
        $cb->set(function (int $x) use (&$var) {
            $var = $x;
        }, [34]);

        static::assertSame(34, $var);
        static::assertSame('1', $cb->getTriggeredValue());
    }

    public function testCallbackTrigger(): void
    {
        $cb = Callback::addTo($this->app);
        static::assertSame($this->app->layout->name . '_' . $cb->shortName, $cb->getUrlTrigger());

        $cb = Callback::addTo($this->app, ['urlTrigger' => 'test']);
        static::assertSame('test', $cb->getUrlTrigger());
    }

    public function testViewUrlCallback(): void
    {
        $cbApp = Callback::addTo($this->app, ['urlTrigger' => 'aa']);
        $v1 = View::addTo($this->app);
        $cb = Callback::addTo($v1, ['urlTrigger' => 'bb']);

        $this->simulateCallbackTriggering($cbApp);
        $this->simulateCallbackTriggering($cb);

        $expectedUrlCbApp = '?' . Callback::URL_QUERY_TRIGGER_PREFIX . 'aa=callback&' . Callback::URL_QUERY_TARGET . '=aa';
        $expectedUrlCb = '?' . /* Callback::URL_QUERY_TRIGGER_PREFIX . 'aa=1&' . */ Callback::URL_QUERY_TRIGGER_PREFIX . 'bb=callback&' . Callback::URL_QUERY_TARGET . '=bb';
        static::assertSame($expectedUrlCbApp, $cbApp->getUrl());
        static::assertSame($expectedUrlCb, $cb->getUrl());

        // URL must remain the same when urlTrigger is set but name is changed
        $cbApp->name = 'aax';
        $cb->name = 'bbx';
        static::assertSame($expectedUrlCbApp, $cbApp->getUrl());
        static::assertSame($expectedUrlCb, $cb->getUrl());

        $var = null;
        $cb->set(function (int $x) use (&$var, $v1) {
            $v3 = View::addTo($v1);
            static::assertSame('test.php', $v3->url(['test']));
            $var = $x;
        }, [34]);

        $v2 = View::addTo($v1);
        $v2->stickyGet('g1', '1');

        static::assertSame(34, $var);
        static::assertSame('test.php?g1=1', $v2->url(['test']));
    }

    public function testCallbackNotFiring(): void
    {
        $cb = Callback::addTo($this->app);

        // do NOT simulate triggering in this test

        $var = null;
        $cb->set(function (int $x) use (&$var) {
            $var = $x;
        }, [34]);

        static::assertNull($var);
    }

    public function testCallbackLater(): void
    {
        $cb = CallbackLater::addTo($this->app);

        $this->simulateCallbackTriggering($cb);

        $var = null;
        $cb->set(function (int $x) use (&$var) {
            $var = $x;
        }, [34]);

        static::assertNull($var);

        $this->expectOutputRegex($this->htmlDoctypeRegex);
        $this->app->run();

        static::assertSame(34, $var);
    }

    public function testCallbackLaterNested(): void
    {
        $cb = CallbackLater::addTo($this->app);

        $this->simulateCallbackTriggering($cb);

        $var = null;
        $cb->set(function (int $x) use (&$var) {
            $cb2 = CallbackLater::addTo($this->app);

            $this->simulateCallbackTriggering($cb2);

            $cb2->set(function (int $y) use (&$var) {
                $var = $y;
            }, [$x]);
        }, [34]);

        static::assertNull($var);

        $this->expectOutputRegex($this->htmlDoctypeRegex);
        $this->app->run();

        static::assertSame(34, $var);
    }

    public function testCallbackLaterNotFiring(): void
    {
        $cb = CallbackLater::addTo($this->app);

        // don't simulate triggering
        $var = null;
        $cb->set(function (int $x) use (&$var) {
            $var = $x;
        }, [34]);

        static::assertNull($var);

        $this->expectOutputRegex($this->htmlDoctypeRegex);
        $this->app->run();

        static::assertNull($var); // @phpstan-ignore-line
    }

    public function testVirtualPage(): void
    {
        $vp = VirtualPage::addTo($this->app);

        $this->simulateCallbackTriggering($vp);

        $var = null;
        $vp->set(function (VirtualPage $p) use (&$var) {
            $var = 25;
        });

        $this->expectOutputRegex('~^..DOCTYPE~');
        $this->app->run();
        static::assertSame(25, $var);
    }

    public function testVirtualPageCustomTrigger(): void
    {
        $vp = VirtualPage::addTo($this->app, ['urlTrigger' => 'bah']);

        $this->simulateCallbackTriggering($vp);

        $var = null;
        $vp->set(function (VirtualPage $p) use (&$var) {
            $var = 25;
        });

        $this->expectOutputRegex('~^..DOCTYPE~');
        $this->app->run();
        static::assertSame(25, $var);
    }

    /** @var int */
    private $varPull230;

    public function testPull230(): void
    {
        $vp = VirtualPage::addTo($this->app);

        $this->simulateCallbackTriggering($vp);

        $vp->set(function () {
            $this->varPull230 = 26;
        });

        $this->expectOutputRegex('~^..DOCTYPE~');
        $this->app->run();
        static::assertSame(26, $this->varPull230);
    }
}


text:
<?php

namespace yii\db;

use yii\base\Component;
use yii\base\InvalidConfigException;
use yii\base\NotSupportedException;
use yii\caching\Cache;

/**
 * Connection represents a connection to a database via [PDO](http://www.php.net/manual/en/ref.pdo.php).
 *
 * Connection works together with [[Command]], [[DataReader]] and [[Transaction]]
 * to provide data access to various DBMS in a common set of APIs. They are a thin wrapper
 * of the [[PDO PHP extension]](http://www.php.net/manual/en/ref.pdo.php).
 *
 * To establish a DB connection, set [[dsn]], [[username]] and [[password]], and then
 * call [[open()]] to be true.
 *
 * The following example shows how to create a Connection instance and establish
 * the DB connection:
 *
 * ~~~
 * $connection = new \yii\db\Connection(array(
 *     'dsn' => $dsn,
 *     'username' => $username,
 *     'password' => $password,
 * ));
 * $connection->open();
 * ~~~
 *
 * After the DB connection is established, one can execute SQL statements like the following:
 *
 * ~~~
 * $command = $connection->createCommand('SELECT * FROM tbl_post');
 * $posts = $command->queryAll();
 * $command = $connection->createCommand('UPDATE tbl_post SET status=1');
 * $command->execute();
 * ~~~
 *
 * One can also do prepared SQL execution and bind parameters to the prepared SQL.
 * When the parameters are coming from user input, you should use this approach
 * to prevent SQL injection attacks. The following is an example:
 *
 * ~~~
 * $command = $connection->createCommand('SELECT * FROM tbl_post WHERE id=:id');
 * $command->bindValue(':id', $_GET['id']);
 * $post = $command->query();
 * ~~~
 *
 * For more information about how to perform various DB queries, please refer to [[Command]].
 *
 * If the underlying DBMS supports transactions, you can perform transactional SQL queries
 * like the following:
 *
 * ~~~
 * $transaction = $connection->beginTransaction();
 * try {
 *     $connection->createCommand($sql1)->execute();
 *     $connection->createCommand($sql2)->execute();
 *     // ... executing other SQL statements ...
 *     $transaction->commit();
 * } catch(Exception $e) {
 *     $transaction->rollback();
 * }
 * ~~~
 *
 * Connection is often used as an application component and configured in the application
 * configuration like the following:
 *
 * ~~~
 * array(
 *	 'components' => array(
 *		 'db' => array(
 *			 'class' => '\yii\db\Connection',
 *			 'dsn' => 'mysql:host=127.0.0.1;dbname=demo',
 *			 'username' => 'root',
 *			 'password' => '',
 *			 'charset' => 'utf8',
 *		 ),
 *	 ),
 * )
 * ~~~
 *
 * @property boolean $isActive Whether the DB connection is established. This property is read-only.
 * @property Transaction $transaction The currently active transaction. Null if no active transaction.
 * @property Schema $schema The database schema information for the current connection.
 * @property QueryBuilder $queryBuilder The query builder.
 * @property string $lastInsertID The row ID of the last row inserted, or the last value retrieved from the sequence object.
 * @property string $driverName Name of the DB driver currently being used.
 * @property array $querySummary The statistical results of SQL queries.
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class Connection extends Component
{
	/**
	 * @event Event an event that is triggered after a DB connection is established
	 */
	const EVENT_AFTER_OPEN = 'afterOpen';

	/**
	 * @var string the Data Source Name, or DSN, contains the information required to connect to the database.
	 * Please refer to the [PHP manual](http://www.php.net/manual/en/function.PDO-construct.php) on
	 * the format of the DSN string.
	 * @see charset
	 */
	public $dsn;
	/**
	 * @var string the username for establishing DB connection. Defaults to empty string.
	 */
	public $username = '';
	/**
	 * @var string the password for establishing DB connection. Defaults to empty string.
	 */
	public $password = '';
	/**
	 * @var array PDO attributes (name=>value) that should be set when calling [[open()]]
	 * to establish a DB connection. Please refer to the
	 * [PHP manual](http://www.php.net/manual/en/function.PDO-setAttribute.php) for
	 * details about available attributes.
	 */
	public $attributes;
	/**
	 * @var \PDO the PHP PDO instance associated with this DB connection.
	 * This property is mainly managed by [[open()]] and [[close()]] methods.
	 * When a DB connection is active, this property will represent a PDO instance;
	 * otherwise, it will be null.
	 */
	public $pdo;
	/**
	 * @var boolean whether to enable schema caching.
	 * Note that in order to enable truly schema caching, a valid cache component as specified
	 * by [[schemaCache]] must be enabled and [[enableSchemaCache]] must be set true.
	 * @see schemaCacheDuration
	 * @see schemaCacheExclude
	 * @see schemaCache
	 */
	public $enableSchemaCache = false;
	/**
	 * @var integer number of seconds that table metadata can remain valid in cache.
	 * Use 0 to indicate that the cached data will never expire.
	 * @see enableSchemaCache
	 */
	public $schemaCacheDuration = 3600;
	/**
	 * @var array list of tables whose metadata should NOT be cached. Defaults to empty array.
	 * The table names may contain schema prefix, if any. Do not quote the table names.
	 * @see enableSchemaCache
	 */
	public $schemaCacheExclude = array();
	/**
	 * @var Cache|string the cache object or the ID of the cache application component that
	 * is used to cache the table metadata.
	 * @see enableSchemaCache
	 */
	public $schemaCache = 'cache';
	/**
	 * @var boolean whether to enable query caching.
	 * Note that in order to enable query caching, a valid cache component as specified
	 * by [[queryCache]] must be enabled and [[enableQueryCache]] must be set true.
	 *
	 * Methods [[beginCache()]] and [[endCache()]] can be used as shortcuts to turn on
	 * and off query caching on the fly.
	 * @see queryCacheDuration
	 * @see queryCache
	 * @see queryCacheDependency
	 * @see beginCache()
	 * @see endCache()
	 */
	public $enableQueryCache = false;
	/**
	 * @var integer number of seconds that query results can remain valid in cache.
	 * Defaults to 3600, meaning 3600 seconds, or one hour.
	 * Use 0 to indicate that the cached data will never expire.
	 * @see enableQueryCache
	 */
	public $queryCacheDuration = 3600;
	/**
	 * @var \yii\caching\Dependency the dependency that will be used when saving query results into cache.
	 * Defaults to null, meaning no dependency.
	 * @see enableQueryCache
	 */
	public $queryCacheDependency;
	/**
	 * @var Cache|string the cache object or the ID of the cache application component
	 * that is used for query caching.
	 * @see enableQueryCache
	 */
	public $queryCache = 'cache';
	/**
	 * @var string the charset used for database connection. The property is only used
	 * for MySQL and PostgreSQL databases. Defaults to null, meaning using default charset
	 * as specified by the database.
	 *
	 * Note that if you're using GBK or BIG5 then it's highly recommended to
	 * update to PHP 5.3.6+ and to specify charset via DSN like
	 * 'mysql:dbname=mydatabase;host=127.0.0.1;charset=GBK;'.
	 */
	public $charset;
	/**
	 * @var boolean whether to turn on prepare emulation. Defaults to false, meaning PDO
	 * will use the native prepare support if available. For some databases (such as MySQL),
	 * this may need to be set true so that PDO can emulate the prepare support to bypass
	 * the buggy native prepare support.
	 * The default value is null, which means the PDO ATTR_EMULATE_PREPARES value will not be changed.
	 */
	public $emulatePrepare;
	/**
	 * @var boolean whether to enable profiling for the SQL statements being executed.
	 * Defaults to false. This should be mainly enabled and used during development
	 * to find out the bottleneck of SQL executions.
	 * @see getStats
	 */
	public $enableProfiling = false;
	/**
	 * @var string the common prefix or suffix for table names. If a table name is given
	 * as `{{%TableName}}`, then the percentage character `%` will be replaced with this
	 * property value. For example, `{{%post}}` becomes `{{tbl_post}}` if this property is
	 * set as `"tbl_"`.
	 */
	public $tablePrefix;
	/**
	 * @var array mapping between PDO driver names and [[Schema]] classes.
	 * The keys of the array are PDO driver names while the values the corresponding
	 * schema class name or configuration. Please refer to [[\Yii::createObject()]] for
	 * details on how to specify a configuration.
	 *
	 * This property is mainly used by [[getSchema()]] when fetching the database schema information.
	 * You normally do not need to set this property unless you want to use your own
	 * [[Schema]] class to support DBMS that is not supported by Yii.
	 */
	public $schemaMap = array(
		'pgsql' => 'yii\db\pgsql\Schema',    // PostgreSQL
		'mysqli' => 'yii\db\mysql\Schema',   // MySQL
		'mysql' => 'yii\db\mysql\Schema',    // MySQL
		'sqlite' => 'yii\db\sqlite\Schema',  // sqlite 3
		'sqlite2' => 'yii\db\sqlite\Schema', // sqlite 2
		'mssql' => 'yii\db\dao\mssql\Schema', // Mssql driver on windows hosts
		'sqlsrv' => 'yii\db\mssql\Schema',   // Mssql
		'oci' => 'yii\db\oci\Schema',        // Oracle driver
		'dblib' => 'yii\db\mssql\Schema',    // dblib drivers on linux (and maybe others os) hosts
	);
	/**
	 * @var Transaction the currently active transaction
	 */
	private $_transaction;
	/**
	 * @var Schema the database schema
	 */
	private $_schema;

	/**
	 * Closes the connection when this component is being serialized.
	 * @return array
	 */
	public function __sleep()
	{
		$this->close();
		return array_keys(get_object_vars($this));
	}

	/**
	 * Returns a value indicating whether the DB connection is established.
	 * @return boolean whether the DB connection is established
	 */
	public function getIsActive()
	{
		return $this->pdo !== null;
	}

	/**
	 * Turns on query caching.
	 * This method is provided as a shortcut to setting two properties that are related
	 * with query caching: [[queryCacheDuration]] and [[queryCacheDependency]].
	 * @param integer $duration the number of seconds that query results may remain valid in cache.
	 * If not set, it will use the value of [[queryCacheDuration]]. See [[queryCacheDuration]] for more details.
	 * @param \yii\caching\Dependency $dependency the dependency for the cached query result.
	 * See [[queryCacheDependency]] for more details.
	 */
	public function beginCache($duration = null, $dependency = null)
	{
		$this->enableQueryCache = true;
		if ($duration !== null) {
			$this->queryCacheDuration = $duration;
		}
		$this->queryCacheDependency = $dependency;
	}

	/**
	 * Turns off query caching.
	 */
	public function endCache()
	{
		$this->enableQueryCache = false;
	}

	/**
	 * Establishes a DB connection.
	 * It does nothing if a DB connection has already been established.
	 * @throws Exception if connection fails
	 */
	public function open()
	{
		if ($this->pdo === null) {
			if (empty($this->dsn)) {
				throw new InvalidConfigException('Connection::dsn cannot be empty.');
			}
			try {
				\Yii::trace('Opening DB connection: ' . $this->dsn, __METHOD__);
				$this->pdo = $this->createPdoInstance();
				$this->initConnection();
			}
			catch (\PDOException $e) {
				\Yii::error("Failed to open DB connection ({$this->dsn}): " . $e->getMessage(), __METHOD__);
				$message = YII_DEBUG ? 'Failed to open DB connection: ' . $e->getMessage() : 'Failed to open DB connection.';
				throw new Exception($message, $e->errorInfo, (int)$e->getCode());
			}
		}
	}

	/**
	 * Closes the currently active DB connection.
	 * It does nothing if the connection is already closed.
	 */
	public function close()
	{
		if ($this->pdo !== null) {
			\Yii::trace('Closing DB connection: ' . $this->dsn, __METHOD__);
			$this->pdo = null;
			$this->_schema = null;
			$this->_transaction = null;
		}
	}

	/**
	 * Creates the PDO instance.
	 * This method is called by [[open]] to establish a DB connection.
	 * The default implementation will create a PHP PDO instance.
	 * You may override this method if the default PDO needs to be adapted for certain DBMS.
	 * @return \PDO the pdo instance
	 */
	protected function createPdoInstance()
	{
		$pdoClass = '\PDO';
		if (($pos = strpos($this->dsn, ':')) !== false) {
			$driver = strtolower(substr($this->dsn, 0, $pos));
			if ($driver === 'mssql' || $driver === 'dblib' || $driver === 'sqlsrv') {
				$pdoClass = 'yii\db\mssql\PDO';
			}
		}
		return new $pdoClass($this->dsn, $this->username, $this->password, $this->attributes);
	}

	/**
	 * Initializes the DB connection.
	 * This method is invoked right after the DB connection is established.
	 * The default implementation turns on `PDO::ATTR_EMULATE_PREPARES`
	 * if [[emulatePrepare]] is true, and sets the database [[charset]] if it is not empty.
	 * It then triggers an [[EVENT_AFTER_OPEN]] event.
	 */
	protected function initConnection()
	{
		$this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
		if ($this->emulatePrepare !== null && constant('\PDO::ATTR_EMULATE_PREPARES')) {
			$this->pdo->setAttribute(\PDO::ATTR_EMULATE_PREPARES, $this->emulatePrepare);
		}
		if ($this->charset !== null && in_array($this->getDriverName(), array('pgsql', 'mysql', 'mysqli'))) {
			$this->pdo->exec('SET NAMES ' . $this->pdo->quote($this->charset));
		}
		$this->trigger(self::EVENT_AFTER_OPEN);
	}

	/**
	 * Creates a command for execution.
	 * @param string $sql the SQL statement to be executed
	 * @param array $params the parameters to be bound to the SQL statement
	 * @return Command the DB command
	 */
	public function createCommand($sql = null, $params = array())
	{
		$this->open();
		$command = new Command(array(
			'db' => $this,
			'sql' => $sql,
		));
		return $command->bindValues($params);
	}

	/**
	 * Returns the currently active transaction.
	 * @return Transaction the currently active transaction. Null if no active transaction.
	 */
	public function getTransaction()
	{
		return $this->_transaction && $this->_transaction->isActive ? $this->_transaction : null;
	}

	/**
	 * Starts a transaction.
	 * @return Transaction the transaction initiated
	 */
	public function beginTransaction()
	{
		$this->open();
		$this->_transaction = new Transaction(array(
			'db' => $this,
		));
		$this->_transaction->begin();
		return $this->_transaction;
	}

	/**
	 * Returns the schema information for the database opened by this connection.
	 * @return Schema the schema information for the database opened by this connection.
	 * @throws NotSupportedException if there is no support for the current driver type
	 */
	public function getSchema()
	{
		if ($this->_schema !== null) {
			return $this->_schema;
		} else {
			$driver = $this->getDriverName();
			if (isset($this->schemaMap[$driver])) {
				$this->_schema = \Yii::createObject($this->schemaMap[$driver]);
				$this->_schema->db = $this;
				return $this->_schema;
			} else {
				throw new NotSupportedException("Connection does not support reading schema information for '$driver' DBMS.");
			}
		}
	}

	/**
	 * Returns the query builder for the current DB connection.
	 * @return QueryBuilder the query builder for the current DB connection.
	 */
	public function getQueryBuilder()
	{
		return $this->getSchema()->getQueryBuilder();
	}

	/**
	 * Obtains the schema information for the named table.
	 * @param string $name table name.
	 * @param boolean $refresh whether to reload the table schema even if it is found in the cache.
	 * @return TableSchema table schema information. Null if the named table does not exist.
	 */
	public function getTableSchema($name, $refresh = false)
	{
		return $this->getSchema()->getTableSchema($name, $refresh);
	}

	/**
	 * Returns the ID of the last inserted row or sequence value.
	 * @param string $sequenceName name of the sequence object (required by some DBMS)
	 * @return string the row ID of the last row inserted, or the last value retrieved from the sequence object
	 * @see http://www.php.net/manual/en/function.PDO-lastInsertId.php
	 */
	public function getLastInsertID($sequenceName = '')
	{
		return $this->getSchema()->getLastInsertID($sequenceName);
	}

	/**
	 * Quotes a string value for use in a query.
	 * Note that if the parameter is not a string, it will be returned without change.
	 * @param string $str string to be quoted
	 * @return string the properly quoted string
	 * @see http://www.php.net/manual/en/function.PDO-quote.php
	 */
	public function quoteValue($str)
	{
		return $this->getSchema()->quoteValue($str);
	}

	/**
	 * Quotes a table name for use in a query.
	 * If the table name contains schema prefix, the prefix will also be properly quoted.
	 * If the table name is already quoted or contains special characters including '(', '[[' and '{{',
	 * then this method will do nothing.
	 * @param string $name table name
	 * @return string the properly quoted table name
	 */
	public function quoteTableName($name)
	{
		return $this->getSchema()->quoteTableName($name);
	}

	/**
	 * Quotes a column name for use in a query.
	 * If the column name contains prefix, the prefix will also be properly quoted.
	 * If the column name is already quoted or contains special characters including '(', '[[' and '{{',
	 * then this method will do nothing.
	 * @param string $name column name
	 * @return string the properly quoted column name
	 */
	public function quoteColumnName($name)
	{
		return $this->getSchema()->quoteColumnName($name);
	}

	/**
	 * Processes a SQL statement by quoting table and column names that are enclosed within double brackets.
	 * Tokens enclosed within double curly brackets are treated as table names, while
	 * tokens enclosed within double square brackets are column names. They will be quoted accordingly.
	 * Also, the percentage character "%" in a table name will be replaced with [[tablePrefix]].
	 * @param string $sql the SQL to be quoted
	 * @return string the quoted SQL
	 */
	public function quoteSql($sql)
	{
		$db = $this;
		return preg_replace_callback('/(\\{\\{([%\w\-\. ]+)\\}\\}|\\[\\[([\w\-\. ]+)\\]\\])/',
			function($matches) use($db) {
				if (isset($matches[3])) {
					return $db->quoteColumnName($matches[3]);
				} else {
					return str_replace('%', $db->tablePrefix, $db->quoteTableName($matches[2]));
				}
			}, $sql);
	}

	/**
	 * Returns the name of the DB driver for the current [[dsn]].
	 * @return string name of the DB driver
	 */
	public function getDriverName()
	{
		if (($pos = strpos($this->dsn, ':')) !== false) {
			return strtolower(substr($this->dsn, 0, $pos));
		} else {
			return strtolower($this->pdo->getAttribute(\PDO::ATTR_DRIVER_NAME));
		}
	}

	/**
	 * Returns the statistical results of SQL queries.
	 * The results returned include the number of SQL statements executed and
	 * the total time spent.
	 * In order to use this method, [[enableProfiling]] has to be set true.
	 * @return array the first element indicates the number of SQL statements executed,
	 * and the second element the total time spent in SQL execution.
	 * @see \yii\logging\Logger::getProfiling()
	 */
	public function getQuerySummary()
	{
		$logger = \Yii::getLogger();
		$timings = $logger->getProfiling(array('yii\db\Command::query', 'yii\db\Command::execute'));
		$count = count($timings);
		$time = 0;
		foreach ($timings as $timing) {
			$time += $timing[1];
		}
		return array($count, $time);
	}
}

redpajama_set_name: RedPajamaGithub


text:
@interface YFViewController : UIViewController

@end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Schulzeria pellucida Massee

### Remarks
null


text:
<?PHP

class Application_Service_Paginator_Adapter_Category_All
    extends Application_Service_Paginator_Adapter_Category_Abstract {

    public function __construct($order='name') {
        $select = Zend_Db_Table::getDefaultAdapter()->select();
        $select->from(
                array('categories'),
                array('*')
        );

        switch($order) {
            case 'name':
                $select->order('name asc');
                break;
            default:
                $select->order('name asc');
                break;
        }
        parent::__construct($select);
    }

}


text:
<?php

namespace App\Presenters;

use Nette;
use App\Model;
use Tracy\ILogger;

class ErrorPresenter extends BasePresenter
{
	/** @var ILogger */
	private $logger;

	public function __construct(ILogger $logger)
	{
		$this->logger = $logger;
	}

	/**
	 * @param  Exception
	 * @return void
	 */
	public function renderDefault($exception)
	{
		if ($exception instanceof Nette\Application\BadRequestException) {
			$code = $exception->getCode();
			// load template 403.latte or 404.latte or ... 4xx.latte
			$this->setView(in_array($code, array(403, 404, 405, 410, 500)) ? $code : '4xx');
			// log to access.log
			$this->logger->log("HTTP code $code: {$exception->getMessage()} in {$exception->getFile()}:{$exception->getLine()}", 'access');

		} else {
			$this->setView('500'); // load template 500.latte
			$this->logger->log($exception, ILogger::EXCEPTION); // and log exception
		}

		if ($this->isAjax()) { // AJAX request? Note this error in payload.
			$this->payload->error = TRUE;
			$this->terminate();
		}
	}

}


text:
pip install mypy==0.641

python -m unittest test.all_tests

cmd /c mypy -p tutorial
cmd /c mypy -p test


text:
<link rel="import" href="../../bower_components/polymer/polymer.html"/>
<link rel="import" href="../shared/fonts/fonts.html"/>
<link rel="import" href="../shared/js/colors.html"/>
<link rel="import" href="../shared/js/rectangle.html">
<link rel="import" href="../shared/js/measure.html"/>
<link rel="import" href="../shared/js/behaviorutils.html"/>
<link rel="import" href="../shared/behaviors/positionable-dropdown.html"/>
<link rel="import" href="../shared/behaviors/autoclosable.html"/>
<link rel="import" href="../shared/behaviors/autotogglable.html"/>
<link rel="import" href="../shared/behaviors/jqueryable.html"/>
<link rel="import" href="../shared/behaviors/keyselectable.html"/>
<link rel="import" href="../shared/behaviors/stackable.html">
<link rel="import" href="../shared/behaviors/stylable.html"/>
<link rel="import" href="../shared/behaviors/resolvable.html"/>
<link rel="import" href="../strand-item-recycler/strand-item-recycler.html">
<link rel="import" href="../strand-icon/strand-icon.html"/>
<link rel="import" href="../strand-list-item/strand-list-item.html"/>
<link rel="import" href="../strand-highlight/strand-highlight.html"/>
<link rel="import" href="../shared/behaviors/refable.html"/>

<dom-module id="strand-dropdown">
	<link href="strand-dropdown.css" rel="import" type="css"/>
	<template>

				<content select="strand-icon" id="icon"></content>
				{{_updateLabelText(selectedIndex, placeholder)}}

			<template is="dom-if" if="{{!isLoading}}">
				<strand-icon id="caratIcon" class$="{{state}}" type="carat" width="8" height="8"></strand-icon>
			</template>
			<template is="dom-if" if="{{isLoading}}">
				<strand-spinner id="spinner" fill-color="#333333" radius="8"></strand-spinner>
			</template>

				<content hidden$="{{_hideInsertionPoints(data)}}" id="search" select="strand-input"></content>

					<content hidden$="{{_hideInsertionPoints(data)}}" id="content" select="strand-list-item"></content>
					<strand-item-recycler
						id="itemRecycler"
						data="{{data}}"
						hidden$="{{!_hideInsertionPoints(data)}}"
						scope="{{ref}}"
						index="{{index}}">
						<template preserve-content>
							<strand-list-item
								value$="{{model.value}}"
								_keyselectable
								selected$="{{model.selected}}"
								highlighted$="{{model.highlighted}}">
									<strand-highlight
										text="{{model.name}}"
										highlight="{{scope.highlight}}">
									</strand-highlight>
								</strand-list-item>
						</template>
					</strand-item-recycler>

	</template>
</dom-module>


text:
<?xml version="1.0" encoding="UTF-8" ?>

<container xmlns="http://symfony.com/schema/dic/services"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <services>

        <service id="sonata.admin.manager.orm" class="Sonata\AdminBundle\Model\ORM\ModelManager">
            <argument type="service" id="doctrine.orm.default_entity_manager" />
        </service>

        <!-- FormBuilder -->
        <service id="sonata.admin.builder.orm_form" class="Sonata\AdminBundle\Builder\ORM\FormContractor">
            <argument type="service" id="form.factory" />
        </service>

        <!-- ListBuilder -->
        <service id="sonata.admin.builder.orm_list" class="Sonata\AdminBundle\Builder\ORM\ListBuilder" >
            <argument type="service" id="sonata.admin.guesser.orm_list_chain" />
        </service>

        <service id="sonata.admin.guesser.orm_list" class="Sonata\AdminBundle\Guesser\ORM\TypeGuesser">
            <argument type="service" id="doctrine" />
            <tag name="sonata.admin.guesser.orm_list" />
        </service>

        <service id="sonata.admin.guesser.orm_list_chain" class="Sonata\AdminBundle\Guesser\TypeGuesserChain">
            <argument />
        </service>

        <!-- ShowBuilder  -->
        <service id="sonata.admin.builder.orm_show" class="Sonata\AdminBundle\Builder\ORM\ShowBuilder" >
            <argument type="service" id="sonata.admin.guesser.orm_show_chain" />
        </service>

        <service id="sonata.admin.guesser.orm_show" class="Sonata\AdminBundle\Guesser\ORM\TypeGuesser">
            <argument type="service" id="doctrine" />
            <tag name="sonata.admin.guesser.orm_show" />
        </service>

        <service id="sonata.admin.guesser.orm_show_chain" class="Sonata\AdminBundle\Guesser\TypeGuesserChain">
            <argument />
        </service>

        <!-- DatagridBuilder guesser -->
        <service id="sonata.admin.builder.orm_datagrid" class="Sonata\AdminBundle\Builder\ORM\DatagridBuilder">
            <argument type="service" id="form.factory" />
            <argument type="service" id="sonata.admin.guesser.orm_datagrid_chain" />
        </service>

        <service id="sonata.admin.guesser.orm_datagrid" class="Sonata\AdminBundle\Guesser\ORM\TypeGuesser">
            <argument type="service" id="doctrine" />
            <tag name="sonata.admin.guesser.orm_datagrid" />
        </service>

        <service id="sonata.admin.guesser.orm_datagrid_chain" class="Sonata\AdminBundle\Guesser\TypeGuesserChain">
            <argument />
        </service>
    </services>
</container>


text:
title: Shell command useful for data exploration
excerpt: "Introduce head/tail, more, grep, cut, wc, sort, uniq for basic data exploration."
tags: [command line, data exploration, encoding]
comments: true
date: 2015-05-17T20:32:38+08:00
---

Shell command is very useful for initial exploratory analysis of data files.
A simple `head` would allow explore the content of a huge file and It is much faster than firing up an editor.  With so many different tools around for data analysis, I believed that command prompt one-liner could be one of the most understated tools.

{% include toc %}

## Looking at the first/last lines of a file

`Head / tail` views the first / last lines of a file.
{% highlight bash %}
# Print the first 10 lines
head -n10 test.csv
# Print the last 10 lines
tail -n10 test.csv
{% endhighlight %}

`More / less` allows one's to inspect a file quickly.  It is much quicker than firing up a text editor.
{% highlight bash %}
# More allows scrolling forward only.
more test.csv
# Less allows scrolling in either directions and has a lot more features.
less test.csv
{% endhighlight %}

A combination of these tools can be quite powerful in navigating large files.

{% highlight bash %}
# Explore the last 1000 lines of test.csv interactively.
tail -n1000 test.csv | less
{% endhighlight %}

## Watch the latest lines in a log file
Very often we would like to look at a log file while another program is continously outputting messages to it.

{% highlight bash %}
tail -f everIncreasing.log
{% endhighlight %}

By adding the `-f` flag, tail will keep monitoring the file and show you the latest changes.

## Basic data munging

### Grep unique id's
`Grep` searches for a certain regular expression pattern and prints the line(s) matching the expression.
For example, searching for Chris within a text file would be:
{% highlight bash %}
grep Apple input.csv
{% endhighlight %}

One can then easily pipe the output to `wc` to count the number of matching lines.
{% highlight bash %}
grep Apple input.csv | wc -l
{% endhighlight %}

### Obtain the unique entries of a column

To obtain the unique entires in a column of a csv file, first we would like to obtain the column by `cut`.  Then, `sort` its output and count the unique entries with `uniq`.
{% highlight bash %}
<input.csv cut -d, -f1 | sort | uniq -c
{% endhighlight %}

## CSV files cleansing

I have once handled a csv file that has an extra comma at the end of every line.
Because of this extra comma, it could not be read by pandas/R.
This seems a be a task prefectly handled by `sed`.
{% highlight bash %}
sed s/,$// wrongcomma.csv > cleanFile.csv
{% endhighlight %}

However, the regular expression fails to match any of the expected string.
It turns out that the line ending must be unix for `grep` to work.
It can be easily converted by the command dos2unix.
{% highlight bash %}
<wrongcomma.csv dos2unix | sed s/,$// wrongcomma.csv > cleanFile.csv
{% endhighlight %}

## Encoding

Another common problem with non English file is encoding.
I have handled a lot of data with simplified Chinese character.
{% highlight bash %}
# Convert from gb2312 to utf8 encoding
iconv -f gb2312 -t utf8 myfile.csv > correct.csv
{% endhighlight %}

## Further reading
Greg Reda shared his experience with unix commands for data science.
<http://www.gregreda.com/2013/07/15/unix-commands-for-data-science/>

Jeroen introduced a few more tools for data science in the following post.
I personally find that [jq](http://stedolan.github.io/jq/) and [csvkit](https://csvkit.readthedocs.org/en/0.9.1/) introduced in the post are very useful tools introduced in this article very useful for command line data exploration.  Also check out his book "Data Science at the Command Line".
<http://jeroenjanssens.com/2013/09/19/seven-command-line-tools-for-data-science.html>


text:
package com.laytonsmith.abstraction.bukkit;

import com.laytonsmith.PureUtilities.Common.ReflectionUtils;
import com.laytonsmith.PureUtilities.DaemonManager;
import com.laytonsmith.abstraction.AbstractConvertor;
import com.laytonsmith.abstraction.ConvertorHelper;
import com.laytonsmith.abstraction.Implementation;
import com.laytonsmith.abstraction.MCColor;
import com.laytonsmith.abstraction.MCCommand;
import com.laytonsmith.abstraction.MCCommandSender;
import com.laytonsmith.abstraction.MCEnchantment;
import com.laytonsmith.abstraction.MCEntity;
import com.laytonsmith.abstraction.MCFireworkBuilder;
import com.laytonsmith.abstraction.MCInventory;
import com.laytonsmith.abstraction.MCItemMeta;
import com.laytonsmith.abstraction.MCItemStack;
import com.laytonsmith.abstraction.MCLocation;
import com.laytonsmith.abstraction.MCMetadataValue;
import com.laytonsmith.abstraction.MCNote;
import com.laytonsmith.abstraction.MCPattern;
import com.laytonsmith.abstraction.MCPlugin;
import com.laytonsmith.abstraction.MCPluginMeta;
import com.laytonsmith.abstraction.MCRecipe;
import com.laytonsmith.abstraction.MCServer;
import com.laytonsmith.abstraction.MCWorld;
import com.laytonsmith.abstraction.MCWorldCreator;
import com.laytonsmith.abstraction.blocks.MCMaterial;
import com.laytonsmith.abstraction.bukkit.blocks.BukkitMCMaterial;
import com.laytonsmith.abstraction.bukkit.entities.BukkitMCAgeable;
import com.laytonsmith.abstraction.bukkit.entities.BukkitMCComplexEntityPart;
import com.laytonsmith.abstraction.bukkit.entities.BukkitMCComplexLivingEntity;
import com.laytonsmith.abstraction.bukkit.entities.BukkitMCEntity;
import com.laytonsmith.abstraction.bukkit.entities.BukkitMCHanging;
import com.laytonsmith.abstraction.bukkit.entities.BukkitMCHumanEntity;
import com.laytonsmith.abstraction.bukkit.entities.BukkitMCLivingEntity;
import com.laytonsmith.abstraction.bukkit.entities.BukkitMCMinecart;
import com.laytonsmith.abstraction.bukkit.entities.BukkitMCPlayer;
import com.laytonsmith.abstraction.bukkit.entities.BukkitMCProjectile;
import com.laytonsmith.abstraction.bukkit.entities.BukkitMCTameable;
import com.laytonsmith.abstraction.bukkit.entities.BukkitMCVehicle;
import com.laytonsmith.abstraction.bukkit.events.BukkitAbstractEventMixin;
import com.laytonsmith.abstraction.bukkit.events.drivers.BukkitBlockListener;
import com.laytonsmith.abstraction.bukkit.events.drivers.BukkitEntityListener;
import com.laytonsmith.abstraction.bukkit.events.drivers.BukkitInventoryListener;
import com.laytonsmith.abstraction.bukkit.events.drivers.BukkitPlayerListener;
import com.laytonsmith.abstraction.bukkit.events.drivers.BukkitServerListener;
import com.laytonsmith.abstraction.bukkit.events.drivers.BukkitVehicleListener;
import com.laytonsmith.abstraction.bukkit.events.drivers.BukkitWeatherListener;
import com.laytonsmith.abstraction.bukkit.events.drivers.BukkitWorldListener;
import com.laytonsmith.abstraction.enums.MCDyeColor;
import com.laytonsmith.abstraction.enums.MCEntityType;
import com.laytonsmith.abstraction.enums.MCPatternShape;
import com.laytonsmith.abstraction.enums.MCRecipeType;
import com.laytonsmith.abstraction.enums.MCTone;
import com.laytonsmith.abstraction.enums.MCVersion;
import com.laytonsmith.abstraction.enums.bukkit.BukkitMCDyeColor;
import com.laytonsmith.abstraction.enums.bukkit.BukkitMCEntityType;
import com.laytonsmith.abstraction.enums.bukkit.BukkitMCPatternShape;
import com.laytonsmith.annotations.convert;
import com.laytonsmith.commandhelper.CommandHelperPlugin;
import com.laytonsmith.core.CHLog;
import com.laytonsmith.core.LogLevel;
import com.laytonsmith.core.Static;
import com.laytonsmith.core.constructs.Target;
import com.laytonsmith.core.environments.CommandHelperEnvironment;
import com.laytonsmith.core.environments.Environment;
import com.laytonsmith.core.functions.Exceptions;
import org.bukkit.Bukkit;
import org.bukkit.Color;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.DoubleChest;
import org.bukkit.block.banner.Pattern;
import org.bukkit.command.BlockCommandSender;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Ageable;
import org.bukkit.entity.ComplexEntityPart;
import org.bukkit.entity.ComplexLivingEntity;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Hanging;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Minecart;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.entity.Tameable;
import org.bukkit.entity.Vehicle;
import org.bukkit.event.Listener;
import org.bukkit.inventory.FurnaceRecipe;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.Recipe;
import org.bukkit.inventory.ShapedRecipe;
import org.bukkit.inventory.ShapelessRecipe;
import org.bukkit.inventory.meta.BannerMeta;
import org.bukkit.inventory.meta.BookMeta;
import org.bukkit.inventory.meta.EnchantmentStorageMeta;
import org.bukkit.inventory.meta.FireworkMeta;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.LeatherArmorMeta;
import org.bukkit.inventory.meta.PotionMeta;
import org.bukkit.inventory.meta.SkullMeta;
import org.bukkit.material.MaterialData;
import org.bukkit.metadata.FixedMetadataValue;
import org.yaml.snakeyaml.Yaml;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.logging.Level;

/**
 *
 *
 */
@convert(type = Implementation.Type.BUKKIT)
public class BukkitConvertor extends AbstractConvertor {

	private static BukkitMCPluginMeta pluginMeta = null;

	@Override
	public MCLocation GetLocation(MCWorld w, double x, double y, double z, float yaw, float pitch) {
		World w2 = null;
		if (w != null) {
			w2 = ((BukkitMCWorld) w).__World();
		}
		return new BukkitMCLocation(new Location(w2, x, y, z, yaw, pitch));
	}

	@Override
	public Class GetServerEventMixin() {
		return BukkitAbstractEventMixin.class;
	}

	@Override
	public MCEnchantment[] GetEnchantmentValues() {
		MCEnchantment[] ea = new MCEnchantment[Enchantment.values().length];
		Enchantment[] oea = Enchantment.values();
		for (int i = 0; i < ea.length; i++) {
			ea[i] = new BukkitMCEnchantment(oea[i]);
		}
		return ea;

	}

	@Override
	public MCEnchantment GetEnchantmentByName(String name) {
		try {
			//If they are looking it up by number, we can support that
			int i = Integer.valueOf(name);
			return new BukkitMCEnchantment(Enchantment.getById(i));
		} catch (NumberFormatException e) {
			try {
				return new BukkitMCEnchantment(Enchantment.getByName(name));
			} catch (NullPointerException ee) {
				return null;
			}
		} catch(NullPointerException e) {
			return null;
		}
	}

	@Override
	public MCServer GetServer() {
		return BukkitMCServer.Get();
	}

	@Override
	public MCMaterial getMaterial(int id) {
		Material mat = Material.getMaterial(id);
		return mat == null ? null : new BukkitMCMaterial(mat);
	}

	@Override
	public MCItemStack GetItemStack(int type, int qty) {
		return new BukkitMCItemStack(new ItemStack(type, qty));
	}

	@Override
	public MCItemStack GetItemStack(int type, int data, int qty) {
		return new BukkitMCItemStack(new ItemStack(type, qty, (short) data));
	}

	@Override
	public MCItemStack GetItemStack(MCMaterial type, int qty) {
		return new BukkitMCItemStack(new ItemStack(((BukkitMCMaterial) type).getHandle(), qty));
	}

	@Override
	public MCItemStack GetItemStack(MCMaterial type, int data, int qty) {
		return new BukkitMCItemStack(new ItemStack(((BukkitMCMaterial) type).getHandle(), qty, (short) data));
	}

	public MCItemStack GetItemStack(String type, int qty) {
		Material mat = Material.matchMaterial(type);
		if (mat == null) {
			return null;
		}
		return new BukkitMCItemStack(new ItemStack(mat, qty));
	}

	public MCItemStack GetItemStack(String type, int data, int qty) {
		Material mat = Material.matchMaterial(type);
		if (mat == null) {
			return null;
		}
		return new BukkitMCItemStack(new ItemStack(mat, qty, (short) data));
	}

	@Override
	public MCMetadataValue GetMetadataValue(Object value, MCPlugin plugin) {
		return new BukkitMCMetadataValue(new FixedMetadataValue(((BukkitMCPlugin) plugin).getHandle(), value));
	}

	public static final BukkitBlockListener BlockListener = new BukkitBlockListener();
	public static final BukkitEntityListener EntityListener = new BukkitEntityListener();
	public static final BukkitInventoryListener InventoryListener = new BukkitInventoryListener();
	public static final BukkitPlayerListener PlayerListener = new BukkitPlayerListener();
	public static final BukkitServerListener ServerListener = new BukkitServerListener();
	public static final BukkitVehicleListener VehicleListener = new BukkitVehicleListener();
	public static final BukkitWeatherListener WeatherListener = new BukkitWeatherListener();
	public static final BukkitWorldListener WorldListener = new BukkitWorldListener();

	@Override
	public void Startup(CommandHelperPlugin chp) {
		chp.registerEvents((Listener) BlockListener);
		chp.registerEventsDynamic((Listener) EntityListener);
		chp.registerEvents((Listener) InventoryListener);
		chp.registerEvents((Listener) PlayerListener);
		chp.registerEvents((Listener) ServerListener);
		chp.registerEvents((Listener) VehicleListener);
		chp.registerEvents((Listener) WeatherListener);
		chp.registerEvents((Listener) WorldListener);
	}

	@Override
	public int LookupItemId(String materialName) {
		if (Material.matchMaterial(materialName) != null) {
			return new MaterialData(Material.matchMaterial(materialName)).getItemTypeId();
		} else {
			return -1;
		}
	}

	@Override
	public String LookupMaterialName(int id) {
		return Material.getMaterial(id).toString();
	}

	@Override
	protected void triggerRunnable(final Runnable r) {
		try {
			runOnMainThreadAndWait(new Callable<Object>() {

				@Override
				public Object call() throws Exception {
					r.run();
					return null;
				}
			});
		} catch (InterruptedException | ExecutionException ex) {
			java.util.logging.Logger.getLogger(BukkitConvertor.class.getName()).log(Level.SEVERE, null, ex);
		}
	}

//    /**
//     * We don't want to allow scripts to clear other plugin's tasks
//     * on accident, so only ids registered through our interface
//     * can also be cancelled.
//     */
//    private static final Set<Integer> validIDs = new TreeSet<Integer>();
//
//	@Override
//    public synchronized int SetFutureRunnable(DaemonManager dm, long ms, Runnable r) {
//        int id = Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(CommandHelperPlugin.self, r, Static.msToTicks(ms));
//        validIDs.add(id);
//        return id;
//    }
//
//	@Override
//    public synchronized int SetFutureRepeater(DaemonManager dm, long ms, long initialDelay, Runnable r){
//        int id = Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask(CommandHelperPlugin.self, r, Static.msToTicks(initialDelay), Static.msToTicks(ms));
//        validIDs.add(id);
//        return id;
//    }
//
//	@Override
//    public synchronized void ClearAllRunnables() {
//		//Doing cancelTasks apparently does not work, so let's just manually cancel each task, which does appear to work.
//		//Anyways, it's better that way anyhow, because we actually remove IDs from validIDs that way.
//        //((BukkitMCServer)Static.getServer()).__Server().getScheduler().cancelTasks(CommandHelperPlugin.self);
//		Set<Integer> ids = new TreeSet<Integer>(validIDs);
//		for(int id : ids){
//			try{
//				//If this doesn't work, it shouldn't kill everything.
//				ClearFutureRunnable(id);
//			} catch(Exception e){
//				Logger.getLogger(BukkitConvertor.class.getName()).log(null, Level.SEVERE, e);
//			}
//		}
//    }
//
//	@Override
//    public void ClearFutureRunnable(int id) {
//        if(validIDs.contains(id)){
//            Bukkit.getServer().getScheduler().cancelTask(id);
//            validIDs.remove(id);
//        }
//    }
	public static MCEntity BukkitGetCorrectEntity(Entity be) {
		if (be == null) {
			return null;
		}

		BukkitMCEntityType type = BukkitMCEntityType.valueOfConcrete(be.getType());
		if (type.getWrapperClass() != null) {
			return ReflectionUtils.newInstance(type.getWrapperClass(), new Class[]{Entity.class}, new Object[]{be});
		}

		if (be instanceof Hanging) {
			type.setWrapperClass(BukkitMCHanging.class);
			return new BukkitMCHanging(be);
		}

		if (be instanceof Minecart) {
			// Must come before Vehicle
			type.setWrapperClass(BukkitMCMinecart.class);
			return new BukkitMCMinecart(be);
		}

		if (be instanceof Projectile) {
			type.setWrapperClass(BukkitMCProjectile.class);
			return new BukkitMCProjectile(be);
		}

		if (be instanceof Tameable) {
			// Must come before Ageable
			type.setWrapperClass(BukkitMCTameable.class);
			return new BukkitMCTameable(be);
		}

		if (be instanceof Ageable) {
			// Must come before LivingEntity
			type.setWrapperClass(BukkitMCAgeable.class);
			return new BukkitMCAgeable(be);
		}

		if (be instanceof HumanEntity) {
			// Must come before LivingEntity
			type.setWrapperClass(BukkitMCHumanEntity.class);
			return new BukkitMCHumanEntity(be);
		}

		if (be instanceof ComplexEntityPart) {
			type.setWrapperClass(BukkitMCComplexEntityPart.class);
			return new BukkitMCComplexEntityPart(be);
		}

		if (be instanceof ComplexLivingEntity) {
			// Must come before LivingEntity
			type.setWrapperClass(BukkitMCComplexLivingEntity.class);
			return new BukkitMCComplexLivingEntity(be);
		}

		if (be instanceof LivingEntity) {
			type.setWrapperClass(BukkitMCLivingEntity.class);
			return new BukkitMCLivingEntity(be);
		}

		if (be instanceof Vehicle) {
			type.setWrapperClass(BukkitMCVehicle.class);
			return new BukkitMCVehicle(be);
		}

		// Handle generically if we can't find a more specific type
		type.setWrapperClass(BukkitMCEntity.class);
		return new BukkitMCEntity(be);
	}

	@Override
	public MCEntity GetCorrectEntity(MCEntity e) {

		Entity be = ((BukkitMCEntity) e).getHandle();
		try {
			return BukkitConvertor.BukkitGetCorrectEntity(be);
		} catch (IllegalArgumentException iae) {
			CHLog.GetLogger().Log(CHLog.Tags.RUNTIME, LogLevel.INFO, iae.getMessage(), Target.UNKNOWN);
			return e;
		}
	}

	@Override
	public MCItemMeta GetCorrectMeta(MCItemMeta im) {
		ItemMeta bim = ((BukkitMCItemMeta) im).asItemMeta();
		return BukkitConvertor.BukkitGetCorrectMeta(bim);
	}

	@Override
	public List<MCEntity> GetEntitiesAt(MCLocation location, double radius) {
		if (location == null) {
			return Collections.EMPTY_LIST;
		}
		if (radius <= 0) {
			radius = 1;
		}
		Entity tempEntity = ((BukkitMCEntity) location.getWorld().spawn(location, MCEntityType.MCVanillaEntityType.ARROW)).getHandle();
		List<Entity> near = tempEntity.getNearbyEntities(radius, radius, radius);
		tempEntity.remove();
		List<MCEntity> entities = new ArrayList<MCEntity>();
		for (Entity e : near) {
			entities.add(BukkitGetCorrectEntity(e));
		}
		return entities;
	}

	public static MCItemMeta BukkitGetCorrectMeta(ItemMeta im) {
		if (Static.getServer().getMinecraftVersion().gte(MCVersion.MC1_8) && im instanceof BannerMeta) {
			return new BukkitMCBannerMeta((BannerMeta) im);
		}
		if (im instanceof BookMeta) {
			return new BukkitMCBookMeta((BookMeta) im);
		}
		if (im instanceof EnchantmentStorageMeta) {
			return new BukkitMCEnchantmentStorageMeta((EnchantmentStorageMeta) im);
		}
		if (im instanceof FireworkMeta) {
			return new BukkitMCFireworkMeta((FireworkMeta) im);
		}
		if (im instanceof LeatherArmorMeta) {
			return new BukkitMCLeatherArmorMeta((LeatherArmorMeta) im);
		}
		if (im instanceof PotionMeta) {
			return new BukkitMCPotionMeta((PotionMeta) im);
		}
		if (im instanceof SkullMeta) {
			return new BukkitMCSkullMeta((SkullMeta) im);
		}
		return new BukkitMCItemMeta(im);
	}

	@Override
	public MCInventory GetEntityInventory(MCEntity e) {
		Entity entity = ((BukkitMCEntity) e).getHandle();
		if (entity instanceof InventoryHolder) {
			if (entity instanceof Player) {
				return new BukkitMCPlayerInventory(((Player) entity).getInventory());
			} else {
				return new BukkitMCInventory(((InventoryHolder) entity).getInventory());
			}
		} else {
			return null;
		}
	}

	@Override
	public MCInventory GetLocationInventory(MCLocation location) {
		Block b = ((Location) (location.getHandle())).getBlock();
		if (b.getState() instanceof InventoryHolder) {
			if (b.getState() instanceof DoubleChest) {
				DoubleChest dc = (DoubleChest) (b.getState());
				return new BukkitMCDoubleChest(dc.getLeftSide().getInventory(), dc.getRightSide().getInventory());
			} else {
				return new BukkitMCInventory(((InventoryHolder) b.getState()).getInventory());
			}
		} else {
			return null;
		}
	}

	@Override
	public void runOnMainThreadLater(DaemonManager dm, final Runnable r) {
		Bukkit.getServer().getScheduler().callSyncMethod(CommandHelperPlugin.self, new Callable<Object>() {

			@Override
			public Object call() throws Exception {
				r.run();
				return null;
			}
		});
	}

	@Override
	public <T> T runOnMainThreadAndWait(Callable<T> callable) throws InterruptedException, ExecutionException {
		return Bukkit.getServer().getScheduler().callSyncMethod(CommandHelperPlugin.self, callable).get();
	}

	@Override
	public MCWorldCreator getWorldCreator(String worldName) {
		return new BukkitMCWorldCreator(worldName);
	}

	@Override
	public MCNote GetNote(int octave, MCTone tone, boolean sharp) {
		return new BukkitMCNote(octave, tone, sharp);
	}

	@Override
	public MCColor GetColor(int red, int green, int blue) {
		return BukkitMCColor.GetMCColor(Color.fromRGB(red, green, blue));
	}

	@Override
	public MCPattern GetPattern(MCDyeColor color, MCPatternShape shape) {
		return new BukkitMCPattern(new Pattern(BukkitMCDyeColor.getConvertor().getConcreteEnum(color),
				BukkitMCPatternShape.getConvertor().getConcreteEnum(shape)));
	}

	@Override
	public MCFireworkBuilder GetFireworkBuilder() {
		return new BukkitMCFireworkBuilder();
	}

	@Override
	public MCPluginMeta GetPluginMeta() {
		if (pluginMeta == null) {
			pluginMeta = new BukkitMCPluginMeta(CommandHelperPlugin.self);
			addShutdownHook(new Runnable() {

				@Override
				public void run() {
					pluginMeta = null;
				}
			});
		}
		return pluginMeta;
	}

	@Override
	public MCRecipe GetNewRecipe(MCRecipeType type, MCItemStack result) {
		switch (type) {
			case FURNACE:
				return new BukkitMCFurnaceRecipe(result);
			case SHAPED:
				return new BukkitMCShapedRecipe(result);
			case SHAPELESS:
				return new BukkitMCShapelessRecipe(result);
		}
		return null;
	}

	@Override
	public MCRecipe GetRecipe(MCRecipe unspecific) {
		Recipe r = ((BukkitMCRecipe) unspecific).r;
		return BukkitGetRecipe(r);
	}

	public static MCRecipe BukkitGetRecipe(Recipe r) {
		if (r instanceof ShapelessRecipe) {
			return new BukkitMCShapelessRecipe((ShapelessRecipe) r);
		} else if (r instanceof ShapedRecipe) {
			return new BukkitMCShapedRecipe((ShapedRecipe) r);
		} else if (r instanceof FurnaceRecipe) {
			return new BukkitMCFurnaceRecipe((FurnaceRecipe) r);
		} else {
			return null;
		}
	}

	@Override
	public MCCommand getNewCommand(String name) {
		return BukkitMCCommand.newCommand(name);
	}

	@Override
	public MCCommandSender GetCorrectSender(MCCommandSender unspecific) {
		if (unspecific == null) {
			return null;
		}
		return BukkitGetCorrectSender(((BukkitMCCommandSender) unspecific)._CommandSender());
	}

	public static MCCommandSender BukkitGetCorrectSender(CommandSender sender) {
		if (sender instanceof Player) {
			return new BukkitMCPlayer((Player) sender);
		} else if (sender instanceof ConsoleCommandSender) {
			return new BukkitMCConsoleCommandSender((ConsoleCommandSender) sender);
		} else if (sender instanceof BlockCommandSender) {
			return new BukkitMCBlockCommandSender((BlockCommandSender) sender);
		} else {
			return null;
		}
	}

	@Override
	public MCMaterial GetMaterial(String name) {
		Material match = Material.matchMaterial(name);
		if (match == null) {
			return null;
		}
		return new BukkitMCMaterial(match);
	}

	@Override
	public String GetPluginName() {
		return (String) new Yaml().loadAs(getClass().getResourceAsStream("/plugin.yml"), Map.class).get("name");
	}

	@Override
	public MCPlugin GetPlugin() {
		return new BukkitMCPlugin(CommandHelperPlugin.self);
	}

	@Override
	public MCColor GetColor(String colorName, Target t) throws Exceptions.FormatException {
		return ConvertorHelper.GetColor(colorName, t);
	}

	@Override
	public String GetUser(Environment env) {
		MCCommandSender cs = env.getEnv(CommandHelperEnvironment.class).GetCommandSender();
		if(cs == null){
			return null;
		} else {
			String name = cs.getName();
			if("CONSOLE".equals(name)){
				name = "~console";
			}
			return name;
		}
	}
}


text:
namespace Rsyn {

class SandboxPort : public SandboxInstance {

RSYN_FRIEND_OF_GENERIC_LIST_COLLECTION;

friend class Sandbox;
friend class SandboxInstance;

private:
	SandboxPort(SandboxInstanceData * data) : SandboxInstance(data) {}
public:

	SandboxPort() : SandboxInstance(nullptr) {}
	SandboxPort(std::nullptr_t) : SandboxInstance(nullptr) {}

	Port getRelated() const;

	SandboxPin getInnerPin() const;

	// NOTE: dummy, but kept as it's need for some template functions
	SandboxPin getOuterPin() const;
	SandboxPin getOtherPin(Rsyn::SandboxPin pin) const;

	// If this is a virtual port (i.e. does not exist in the design), returns
	// the pin that is driving/driven by this port.
	SandboxPin getAttachedPin() const;

	Direction getDirection() const;

	// Returns true if this port is not related to a real port in the design.
	bool isVirtual() const;
}; // end class

} // end namespace


text:
<?php

namespace Activity\Model;

use Eva\Api,
    Eva\Mvc\Model\AbstractModel;

class Follow extends AbstractModel
{
    protected $itemClass = 'Activity\Item\Follower';

    protected $userList;

    public function getUserList()
    {
        return $this->userList;
    }

    public function setUserList($userList)
    {
        $this->userList = $userList;
        return $this;
    }

    public function getFollowList(array $itemListParameters = array(), $map = null)
    {
        $this->trigger('list.precache');

        $userList = $this->getUserList();
        if($userList){
            $userIdArray = array();
            foreach($userList as $user) {
                $userIdArray[] = $user['id'];
            }
            if($userIdArray){
                $this->itemListParameters['user_id'] = $userIdArray;
            }
        }

        $this->trigger('list.pre');

        $item = $this->getItemList();
        if($map){
            $item = $item->toArray($map);
        }

        $this->trigger('get');

        $this->trigger('list.post');
        $this->trigger('list.postcache');

        return $item;
    }

    public function followUser($data = array())
    {
        if($data) {
            $this->setItem($data);
        }

        $item = $this->getItem();

        $this->trigger('create.pre');

        $userId = $item->user_id;
        $followerId = $item->follower_id;

        if($userId != $followerId) {
            $item->self(array('*'));

            if(!$item->relationshipStatus){
                $item->user_id = $userId;
                $item->follower_id = $followerId;
                $item->create();
                $item->self(array('*'));
            }
        }

        $this->trigger('create');

        if($userId != $followerId && $item->relationshipStatus == 'single'){
            $fansItem = clone $item;
            $fansItem->setDataSource(array());
            $fansItem->user_id = $item->follower_id;
            $fansItem->follower_id = $item->user_id;

            $fansItem->self(array('*'));

            if($fansItem->relationshipStatus){
                $item->relationshipStatus = 'double';
                $item->save();
                $fansItem->relationshipStatus = 'double';
                $fansItem->save();
            }
        }

        $this->trigger('create.post');

        return true;
    }

    public function unfollowUser()
    {
        $this->trigger('remove.pre');

        $item = $this->getItem();

        $userId = $item->user_id;
        $followerId = $item->follower_id;

        $item->remove();

        $this->trigger('remove');

        $fansItem = clone $item;
        $fansItem->setDataSource(array());
        $fansItem->user_id = $followerId;
        $fansItem->follower_id = $userId;
        $fansItem->self(array('*'));

        if($fansItem->relationshipStatus){
            $fansItem->user_id = $followerId;
            $fansItem->follower_id = $userId;
            $fansItem->relationshipStatus = 'single';
            $fansItem->save();
        }

        $this->trigger('remove.post');

        return true;
    }

}


text:
import unittest
import os
from sqltxt.table import Table
from sqltxt.column import Column, ColumnName
from sqltxt.plan import build_graph, traverse
from sqltxt.query import classify_conditions
from sqltxt.expression import Expression

class PlanTest(unittest.TestCase):

    def test_classify_conditions(self):
        aliases = { 'a': 'a', 'alpha': 'a', 'b': 'b', 'c': 'c' }
        conditions = [
            { 'left_operand': 'a.col1', 'operator': '=', 'right_operand': 'b.col1' }, 'and',
            { 'left_operand': 'a.col1', 'operator': '=', 'right_operand': 5 }, 'and',
            { 'left_operand': 'a.col1', 'operator': '=', 'right_operand': 'c.col1' }, 'and',
            { 'left_operand': 'a.col1', 'operator': '=', 'right_operand': 'a.col2' },
        ]

        expected_join_conditions = [
            Expression(ColumnName('a.col1'), '=', ColumnName('b.col1')),
            Expression(ColumnName('a.col1'), '=', ColumnName('c.col1')),
        ]
        expected_where_conditions = [
            Expression(ColumnName('a.col1'), '=', 5),
            Expression(ColumnName('a.col1'), '=', ColumnName('a.col2')),
        ]

        actual_join_conditions, actual_where_conditions = classify_conditions(conditions)
        self.assertEqual(actual_join_conditions, expected_join_conditions)
        self.assertEqual(actual_where_conditions, expected_where_conditions)

    def test_build_graph(self):
        relations = [
            {'path': 'a.txt', 'alias': 'a'},
            {'path': 'b.txt', 'alias': 'b'},
            {'path': 'c.txt', 'alias': 'c'},
        ]
        tables = [Table(r['path'], alias=r['alias']) for r in relations]
        aliases = { 'a': 'a', 'alpha': 'a', 'b': 'b', 'c': 'c' }
        conditions = [
            Expression(ColumnName('a.col1'), '=', ColumnName('b.col1')),
            Expression(ColumnName('a.col1'), '=', ColumnName('c.col1')),
        ]

        expected_graph = {
            'a': { 'idx': 0, 'neighbors': set(['b', 'c']), },
            'b': { 'idx': 1, 'neighbors': set(['a']), },
            'c': { 'idx': 2, 'neighbors': set(['a']), },
        }

        actual_graph = build_graph(tables, conditions)
        self.assertEqual(actual_graph, expected_graph)

    def test_traverse(self):

        graph = {
            'a': { 'idx': 0, 'neighbors': set(['b', 'c']), },
            'b': { 'idx': 1, 'neighbors': set(['a']), },
            'c': { 'idx': 2, 'neighbors': set(['a']), },
        }
        priorities = { 'a': 15, 'b': 20, 'c': 3 }

        actual_node_order = traverse(graph, priorities)
        expected_node_order = { 'a': 1, 'b': 0, 'c': 2 }
        self.assertEqual(actual_node_order, expected_node_order)

        priorities = { 'a': 25, 'b': 20, 'c': 3 }

        actual_node_order = traverse(graph, priorities)
        expected_node_order = { 'a': 0, 'b': 1, 'c': 2 }
        self.assertEqual(actual_node_order, expected_node_order)


text:
module.exports = function(controller) {
    //rozvrh
    controller.hears('rozvrh', 'message_received', function(bot, message) {
        bot.reply(message, { type: 'typing' });
        setTimeout(function() {
            bot.reply(message, 'Here you go! 👉 http://bit.ly/stunome_harmonogram');
        }, 2000);
    });
    //harmonogram
    controller.hears('harmonogram', 'message_received', function(bot, message) {
        var harmonogram = {
            attachments: [
                {
                    contentType: 'application/vnd.microsoft.card.hero',
                    content: {
                        title: 'Jaký harmonogram tě zajímá?',
                        buttons: [
                            {
                                type: 'openUrl',
                                title: 'podrobný harmonogram roku',
                                value: 'http://www.ff.cuni.cz/fakulta/predpisy-a-dokumenty/opatreni-dekana/harmonogram/'
                            },
                            {
                                type: 'openUrl',
                                title: 'hlavně rozvrh',
                                value: 'http://novamedia.ff.cuni.cz/studium/rozvrh-harmonogram-semestru/'
                            }
                        ]
                    }
                }
            ]
        };
        bot.reply(message, {type: 'typing'});
        setTimeout(function() {
            bot.reply(message, harmonogram);
        }, 2000);
    });

    controller.hears(['za[cč][ií]n[aá] semestr', 'za[cč][ií]n[aá] akademick[yý]','za[cč][ií]n[aá] ls','kon[cč][ií] semestr','kon[cč][ií] ls','kon[cč][ií] akademický','za[cč][ií]n[aá] zs','kon[cč][ií] zs', 'kdy .* akademick[yý] rok'], 'message_received', function(bot, message) {
        bot.reply(message, {type: 'typing'});
        setTimeout(function() {
            bot.reply(message, 'Většinou škola začíná na přelomu září a října, v lednu máš zkouškový. Letňák začíná tak v půlce února a končí na konci května. Celej akademickej rok končí na konci září. Každý rok se to trochu liší, radši mrkni na harmonogram tady: http://www.ff.cuni.cz/fakulta/predpisy-a-dokumenty/opatreni-dekana/harmonogram/');
        }, 2000);
    });

    controller.hears(['kdy .* zkou[sš]kov[eéyý]'], 'message_received', function(bot, message) {
        bot.reply(message, {type: 'typing'});
        setTimeout(function() {
            bot.reply(message, 'Většinou klasicky leden až půlka února a pak půlka května až konec června. Ale pozor, často máš "zkouškový" až do září, ale radši se ujisti u přednášejícího!');
        }, 2000);
    });
};


text:
<?php

use Phinx\Migration\AbstractMigration;

class AddMissingModifiedColumn extends AbstractMigration
{
    public function change()
    {
        $user_tokens = $this->table('user_tokens');
        $user_tokens
            ->addColumn('modified', 'integer', array('after' => 'created'))
            ->update();

        $login_attempts = $this->table('login_attempts');
        $login_attempts
        ->addColumn('modified', 'integer', array('after' => 'created'))
        ->update();
    }
}


text:
package ideal.library.elements;

public interface writeonly_reference_equality extends writeonly_equality_comparable, any_reference_equality { }


text:
@interface OtherBall : NSObject
@property(nonatomic, copy) NSString *color;

- (id)initAlternative;
- (id)initWithColor:(NSString *)color;
@end


text:
import { ImapCache } from "./imapcache";

describe("PouchCache", () => {
  let imapClient: ImapCache;

  beforeEach(()=>{
    imapClient = new ImapCache("./testdb");
  })

  afterEach(()=>{
    imapClient.dbAccess().destroy();
  })

  it("can raw read/write", () => {
    return imapClient.store({_id:"someid",hello:"world"})
    .then(()=>imapClient.retrieve("someid"))
    .then((doc)=>{ expect(doc.hello).toEqual("someid"); });
  });
});


text:
[![CF Slack](https://www.google.com/s2/favicons?domain=www.slack.com) Join us on Slack](https://cloudfoundry.slack.com/messages/buildpacks/)

A Cloud Foundry [buildpack](http://docs.cloudfoundry.org/buildpacks/) for running arbitrary binary web servers.

### Buildpack User Documentation

Official buildpack documentation can be found at [binary buildpack docs](http://docs.cloudfoundry.org/buildpacks/binary/index.html).

### Building the Buildpack

To build this buildpack, run the following command from the buildpack's directory:

1. Source the .envrc file in the buildpack directory.

   ```bash
   source .envrc
   ```
   To simplify the process in the future, install [direnv](https://direnv.net/) which will automatically source .envrc when you change directories.

1. Install buildpack-packager

    ```bash
    go install github.com/cloudfoundry/libbuildpack/packager/buildpack-packager
    ```

1. Build the buildpack

    ```bash
    buildpack-packager build [ --cached=(true|false) ]
    ```

1. Use in Cloud Foundry

   Upload the buildpack to your Cloud Foundry and optionally specify it by name

    ```bash
    cf create-buildpack [BUILDPACK_NAME] [BUILDPACK_ZIP_FILE_PATH] 1
    cf push my_app [-b BUILDPACK_NAME]
    ```

### Testing

Buildpacks use the [Cutlass](https://github.com/cloudfoundry/libbuildpack/tree/master/cutlass) framework for running integration tests.

To test this buildpack, run the following command from the buildpack's directory:

1. Source the .envrc file in the buildpack directory.

   ```bash
   source .envrc
   ```
   To simplify the process in the future, install [direnv](https://direnv.net/) which will automatically source .envrc when you change directories.

1. Run unit tests

    ```bash
    ./scripts/unit.sh
    ```

1. Run integration tests

    ```bash
    ./scripts/integration.sh
    ```

### Contributing

Find our guidelines [here](./CONTRIBUTING.md).

### Help and Support

Join the #buildpacks channel in our [Slack community](http://slack.cloudfoundry.org/) if you need any further assistance.

### Reporting Issues

Open a GitHub issue on this project [here](https://github.com/cloudfoundry/binary-buildpack/issues/new)

### Active Development

The project backlog is on [Pivotal Tracker](https://www.pivotaltracker.com/projects/1042066)


text:
const util = require('util');

module.exports = function (req, res, utils) {

    var deferred = Promise.defer();

    utils.request({
        url: 'open/get_posts_by_category',
        method: 'POST',
        qs: {
            siteId: req.site.id,
            categoryId: 'o7v1anqms4rd5xuydjxtfg',
            pageSize: 5
        }
    }, function (result) {

        var data = {
            category: {},
            list: [],
            first: undefined
        };

        if (result.code != 200) {

            deferred.resolve(data);
            return;
        };

        result.body = JSON.parse(result.body);
        data.category = { href: util.format('category?id=%s', result.body.category.id) };

        result.body.data.forEach(function (e) {

            //设置第一个显示的新闻
            if (!data.first) {

                e.text ? e.text : (e.text = e.title);
                e.image_url ? (e.image_url = util.format('%s&width=171&height=105', e.image_url)) : '';

                data.first = {
                    image: e.image_url,
                    title: utils.subString(e.title, 13),
                    text: (e.image_url ? utils.subString(e.text, 27) : utils.subString(e.text, 50)),
                    href: util.format('detail?id=%s', e.id)
                };

                return false;
            }

            data.list.push({
                ori_title: e.title,
                title: utils.subString(e.title, 25),
                date: e.date_published,
                href: util.format('detail?id=%s', e.id)
            });

        }, this);

        deferred.resolve({ data: data });
    },deferred);

    return deferred.promise;
}


text:
.class public final Lo/氵;
.super Lo/丨;
.source ""

# annotations
.annotation system Ldalvik/annotation/MemberClasses;
    value = {
        Lo/氵$if;
    }
.end annotation

# instance fields
.field private final ˎ:Lcom/quizup/core/activities/HomeActivity$8;

.field private ˏ:I

# direct methods
.method public constructor <init>(Lcom/quizup/core/activities/HomeActivity;Lcom/quizup/core/activities/HomeActivity$8;)V
    .locals 3

    .line 26
    const/4 v0, 0x0

    const v1, 0x7f0c0199

    invoke-direct {p0, p1, v0, v1}, Lo/丨;-><init>(Landroid/app/Activity;Lo/‿$if;I)V

    .line 22
    const/4 v0, 0x0

    iput v0, p0, Lo/氵;->ˏ:I

    .line 28
    iget-object v0, p0, Lo/ン;->ͺ:Landroid/widget/RelativeLayout;

    const v1, 0x7f090179

    invoke-virtual {v0, v1}, Landroid/widget/RelativeLayout;->findViewById(I)Landroid/view/View;

    move-result-object v0

    check-cast v0, Landroid/widget/TextView;

    .line 29
    const/16 v1, 0x8

    invoke-virtual {v0, v1}, Landroid/widget/TextView;->setVisibility(I)V

    .line 31
    iget-object v0, p0, Lo/ン;->ͺ:Landroid/widget/RelativeLayout;

    const v1, 0x7f09017a

    invoke-virtual {v0, v1}, Landroid/widget/RelativeLayout;->findViewById(I)Landroid/view/View;

    move-result-object v0

    check-cast v0, Landroid/widget/TextView;

    .line 32
    const v1, 0x7f070295

    invoke-virtual {v0, v1}, Landroid/widget/TextView;->setText(I)V

    .line 34
    iget-object v0, p0, Lo/氵;->ˊ:Lcom/quizup/core/widgets/topicButton/IconAndTextButton;

    const v1, 0x7f070297

    invoke-virtual {p1, v1}, Landroid/app/Activity;->getString(I)Ljava/lang/String;

    move-result-object v1

    const v2, 0x7f02023e

    invoke-virtual {v0, v1, v2}, Lcom/quizup/core/widgets/topicButton/IconAndTextButton;->ˊ(Ljava/lang/String;I)V

    .line 35
    iget-object v0, p0, Lo/氵;->ˋ:Lcom/quizup/core/widgets/topicButton/IconAndTextButton;

    const v1, 0x7f070296

    invoke-virtual {p1, v1}, Landroid/app/Activity;->getString(I)Ljava/lang/String;

    move-result-object v1

    const v2, 0x7f02021d

    invoke-virtual {v0, v1, v2}, Lcom/quizup/core/widgets/topicButton/IconAndTextButton;->ˊ(Ljava/lang/String;I)V

    .line 37
    iput-object p2, p0, Lo/氵;->ˎ:Lcom/quizup/core/activities/HomeActivity$8;

    .line 38
    iget-object p2, p0, Lo/氵;->ˎ:Lcom/quizup/core/activities/HomeActivity$8;

    move-object p1, p0

    if-eqz p2, :cond_0

    new-instance v0, Lo/氵$1;

    invoke-direct {v0, p1, p2}, Lo/氵$1;-><init>(Lo/氵;Lcom/quizup/core/activities/HomeActivity$8;)V

    move-object p2, v0

    iget-object v0, p1, Lo/氵;->ˊ:Lcom/quizup/core/widgets/topicButton/IconAndTextButton;

    invoke-virtual {v0, p2}, Lcom/quizup/core/widgets/topicButton/IconAndTextButton;->setOnClickListener(Landroid/view/View$OnClickListener;)V

    iget-object v0, p1, Lo/氵;->ˋ:Lcom/quizup/core/widgets/topicButton/IconAndTextButton;

    invoke-virtual {v0, p2}, Lcom/quizup/core/widgets/topicButton/IconAndTextButton;->setOnClickListener(Landroid/view/View$OnClickListener;)V

    .line 39
    :cond_0
    return-void
.end method