_id stringlengths 2 7 | title stringlengths 3 151 | partition stringclasses 3
values | text stringlengths 83 13k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q9800 | Source.bailIfConstructArguments | train | private function bailIfConstructArguments(string $source, int $width, int $height): void
{
if ($width <= 0) {
throw new InvalidArgumentException('Width cannot be less or equal than zero.');
}
if ($height <= 0) {
throw new InvalidArgumentException('Height cannot be less or equal than zero.');
}
if (!file_exists($source)) {
throw new InvalidArgumentException('Source file does not exists.');
}
} | php | {
"resource": ""
} |
q9801 | TokenFactory.buildFromHtml | train | public static function buildFromHtml(string $html, Token $parent = null, bool $throwOnError = true)
{
$matchCriteria = array(
'Php' => "/^\s*<\?(php)?\s/i",
'Comment' => "/^\s*<!--/",
'CData' => "/^\s*<!\[CDATA\[/",
'DocType' => "/^\s*<!DOCTYPE /i",
'Element' => "/^\s*<[a-z]/i",
'Text' => "/^[^<]/"
);
foreach ($matchCriteria as $className => $regex) {
if (preg_match($regex, $html) === 1) {
$fullClassName = "Kevintweber\\HtmlTokenizer\\Tokens\\" . $className;
return new $fullClassName($parent, $throwOnError);
}
}
// Error condition
if ($throwOnError) {
throw new TokenMatchingException();
}
} | php | {
"resource": ""
} |
q9802 | PoolTask.cloneStructure | train | private function cloneStructure(array & $struct): void
{
foreach ($struct as & $v) {
if (is_object($v)) {
$v = clone $v;
} elseif (is_array($v)) {
$this->cloneStructure($v);
}
}
} | php | {
"resource": ""
} |
q9803 | PictureEffect.restore | train | public function restore(array $settings = array())
{
$settings = array_values($settings);
$reflection = new ReflectionMethod(get_class($this), '__construct');
$alreadySet = $reflection->getNumberOfParameters();
$index = 0;
foreach($this->settings as &$setting)
{
if($alreadySet > $index)
{
continue;
}
if(array_key_exists($index, $settings))
{
$setting = $settings[$index] === '' ? NULL : $settings[$index];
}
$index++;
}
} | php | {
"resource": ""
} |
q9804 | PictureEffect.hex2rgb | train | public function hex2rgb($hex, $returnString = FALSE)
{
$hex = str_replace('#', '', $hex);
if(strlen($hex) == 3)
{
$r = hexdec(substr($hex,0,1).substr($hex,0,1));
$g = hexdec(substr($hex,1,1).substr($hex,1,1));
$b = hexdec(substr($hex,2,1).substr($hex,2,1));
}
else
{
$r = hexdec(substr($hex,0,2));
$g = hexdec(substr($hex,2,2));
$b = hexdec(substr($hex,4,2));
}
if($returnString)
{
return implode(', ', array($r, $g, $b));
}
return array($r, $g, $b);
} | php | {
"resource": ""
} |
q9805 | MemberExtension.setCart | train | public function setCart(ShoppingCart $cart)
{
$curr = $this->getOwner()->getCart();
$contact = $this->getOwner()->Contact();
if (isset($curr) && $curr->ID != $cart->ID) {
$curr->delete();
}
$cart->CustomerID = $contact->ID;
return $this;
} | php | {
"resource": ""
} |
q9806 | CookieButton.renderButton | train | private function renderButton()
{
$this->params = Json::encode([
'btnName' => $this->options['id'],
'cookieName' => $this->cookie['name'],
'cookieValue' => addslashes($this->getHashedCookieValue($this->cookie['value'])),
'cookieOptions' => isset($this->cookie['options']) ? $this->cookie['options'] : null,
]);
if($this->cookie($this->cookie['name'])) {
Html::addCssClass($this->options, 'active');
}
echo Button::widget([
'label' => $this->encodeLabel ? Html::encode($this->label) : $this->label,
'encodeLabel' => $this->encodeLabel,
'options' => ArrayHelper::merge(['data-toggle' => 'button'], $this->options),
]);
} | php | {
"resource": ""
} |
q9807 | CookieButton.renderButtonGroup | train | private function renderButtonGroup()
{
$this->params = Json::encode([
'btnName' => $this->options['id'],
'cookieName' => $this->cookie['name'],
'cookieValue' => addslashes($this->getHashedCookieValue($this->cookie['value'])),
'cookieOptions' => isset($this->cookie['options']) ? $this->cookie['options'] : null,
'toggleClass' => isset($this->toggleClass) ? $this->toggleClass : null
]);
if($this->cookie($this->cookie['name'])) {
$isActive = true;
} else {
$isActive = false;
}
echo ButtonGroup::widget([
'id' => $this->options['id'],
'buttons' => [
[
'label' => $this->encodeLabel ? Html::encode($this->label[0]) : $this->label[0],
'options' => [
'class' => 'btn ' . ($isActive ? $this->toggleClass : 'btn-default') . ' ' . $this->options['class'] . ($isActive ? ' active' : '')
]
],
[
'label' => $this->encodeLabel ? Html::encode($this->label[1]) : $this->label[1],
'options' => [
'class' => 'btn ' . ($isActive ? 'btn-default' : $this->toggleClass) . ' ' . $this->options['class'] . ($isActive ? ' active' : '')
]
],
]
]);
} | php | {
"resource": ""
} |
q9808 | CookieButton.cookie | train | private function cookie($name, $value = null, $expire = 0, $domain = '', $path = '/', $secure = false)
{
if($value === false) {
\Yii::$app->response->cookies->remove($name);
} elseif($value === null) {
return \Yii::$app->request->cookies->getValue($name);
}
/*$options['name'] = $name;
$options['value'] = $value;
$options['expire'] = $expire; //$expire?:time()+86400*365
$options['domain'] = $domain;
$options['path'] = $path;
$options['secure'] = $secure;
$cookie = new \yii\web\Cookie($options);
\Yii::$app->response->cookies->add($cookie);*/
} | php | {
"resource": ""
} |
q9809 | Factory.instantiate | train | private static function instantiate(array $declaration)
{
$fieldType = array_shift($declaration);
$class = "\\Zerg\\Field\\" . ucfirst(strtolower($fieldType));
if (class_exists($class)) {
$reflection = new \ReflectionClass($class);
return $reflection->newInstanceArgs($declaration);
}
throw new ConfigurationException("Field {$fieldType} doesn't exist");
} | php | {
"resource": ""
} |
q9810 | Configuration.getApplicationNode | train | private function getApplicationNode(): NodeDefinition
{
$treeBuilder = new TreeBuilder('application');
return $treeBuilder
->getRootNode()
->addDefaultsIfNotSet()
->children()
->arrayNode('version')
->addDefaultsIfNotSet()
->children()
->scalarNode('file_path')
->info('Path of a file who contains version of the application')
->defaultValue(sprintf('%%kernel.project_dir%%/%s', ApplicationService::VERSION_FILE_NAME))
->cannotBeEmpty()
->end()
->end()
->end()
->scalarNode('name')
->info('Name of application. May be displayed near logo.')
->defaultValue('')
->end()
->scalarNode('description')
->info('Description of application. May be displayed near logo.')
->defaultValue('')
->end()
->scalarNode('empty_value_replacement')
->info('Replacement of empty value. May be used to filter values in templates/views.')
->defaultValue('-')
->end()
->end()
;
} | php | {
"resource": ""
} |
q9811 | Configuration.getFormNode | train | private function getFormNode(): NodeDefinition
{
$treeBuilder = new TreeBuilder('form');
return $treeBuilder
->getRootNode()
->addDefaultsIfNotSet()
->children()
->scalarNode('novalidate')
->info('Information if HTML5 inline validation is disabled')
->defaultFalse()
->end()
->end()
;
} | php | {
"resource": ""
} |
q9812 | Configuration.getDateNode | train | private function getDateNode(): NodeDefinition
{
$treeBuilder = new TreeBuilder('date');
return $treeBuilder
->getRootNode()
->addDefaultsIfNotSet()
->children()
->arrayNode('format')
->addDefaultsIfNotSet()
->children()
->scalarNode(DateLength::DATE)
->info('Format of date without time')
->defaultValue('d.m.Y')
->end()
->scalarNode(DateLength::DATETIME)
->info('Format of date with time')
->defaultValue('d.m.Y H:i')
->end()
->scalarNode(DateLength::TIME)
->info('Format of time without date')
->defaultValue('H:i')
->end()
->end()
->end()
->end()
;
} | php | {
"resource": ""
} |
q9813 | Assert.empty | train | public static function empty(...$values): bool
{
self::handleInvalidArguments($values);
foreach ($values as $value) {
if (empty($value) === false) {
return false;
}
}
return true;
} | php | {
"resource": ""
} |
q9814 | Assert.typeOf | train | public static function typeOf($types, ...$values): bool
{
if (is_string($types)) {
$types = [$types];
}
if (is_array($types) === false) {
throw new InvalidArgumentException(sprintf(static::MSG_TYPE_MISMATCH, gettype($types)));
}
foreach ($values as $value) {
$isObject = is_object($value);
$match = false;
$valueType = gettype($value);
// Check if current value is one of the specified types or instances
foreach ($types as $type) {
if (($isObject && $value instanceof $type) xor ($isObject === false && $valueType === $type)) {
$match = true;
break;
}
}
// Throw type error
if ($match === false) {
if ($isObject) {
$message = 'Expected value to be an instance of %s, instance of %s given!';
$valueType = get_class($value);
} else {
$message = 'Expected value to be of type %s, %s given!';
}
throw new TypeError(sprintf($message, implode(' or ', $types), $valueType));
}
}
return true;
} | php | {
"resource": ""
} |
q9815 | Runtime.unregisterHelper | train | public static function unregisterHelper($name)
{
//Argument 1 must be a string
Argument::i()->test(1, 'string');
if (isset(self::$helpers[$name])) {
unset(self::$helpers[$name]);
}
} | php | {
"resource": ""
} |
q9816 | Runtime.unregisterPartial | train | public static function unregisterPartial($name)
{
//Argument 1 must be a string
Argument::i()->test(1, 'string');
if (isset(self::$partials[$name])) {
unset(self::$partials[$name]);
}
} | php | {
"resource": ""
} |
q9817 | Text.addItem | train | private function addItem()
{
$args = func_get_args();
$this->items[$args[0]] = implode(':', array_slice($args, 1));
return $this;
} | php | {
"resource": ""
} |
q9818 | Text.render | train | private function render()
{
$parts = [];
if (!empty($this->items)) {
$parts[] = implode(',', $this->items);
}
$parts[] = isset($this->items['base64']) ? self::base64Encode($this->text) : urlencode($this->text);
return implode(':', $parts);
} | php | {
"resource": ""
} |
q9819 | FirewallService.index | train | public function index($params = [], $optParams = [])
{
if ($optParams instanceof IndexParams) {
$optParams = $optParams->toArray(true);
}
return $this->sendRequest([], [
'restAction' => 'index',
'params' => $params,
'getParams' => $optParams,
], function ($response) {
$firewalls = [];
foreach ($response->data['items'] as $firewall) {
$firewalls[] = new Firewall($firewall);
}
return new Index([
'models' => $firewalls,
'totalCount' => (int) $response->data['totalCount'],
'nextPageToken' => $response->data['nextPageToken'],
]);
});
} | php | {
"resource": ""
} |
q9820 | FirewallService.create | train | public function create($params, $optParams = [])
{
if (!$params instanceof Firewall) {
throw new InvalidParamException(Firewall::class.' is required!');
}
return $this->sendRequest([], [
'restAction' => 'create',
'postParams' => $params->toArray(),
'getParams' => $optParams,
], function ($response) {
return isset($response->data) ? new Firewall($response->data) : $response;
});
} | php | {
"resource": ""
} |
q9821 | FirewallService.view | train | public function view($params, $optParams = [])
{
if ($params instanceof Firewall) {
$params = $params->id;
}
return $this->sendRequest([], [
'restAction' => 'view',
'restId' => $params,
'getParams' => $optParams,
], function ($response) {
return isset($response->data) ? new Firewall($response->data) : $response;
});
} | php | {
"resource": ""
} |
q9822 | Address.mergeWith | train | public function mergeWith(Address $address): self
{
return new static(...\array_merge($this->ipv4, $address->ipv4), ...\array_merge($this->ipv6, $address->ipv6));
} | php | {
"resource": ""
} |
q9823 | CompositeHealthIndicator.health | train | public function health()
{
$healths = [];
foreach ($this->indicators as $key => $indicator) {
$healths[$key] = $indicator->health();
}
return $this->healthAggregator->aggregate($healths);
} | php | {
"resource": ""
} |
q9824 | Filesystem.purge | train | public function purge($dir)
{
if (!is_dir($dir)) {
return;
}
$files = scandir($dir);
if ($files !== false) {
foreach ($files as $file) {
if ($file === '.' || $file === '..') {
continue;
}
$path = $dir . '/' . $file;
if (is_dir($path)) {
$this->purge($path);
rmdir($path);
} else {
unlink($path);
}
}
}
} | php | {
"resource": ""
} |
q9825 | Filesystem.copy | train | public function copy($src, $dest)
{
if (is_dir($src)) {
$this->ensureDir($dest);
$files = scandir($src);
foreach ($files as $file) {
if ($file !== '.' && $file !== '..') {
$this->copy($src . '/' . $file, $dest . '/' . $file);
}
}
} else {
$this->ensureDir(dirname($dest));
copy($src, $dest);
}
} | php | {
"resource": ""
} |
q9826 | ConfigServiceProvider.configMerge | train | public static function configMerge() {
$result = array();
$args = func_get_args();
foreach ($args as $arg) {
if (!is_array($arg)) {
continue;
}
foreach ($arg as $key => $value) {
if (is_numeric($key)) {
// Renumber numeric keys as array_merge() does.
$result[] = $value;
} elseif (array_key_exists($key, $result) && is_array($result[$key]) && is_array($value)) {
// Recurse only when both values are arrays.
$result[$key] = ConfigServiceProvider::configMerge($result[$key], $value);
} else {
// Otherwise, use the latter value.
$result[$key] = $value;
}
}
}
return $result;
} | php | {
"resource": ""
} |
q9827 | DoctrineActivationRepository.completed | train | public function completed(UserInterface $user)
{
$queryBuilder = $this->createQueryBuilder('a');
$queryBuilder
->where('a.user = :user')
->andWhere('a.completed = :completed');
$queryBuilder
->setParameters([
'user' => $user,
'completed' => true
]);
try
{
return $queryBuilder->getQuery()->getSingleResult();
}
catch (NoResultException $e)
{
return false;
}
} | php | {
"resource": ""
} |
q9828 | Executor.submit | train | public function submit(Context $context, $work, int $priority = 0): Promise
{
$job = new class($context) extends Placeholder {
public $priority;
public $generator;
};
$job->priority = $priority;
$job->generator = ($work instanceof \Generator) ? $work : Coroutine::generate($work, $context);
for ($inserted = null, $count = \count($this->jobs), $i = 0; $i < $count; $i++) {
if ($priority <= $this->jobs[$i]->priority) {
$inserted = \array_splice($this->jobs, $i, 0, [
$job
]);
break;
}
}
if ($inserted === null) {
$this->jobs[] = $job;
}
if ($this->running < $this->concurrency) {
$this->running++;
$context->getLoop()->defer(\Closure::fromCallable([
$this,
'executeNextJob'
]));
}
return $context->keepBusy($job->promise());
} | php | {
"resource": ""
} |
q9829 | Executor.executeNextJob | train | protected function executeNextJob(): void
{
while ($this->jobs) {
$job = \array_pop($this->jobs);
if ($job->state & AbstractPromise::PENDING) {
$done = false;
(new Coroutine($job->context, $job->generator))->when(function (?\Throwable $e, $v = null) use ($job, & $done) {
if ($e) {
$job->fail($e);
} else {
$job->resolve($v);
}
if ($done) {
$this->executeNextJob();
} else {
$done = true;
}
});
if (!$done) {
$done = true;
return;
}
}
}
$this->running--;
} | php | {
"resource": ""
} |
q9830 | FeatureFeatureType.setFeature | train | public function setFeature(ChildFeature $v = null)
{
if ($v === null) {
$this->setFeatureId(NULL);
} else {
$this->setFeatureId($v->getId());
}
$this->aFeature = $v;
// Add binding for other direction of this n:n relationship.
// If this object has already been added to the ChildFeature object, it will not be re-added.
if ($v !== null) {
$v->addFeatureFeatureType($this);
}
return $this;
} | php | {
"resource": ""
} |
q9831 | FeatureFeatureType.getFeature | train | public function getFeature(ConnectionInterface $con = null)
{
if ($this->aFeature === null && ($this->feature_id !== null)) {
$this->aFeature = FeatureQuery::create()->findPk($this->feature_id, $con);
/* The following can be used additionally to
guarantee the related object contains a reference
to this object. This level of coupling may, however, be
undesirable since it could result in an only partially populated collection
in the referenced object.
$this->aFeature->addFeatureFeatureTypes($this);
*/
}
return $this->aFeature;
} | php | {
"resource": ""
} |
q9832 | FeatureFeatureType.initFeatureTypeAvMetas | train | public function initFeatureTypeAvMetas($overrideExisting = true)
{
if (null !== $this->collFeatureTypeAvMetas && !$overrideExisting) {
return;
}
$this->collFeatureTypeAvMetas = new ObjectCollection();
$this->collFeatureTypeAvMetas->setModel('\FeatureType\Model\FeatureTypeAvMeta');
} | php | {
"resource": ""
} |
q9833 | FeatureFeatureType.getFeatureTypeAvMetas | train | public function getFeatureTypeAvMetas($criteria = null, ConnectionInterface $con = null)
{
$partial = $this->collFeatureTypeAvMetasPartial && !$this->isNew();
if (null === $this->collFeatureTypeAvMetas || null !== $criteria || $partial) {
if ($this->isNew() && null === $this->collFeatureTypeAvMetas) {
// return empty collection
$this->initFeatureTypeAvMetas();
} else {
$collFeatureTypeAvMetas = ChildFeatureTypeAvMetaQuery::create(null, $criteria)
->filterByFeatureFeatureType($this)
->find($con);
if (null !== $criteria) {
if (false !== $this->collFeatureTypeAvMetasPartial && count($collFeatureTypeAvMetas)) {
$this->initFeatureTypeAvMetas(false);
foreach ($collFeatureTypeAvMetas as $obj) {
if (false == $this->collFeatureTypeAvMetas->contains($obj)) {
$this->collFeatureTypeAvMetas->append($obj);
}
}
$this->collFeatureTypeAvMetasPartial = true;
}
reset($collFeatureTypeAvMetas);
return $collFeatureTypeAvMetas;
}
if ($partial && $this->collFeatureTypeAvMetas) {
foreach ($this->collFeatureTypeAvMetas as $obj) {
if ($obj->isNew()) {
$collFeatureTypeAvMetas[] = $obj;
}
}
}
$this->collFeatureTypeAvMetas = $collFeatureTypeAvMetas;
$this->collFeatureTypeAvMetasPartial = false;
}
}
return $this->collFeatureTypeAvMetas;
} | php | {
"resource": ""
} |
q9834 | FeatureFeatureType.countFeatureTypeAvMetas | train | public function countFeatureTypeAvMetas(Criteria $criteria = null, $distinct = false, ConnectionInterface $con = null)
{
$partial = $this->collFeatureTypeAvMetasPartial && !$this->isNew();
if (null === $this->collFeatureTypeAvMetas || null !== $criteria || $partial) {
if ($this->isNew() && null === $this->collFeatureTypeAvMetas) {
return 0;
}
if ($partial && !$criteria) {
return count($this->getFeatureTypeAvMetas());
}
$query = ChildFeatureTypeAvMetaQuery::create(null, $criteria);
if ($distinct) {
$query->distinct();
}
return $query
->filterByFeatureFeatureType($this)
->count($con);
}
return count($this->collFeatureTypeAvMetas);
} | php | {
"resource": ""
} |
q9835 | FeatureFeatureType.addFeatureTypeAvMeta | train | public function addFeatureTypeAvMeta(ChildFeatureTypeAvMeta $l)
{
if ($this->collFeatureTypeAvMetas === null) {
$this->initFeatureTypeAvMetas();
$this->collFeatureTypeAvMetasPartial = true;
}
if (!in_array($l, $this->collFeatureTypeAvMetas->getArrayCopy(), true)) { // only add it if the **same** object is not already associated
$this->doAddFeatureTypeAvMeta($l);
}
return $this;
} | php | {
"resource": ""
} |
q9836 | FeatureFeatureType.getFeatureTypeAvMetasJoinFeatureAv | train | public function getFeatureTypeAvMetasJoinFeatureAv($criteria = null, $con = null, $joinBehavior = Criteria::LEFT_JOIN)
{
$query = ChildFeatureTypeAvMetaQuery::create(null, $criteria);
$query->joinWith('FeatureAv', $joinBehavior);
return $this->getFeatureTypeAvMetas($query, $con);
} | php | {
"resource": ""
} |
q9837 | XTreeDB.Put | train | function Put($key, $value)
{
// check the file description
if (!$this->fd || $this->mode != 'w')
{
trigger_error("XDB::Put(), null db handler or readonly.", E_USER_WARNING);
return false;
}
// check the length
$klen = strlen($key);
$vlen = strlen($value);
if (!$klen || $klen > XDB_MAXKLEN)
return false;
// try to find the old data
$rec = $this->_get_record($key);
if (isset($rec['vlen']) && ($vlen <= $rec['vlen']))
{
// update the old value & length
if ($vlen > 0)
{
fseek($this->fd, $rec['voff'], SEEK_SET);
fwrite($this->fd, $value, $vlen);
}
if ($vlen < $rec['vlen'])
{
$newlen = $rec['len'] + $vlen - $rec['vlen'];
$newbuf = pack('I', $newlen);
fseek($this->fd, $rec['poff'] + 4, SEEK_SET);
fwrite($this->fd, $newbuf, 4);
}
return true;
}
// 构造数据
$new = array('loff' => 0, 'llen' => 0, 'roff' => 0, 'rlen' => 0);
if (isset($rec['vlen']))
{
$new['loff'] = $rec['loff'];
$new['llen'] = $rec['llen'];
$new['roff'] = $rec['roff'];
$new['rlen'] = $rec['rlen'];
}
$buf = pack('IIIIC', $new['loff'], $new['llen'], $new['roff'], $new['rlen'], $klen);
$buf .= $key . $value;
$len = $klen + $vlen + 17;
$off = $this->fsize;
fseek($this->fd, $off, SEEK_SET);
fwrite($this->fd, $buf, $len);
$this->fsize += $len;
$pbuf = pack('II', $off, $len);
fseek($this->fd, $rec['poff'], SEEK_SET);
fwrite($this->fd, $pbuf, 8);
return true;
} | php | {
"resource": ""
} |
q9838 | XTreeDB.Draw | train | function Draw($i = -1)
{
if ($i < 0 || $i >= $this->hash_prime)
{
$i = 0;
$j = $this->hash_prime;
}
else
{
$j = $i + 1;
}
echo "Draw the XDB data [$i ~ $j]. (" . trim($this->Version()) . ")\n\n";
while ($i < $j)
{
$poff = $i * 8 + 32;
fseek($this->fd, $poff, SEEK_SET);
$buf = fread($this->fd, 8);
if (strlen($buf) != 8) break;
$ptr = unpack('Ioff/Ilen', $buf);
$this->_cur_depth = 0;
$this->_node_num = 0;
$this->_draw_node($ptr['off'], $ptr['len']);
echo "-------------------------------------------\n";
echo "Tree(xdb) [$i] max_depth: {$this->_cur_depth} nodes_num: {$this->_node_num}\n";
$i++;
}
} | php | {
"resource": ""
} |
q9839 | XTreeDB.Version | train | function Version()
{
$ver = (is_null($this) ? XDB_VERSION : $this->version);
$str = sprintf("%s/%d.%d", XDB_TAGNAME, ($ver >> 5), ($ver & 0x1f));
if (!is_null($this)) $str .= " <base={$this->hash_base}, prime={$this->hash_prime}>";
return $str;
} | php | {
"resource": ""
} |
q9840 | XTreeDB.Close | train | function Close()
{
if (!$this->fd)
return;
if ($this->mode == 'w')
{
$buf = pack('I', $this->fsize);
fseek($this->fd, 12, SEEK_SET);
fwrite($this->fd, $buf, 4);
flock($this->fd, LOCK_UN);
}
fclose($this->fd);
$this->fd = false;
} | php | {
"resource": ""
} |
q9841 | XTreeDB.Optimize | train | function Optimize($i = -1)
{
// check the file description
if (!$this->fd || $this->mode != 'w')
{
trigger_error("XDB::Optimize(), null db handler or readonly.", E_USER_WARNING);
return false;
}
// get the index zone:
if ($i < 0 || $i >= $this->hash_prime)
{
$i = 0;
$j = $this->hash_prime;
}
else
{
$j = $i + 1;
}
// optimize every index
while ($i < $j)
{
$this->_optimize_index($i);
$i++;
}
} | php | {
"resource": ""
} |
q9842 | XTreeDB._optimize_index | train | function _optimize_index($index)
{
static $cmp = false;
$poff = $index * 8 + 32;
// save all nodes into array()
$this->_sync_nodes = array();
$this->_load_tree_nodes($poff);
$count = count($this->_sync_nodes);
if ($count < 3) return;
// sync the nodes, sort by key first
if ($cmp == false) $cmp = create_function('$a,$b', 'return strcmp($a[key],$b[key]);');
usort($this->_sync_nodes, $cmp);
$this->_reset_tree_nodes($poff, 0, $count - 1);
unset($this->_sync_nodes);
} | php | {
"resource": ""
} |
q9843 | XTreeDB._load_tree_nodes | train | function _load_tree_nodes($poff)
{
fseek($this->fd, $poff, SEEK_SET);
$buf = fread($this->fd, 8);
if (strlen($buf) != 8) return;
$tmp = unpack('Ioff/Ilen', $buf);
if ($tmp['len'] == 0) return;
fseek($this->fd, $tmp['off'], SEEK_SET);
$rlen = XDB_MAXKLEN + 17;
if ($rlen > $tmp['len']) $rlen = $tmp['len'];
$buf = fread($this->fd, $rlen);
$rec = unpack('Iloff/Illen/Iroff/Irlen/Cklen', substr($buf, 0, 17));
$rec['off'] = $tmp['off'];
$rec['len'] = $tmp['len'];
$rec['key'] = substr($buf, 17, $rec['klen']);
$this->_sync_nodes[] = $rec;
unset($buf);
// left
if ($rec['llen'] != 0) $this->_load_tree_nodes($tmp['off']);
// right
if ($rec['rlen'] != 0) $this->_load_tree_nodes($tmp['off'] + 8);
} | php | {
"resource": ""
} |
q9844 | XTreeDB._reset_tree_nodes | train | function _reset_tree_nodes($poff, $low, $high)
{
if ($low <= $high)
{
$mid = ($low+$high)>>1;
$node = $this->_sync_nodes[$mid];
$buf = pack('II', $node['off'], $node['len']);
// left
$this->_reset_tree_nodes($node['off'], $low, $mid - 1);
// right
$this->_reset_tree_nodes($node['off'] + 8, $mid + 1, $high);
}
else
{
$buf = pack('II', 0, 0);
}
fseek($this->fd, $poff, SEEK_SET);
fwrite($this->fd, $buf, 8);
} | php | {
"resource": ""
} |
q9845 | XTreeDB._check_header | train | function _check_header($fd)
{
fseek($fd, 0, SEEK_SET);
$buf = fread($fd, 32);
if (strlen($buf) !== 32) return false;
$hdr = unpack('a3tag/Cver/Ibase/Iprime/Ifsize/fcheck/a12reversed', $buf);
if ($hdr['tag'] != XDB_TAGNAME) return false;
// check the fsize
$fstat = fstat($fd);
if ($fstat['size'] != $hdr['fsize'])
return false;
// check float?
$this->hash_base = $hdr['base'];
$this->hash_prime = $hdr['prime'];
$this->version = $hdr['ver'];
$this->fsize = $hdr['fsize'];
return true;
} | php | {
"resource": ""
} |
q9846 | XTreeDB._write_header | train | function _write_header($fd)
{
$buf = pack('a3CiiIfa12', XDB_TAGNAME, $this->version,
$this->hash_base, $this->hash_prime, 0, XDB_FLOAT_CHECK, '');
fseek($fd, 0, SEEK_SET);
fwrite($fd, $buf, 32);
} | php | {
"resource": ""
} |
q9847 | XTreeDB._get_record | train | function _get_record($key)
{
$this->_io_times = 1;
$index = ($this->hash_prime > 1 ? $this->_get_index($key) : 0);
$poff = $index * 8 + 32;
fseek($this->fd, $poff, SEEK_SET);
$buf = fread($this->fd, 8);
if (strlen($buf) == 8) $tmp = unpack('Ioff/Ilen', $buf);
else $tmp = array('off' => 0, 'len' => 0);
return $this->_tree_get_record($tmp['off'], $tmp['len'], $poff, $key);
} | php | {
"resource": ""
} |
q9848 | XTreeDB._tree_get_record | train | function _tree_get_record($off, $len, $poff = 0, $key = '')
{
if ($len == 0)
return (array('poff' => $poff));
$this->_io_times++;
// get the data & compare the key data
fseek($this->fd, $off, SEEK_SET);
$rlen = XDB_MAXKLEN + 17;
if ($rlen > $len) $rlen = $len;
$buf = fread($this->fd, $rlen);
$rec = unpack('Iloff/Illen/Iroff/Irlen/Cklen', substr($buf, 0, 17));
$fkey = substr($buf, 17, $rec['klen']);
$cmp = ($key ? strcmp($key, $fkey) : 0);
if ($cmp > 0)
{
// --> right
unset($buf);
return $this->_tree_get_record($rec['roff'], $rec['rlen'], $off + 8, $key);
}
else if ($cmp < 0)
{
// <-- left
unset($buf);
return $this->_tree_get_record($rec['loff'], $rec['llen'], $off, $key);
}
else {
// found!!
$rec['poff'] = $poff;
$rec['off'] = $off;
$rec['len'] = $len;
$rec['voff'] = $off + 17 + $rec['klen'];
$rec['vlen'] = $len - 17 - $rec['klen'];
$rec['key'] = $fkey;
fseek($this->fd, $rec['voff'], SEEK_SET);
$rec['value'] = fread($this->fd, $rec['vlen']);
return $rec;
}
} | php | {
"resource": ""
} |
q9849 | ReadSection.read | train | public function read(
ReadOptionsInterface $options,
SectionConfig $sectionConfig = null
): \ArrayIterator {
$sectionData = new \ArrayIterator();
$this->dispatcher->dispatch(
SectionBeforeRead::NAME,
new SectionBeforeRead($sectionData, $options, $sectionConfig)
);
if ($sectionConfig === null && count($options->getSection()) > 0) {
$sectionConfig = $this->sectionManager->readByHandle(
$options->getSection()[0]->toHandle()
)->getConfig();
}
// Make sure we are passing the fully qualified class name as the section
if (count($options->getSection()) > 0) {
$optionsArray = $options->toArray();
$optionsArray[ReadOptions::SECTION] = (string)$sectionConfig->getFullyQualifiedClassName();
$options = ReadOptions::fromArray($optionsArray);
}
/** @var ReadSectionInterface $reader */
foreach ($this->readers as $reader) {
foreach ($reader->read($options, $sectionConfig) as $entry) {
$sectionData->append($entry);
}
}
$this->dispatcher->dispatch(
SectionDataRead::NAME,
new SectionDataRead($sectionData, $options, $sectionConfig)
);
return $sectionData;
} | php | {
"resource": ""
} |
q9850 | NativeLoop.nextTimeout | train | private function nextTimeout(): ?int
{
$time = \microtime(true);
while (!$this->scheduler->isEmpty()) {
list ($watcher, $scheduled) = $this->scheduler->top();
if ($watcher->enabled && $watcher->scheduled === $scheduled) {
return (int) \max(0, ($watcher->due - $time) * 1000000);
}
}
return null;
} | php | {
"resource": ""
} |
q9851 | NativeLoop.notifyPolls | train | private function notifyPolls(array $selected, array & $watchers): void
{
foreach ($selected as $k => $stream) {
$k = $k ?: (int) $stream;
if (isset($watchers[$k])) {
foreach ($watchers[$k] as $watcher) {
if (isset($watchers[$k][$watcher->id])) {
($watcher->callback)($watcher->id, $stream);
}
}
}
}
} | php | {
"resource": ""
} |
q9852 | AbstractView.addToContext | train | public function addToContext( string $key, $value, string $behavior ): View
{
switch ($behavior) {
case View::REPLACE:
$this->_context_[$key] = $value;
return $this;
case View::MERGE:
if(array_key_exists($key, $this->_context_)) {
$this->_context_ = array_merge_recursive($this->_context_, [$key => $value]);
return $this;
}
$this->_context_[$key] = $value;
return $this;
case View::ADD_ONLY:
if (array_key_exists($key, $this->_context_)) {
return $this;
}
$this->_context_[$key] = $value;
return $this;
case View::REPLACE_ONLY:
if (! array_key_exists($key, $this->_context_)) {
return $this;
}
$this->_context_[$key] = $value;
return $this;
case View::MERGE_ONLY:
if (! array_key_exists($key, $this->_context_)) {
return $this;
}
$this->_context_ = array_merge_recursive($this->_context_, [$key => $value]);
return $this;
default:
throw new InvalidContextAddingBehavior(
sprintf(
_('Invalid behavior "%s" for adding to the context of view "%s".'),
$key,
$this->_uri_
)
);
}
} | php | {
"resource": ""
} |
q9853 | AbstractView.assimilateContext | train | protected function assimilateContext(array $context = [])
{
$this->_context_ = $context;
foreach ($context as $key => $value) {
$this->$key = $value;
}
} | php | {
"resource": ""
} |
q9854 | FeatureTypeI18nTableMap.doDelete | train | public static function doDelete($values, ConnectionInterface $con = null)
{
if (null === $con) {
$con = Propel::getServiceContainer()->getWriteConnection(FeatureTypeI18nTableMap::DATABASE_NAME);
}
if ($values instanceof Criteria) {
// rename for clarity
$criteria = $values;
} elseif ($values instanceof \FeatureType\Model\FeatureTypeI18n) { // it's a model object
// create criteria based on pk values
$criteria = $values->buildPkeyCriteria();
} else { // it's a primary key, or an array of pks
$criteria = new Criteria(FeatureTypeI18nTableMap::DATABASE_NAME);
// primary key is composite; we therefore, expect
// the primary key passed to be an array of pkey values
if (count($values) == count($values, COUNT_RECURSIVE)) {
// array is not multi-dimensional
$values = array($values);
}
foreach ($values as $value) {
$criterion = $criteria->getNewCriterion(FeatureTypeI18nTableMap::ID, $value[0]);
$criterion->addAnd($criteria->getNewCriterion(FeatureTypeI18nTableMap::LOCALE, $value[1]));
$criteria->addOr($criterion);
}
}
$query = FeatureTypeI18nQuery::create()->mergeWith($criteria);
if ($values instanceof Criteria) { FeatureTypeI18nTableMap::clearInstancePool();
} elseif (!is_object($values)) { // it's a primary key, or an array of pks
foreach ((array) $values as $singleval) { FeatureTypeI18nTableMap::removeInstanceFromPool($singleval);
}
}
return $query->delete($con);
} | php | {
"resource": ""
} |
q9855 | LazyLoader.load | train | public function load($object)
{
if (get_class($object) !== $this->objectClass) {
throw new \LogicException(sprintf('Invalid object type. Expected "%s" but got "%s".', $this->objectClass, get_class($object)));
}
$hydrator = $this->objectManager->getHydratorFor($this->objectClass);
$hydrator->load($object);
} | php | {
"resource": ""
} |
q9856 | LazyLoader.loadProperty | train | public function loadProperty($object, $propertyName)
{
if (get_class($object) !== $this->objectClass) {
throw new \LogicException(sprintf('Invalid object type. Expected "%s" but got "%s".', $this->objectClass, get_class($object)));
}
if ($this->objectManager->isPropertyLoaded($object, $propertyName)) {
return;
}
$hydrator = $this->objectManager->getHydratorFor($this->objectClass);
$hydrator->loadProperty($object, $propertyName);
} | php | {
"resource": ""
} |
q9857 | Client.defer | train | public function defer($enable)
{
$this->deferred = $enable;
if (!$this->deferred && isset($this->request)) {
return $this->doSend();
}
} | php | {
"resource": ""
} |
q9858 | Client.doSend | train | private function doSend()
{
try {
if (!empty($this->sentContentIds) && count($this->sentContentIds) > $this->batchLimit) {
throw new InvalidCallException(sprintf("Request limit reached! Max %d requests per batch is accepted!", $this->batchLimit));
}
$response = $this->request->send();
$this->request = null;
if ($response instanceof ApiResponse) {
$response = [$response];
}
$responses = [];
$index = 0;
foreach ($response as $_response) {
$responses[$_response->id ?? $index] = $this->handleResponse($_response);
$index++;
}
foreach ($this->sentContentIds as $sentContentId) {
if (!array_key_exists($sentContentId, $responses)) {
$responses[$sentContentId] = new ApiResponse([
'success' => false,
'error' => new ResponseError([
'type' => BadGatewayHttpException::class,
'code' => ResponseError::ERRORCODE_HTTP_RESPONSE_ERROR,
'message' => ['httpError' => 'Sent content not found in response!'],
]),
]);
}
}
return $responses;
} finally {
$this->sentContentIds = [];
}
} | php | {
"resource": ""
} |
q9859 | FeatureFeatureTypeQuery.create | train | public static function create($modelAlias = null, $criteria = null)
{
if ($criteria instanceof \FeatureType\Model\FeatureFeatureTypeQuery) {
return $criteria;
}
$query = new \FeatureType\Model\FeatureFeatureTypeQuery();
if (null !== $modelAlias) {
$query->setModelAlias($modelAlias);
}
if ($criteria instanceof Criteria) {
$query->mergeWith($criteria);
}
return $query;
} | php | {
"resource": ""
} |
q9860 | FeatureFeatureTypeQuery.filterByFeatureId | train | public function filterByFeatureId($featureId = null, $comparison = null)
{
if (is_array($featureId)) {
$useMinMax = false;
if (isset($featureId['min'])) {
$this->addUsingAlias(FeatureFeatureTypeTableMap::FEATURE_ID, $featureId['min'], Criteria::GREATER_EQUAL);
$useMinMax = true;
}
if (isset($featureId['max'])) {
$this->addUsingAlias(FeatureFeatureTypeTableMap::FEATURE_ID, $featureId['max'], Criteria::LESS_EQUAL);
$useMinMax = true;
}
if ($useMinMax) {
return $this;
}
if (null === $comparison) {
$comparison = Criteria::IN;
}
}
return $this->addUsingAlias(FeatureFeatureTypeTableMap::FEATURE_ID, $featureId, $comparison);
} | php | {
"resource": ""
} |
q9861 | FeatureFeatureTypeQuery.filterByFeatureTypeId | train | public function filterByFeatureTypeId($featureTypeId = null, $comparison = null)
{
if (is_array($featureTypeId)) {
$useMinMax = false;
if (isset($featureTypeId['min'])) {
$this->addUsingAlias(FeatureFeatureTypeTableMap::FEATURE_TYPE_ID, $featureTypeId['min'], Criteria::GREATER_EQUAL);
$useMinMax = true;
}
if (isset($featureTypeId['max'])) {
$this->addUsingAlias(FeatureFeatureTypeTableMap::FEATURE_TYPE_ID, $featureTypeId['max'], Criteria::LESS_EQUAL);
$useMinMax = true;
}
if ($useMinMax) {
return $this;
}
if (null === $comparison) {
$comparison = Criteria::IN;
}
}
return $this->addUsingAlias(FeatureFeatureTypeTableMap::FEATURE_TYPE_ID, $featureTypeId, $comparison);
} | php | {
"resource": ""
} |
q9862 | FeatureFeatureTypeQuery.filterByFeature | train | public function filterByFeature($feature, $comparison = null)
{
if ($feature instanceof \Thelia\Model\Feature) {
return $this
->addUsingAlias(FeatureFeatureTypeTableMap::FEATURE_ID, $feature->getId(), $comparison);
} elseif ($feature instanceof ObjectCollection) {
if (null === $comparison) {
$comparison = Criteria::IN;
}
return $this
->addUsingAlias(FeatureFeatureTypeTableMap::FEATURE_ID, $feature->toKeyValue('PrimaryKey', 'Id'), $comparison);
} else {
throw new PropelException('filterByFeature() only accepts arguments of type \Thelia\Model\Feature or Collection');
}
} | php | {
"resource": ""
} |
q9863 | FeatureFeatureTypeQuery.useFeatureQuery | train | public function useFeatureQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN)
{
return $this
->joinFeature($relationAlias, $joinType)
->useQuery($relationAlias ? $relationAlias : 'Feature', '\Thelia\Model\FeatureQuery');
} | php | {
"resource": ""
} |
q9864 | FeatureFeatureTypeQuery.filterByFeatureTypeAvMeta | train | public function filterByFeatureTypeAvMeta($featureTypeAvMeta, $comparison = null)
{
if ($featureTypeAvMeta instanceof \FeatureType\Model\FeatureTypeAvMeta) {
return $this
->addUsingAlias(FeatureFeatureTypeTableMap::ID, $featureTypeAvMeta->getFeatureFeatureTypeId(), $comparison);
} elseif ($featureTypeAvMeta instanceof ObjectCollection) {
return $this
->useFeatureTypeAvMetaQuery()
->filterByPrimaryKeys($featureTypeAvMeta->getPrimaryKeys())
->endUse();
} else {
throw new PropelException('filterByFeatureTypeAvMeta() only accepts arguments of type \FeatureType\Model\FeatureTypeAvMeta or Collection');
}
} | php | {
"resource": ""
} |
q9865 | FeatureFeatureTypeQuery.useFeatureTypeAvMetaQuery | train | public function useFeatureTypeAvMetaQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN)
{
return $this
->joinFeatureTypeAvMeta($relationAlias, $joinType)
->useQuery($relationAlias ? $relationAlias : 'FeatureTypeAvMeta', '\FeatureType\Model\FeatureTypeAvMetaQuery');
} | php | {
"resource": ""
} |
q9866 | Router.map | train | public function map($method, string $route, string $action, string $controller)
{
// alias
$proxy = $this->proxy_factory;
if (!\is_array($method)) {
$method = [(string)$method];
}
// whitelist http methods
\array_walk($method, function ($v) {
if (!\in_array($v, ['GET', 'POST', 'PUT', 'DELETE'])) {
throw new \InvalidArgumentException(\sprintf('Unknown http method: "%s"', $v));
}
});
foreach ($method as $m) {
$this->klein->respond($m, $route, function ($request, $response) use (&$proxy, $action, $controller) {
return $proxy($controller)
->setRequest($request)
->setResponse($response)
->$action();
});
}
return $this;
} | php | {
"resource": ""
} |
q9867 | Router.dispatch | train | public function dispatch(Request $request, ControllerFactory $actual_factory)
{
$this->proxy_factory
->replace($actual_factory)
->close();
$this->klein->dispatch($request);
} | php | {
"resource": ""
} |
q9868 | SecurityContext.add | train | public function add(SecurityContextConfiguration $configuration)
{
$this->contexts[$configuration->getName()] = $configuration;
$this->updateMappings(
$configuration,
$this->container->make(EntityManagerInterface::class)
);
} | php | {
"resource": ""
} |
q9869 | SecurityContext.bindContext | train | public function bindContext($context, Request $request)
{
$security = $this->getSecurity($context);
$this->container->instance(SecurityApi::class, $security);
$this->container->bind(UrlGeneratorContract::class, function() use ($security){
return $security->url();
});
$this->container->bind(UrlGenerator::class, function(Container $container) use ($security){
/** @var PermissionAwareUrlGeneratorExtension $url */
$url = $container->make(PermissionAwareUrlGeneratorExtension::class);
$url->setUrlGenerator($security->url());
return $url;
});
$this->container->alias(UrlGenerator::class, 'url');
$request->setUserResolver(function() use ($security){
return $security->getUser();
});
} | php | {
"resource": ""
} |
q9870 | SecurityContext.getSecurity | train | public function getSecurity($context)
{
if (array_key_exists($context, $this->instances))
{
return $this->instances[$context];
}
$configuration = $this->getConfigurationFor($context);
$this->addPermissionsFactoryListener($context);
return $this->instances[$context] = $this->getSecurityFactory()->create($context, $configuration);
} | php | {
"resource": ""
} |
q9871 | ExampleGroup.runHooks | train | public function runHooks($name, AbstractContext $context, $reverse = false)
{
$parent = $this->getParent();
$hooks = $this->hooks[$name];
if ($reverse) {
foreach (array_reverse($hooks) as $hook) {
$hook->run($context);
}
if ($parent) {
$parent->runHooks($name, $context, $reverse);
}
} else {
if ($parent) {
$parent->runHooks($name, $context, $reverse);
}
foreach ($hooks as $hook) {
$hook->run($context);
}
}
} | php | {
"resource": ""
} |
q9872 | ExampleGroup.total | train | public function total()
{
$total = array_reduce($this->examples, function($x, $e) {
$x += $e instanceof Example ? 1 : $e->total();
return $x;
}, 0);
return $total;
} | php | {
"resource": ""
} |
q9873 | ExampleGroup.setErrorHandler | train | public function setErrorHandler()
{
set_error_handler(function ($errno, $errstr, $errfile, $errline ) {
throw new \ErrorException($errstr, 0, $errno, $errfile, $errline);
});
} | php | {
"resource": ""
} |
q9874 | PSCWS4._rule_get | train | function _rule_get($str) {
if (!isset($this->_rd[$str])) return false;
return $this->_rd[$str];
} | php | {
"resource": ""
} |
q9875 | PSCWS4._rule_checkbit | train | function _rule_checkbit($str, $bit) {
if (!isset($this->_rd[$str])) return false;
$bit2 = $this->_rd[$str]['bit'];
return ($bit & $bit2 ? true : false);
} | php | {
"resource": ""
} |
q9876 | PSCWS4._rule_check | train | function _rule_check($rule, $str) {
if (($rule['flag'] & PSCWS4_ZRULE_INCLUDE) && !$this->_rule_checkbit($str, $rule['bit']))
return false;
if (($rule['flag'] & PSCWS4_ZRULE_EXCLUDE) && $this->_rule_checkbit($str, $rule['bit']))
return false;
return true;
} | php | {
"resource": ""
} |
q9877 | PSCWS4._dict_query | train | function _dict_query($word) {
if (!$this->_xd) return false;
$value = $this->_xd->Get($word);
if (!$value) return false;
$tmp = unpack('ftf/fidf/Cflag/a3attr', $value);
return $tmp;
} | php | {
"resource": ""
} |
q9878 | PSCWS4._get_zs | train | function _get_zs($i, $j = -1) {
if ($j == -1) $j = $i;
return substr($this->_txt, $this->_zmap[$i]['start'], $this->_zmap[$j]['end'] - $this->_zmap[$i]['start']);
} | php | {
"resource": ""
} |
q9879 | FosUser.setSalt | train | public function setSalt( $value )
{
if( (string) $value !== $this->getSalt() )
{
$this->values['salt'] = (string) $value;
$this->setModified();
}
return $this;
} | php | {
"resource": ""
} |
q9880 | ResponseParser.parse | train | public function parse(Context $context, ?Request $request = null): \Generator
{
$header = \unpack('nid/nflags/nqc/nac/nauth/nadd', yield $this->stream->readBuffer($context, 12));
$this->offset += 12;
$response = new Response($header['id']);
$response->setFlags($header['flags']);
if ($request && $response->getId() !== $request->getId()) {
throw new \RuntimeException(\sprintf('Expected DNS message ID is %u, server returned %u', $request->getId(), $response->getId()));
}
$response->setAuthorityCount($header['auth']);
$response->setAdditionalCount($header['add']);
// Parse questions:
for ($i = 0; $i < $header['qc']; $i++) {
yield from $this->parseQuestion($context, $response);
}
if ($request && $response->getQuestions() !== $request->getQuestions()) {
throw new \RuntimeException('DNS server did not return the question(s) in the response message');
}
// Parse answers:
for ($i = 0; $i < $header['ac']; $i++) {
yield from $this->parseAnswer($context, $response);
}
return $response;
} | php | {
"resource": ""
} |
q9881 | ResponseParser.parseQuestion | train | protected function parseQuestion(Context $context, Response $response): \Generator
{
$host = yield from $this->readLabel($context);
$question = \unpack('ntype/nclass', yield $this->stream->readBuffer($context, 4));
$this->offset += 4;
$response->addQuestion($host, $question['type'], $question['class']);
} | php | {
"resource": ""
} |
q9882 | ResponseParser.parseAnswer | train | protected function parseAnswer(Context $context, Response $response): \Generator
{
$host = yield from $this->readLabel($context);
$answer = \unpack('ntype/nclass/Nttl/nlen', yield $this->stream->readBuffer($context, 10));
$this->offset += 10;
$ttl = $answer['ttl'];
$len = $answer['len'];
// Discard payloads of truncated messages.
if ($response->isTruncated()) {
$data = yield $this->stream->readBuffer($context, $len);
$this->offset += $len;
return;
}
switch ($answer['type']) {
case Message::TYPE_A:
case Message::TYPE_AAAA:
$data = \inet_ntop(yield $this->stream->readBuffer($context, $len));
$this->offset += $len;
break;
case Message::TYPE_CNAME:
$data = yield from $this->readLabel($context);
break;
default:
$data = yield $this->stream->readBuffer($context, $len);
$this->offset += $len;
}
if ($ttl & 0x80000000) {
$ttl = ($ttl - 0xFFFFFFFF);
}
$response->addAnswer($host, $answer['type'], $answer['class'], $data, $ttl);
} | php | {
"resource": ""
} |
q9883 | State.nextOutdent | train | public function nextOutdent()
{
$oldLevel = $this->getIndentLevel();
$expected = $this->getLevel();
if ($expected < $oldLevel) {
$newLevel = $this->outdent();
if ($newLevel < $expected) {
$this->throwException(
'Inconsistent indentation. '.
'Expecting either '.
$newLevel.
' or '.
$oldLevel.
' spaces/tabs.'
);
}
return $newLevel;
}
return false;
} | php | {
"resource": ""
} |
q9884 | State.indent | train | public function indent($level = null)
{
$level = $level ?: $this->getLevel();
array_push($this->indentStack, $level);
return $level;
} | php | {
"resource": ""
} |
q9885 | State.scan | train | public function scan($scanners)
{
$scanners = $this->filterScanners($scanners);
foreach ($scanners as $key => $scanner) {
/** @var ScannerInterface $scanner */
$success = false;
foreach ($scanner->scan($this) as $token) {
if (!($token instanceof TokenInterface)) {
$this->throwException(
'Scanner '.get_class($scanner).' generated a result that is not a '.TokenInterface::class
);
}
yield $token;
$success = true;
}
if ($success) {
return;
}
}
} | php | {
"resource": ""
} |
q9886 | State.loopScan | train | public function loopScan($scanners, $required = false)
{
while ($this->reader->hasLength()) {
$success = false;
foreach ($this->scan($scanners) as $token) {
$success = true;
yield $token;
}
if (!$success) {
break;
}
}
if ($this->reader->hasLength() && $required) {
$this->throwException(
'Unexpected '.$this->reader->peek(20)
);
}
} | php | {
"resource": ""
} |
q9887 | State.createToken | train | public function createToken($className)
{
if (!is_subclass_of($className, TokenInterface::class)) {
$this->throwException(
"$className is not a valid token sub-class"
);
}
return new $className(
$this->createCurrentSourceLocation(),
$this->level,
str_repeat($this->getIndentStyle(), $this->getIndentWidth())
);
} | php | {
"resource": ""
} |
q9888 | State.scanToken | train | public function scanToken($className, $pattern, $modifiers = null)
{
if (!$this->reader->match($pattern, $modifiers)) {
return;
}
$data = $this->reader->getMatchData();
$token = $this->createToken($className);
$this->reader->consume();
foreach ($data as $key => $value) {
$method = 'set'.ucfirst($key);
if (method_exists($token, $method)) {
call_user_func([$token, $method], $value);
}
}
yield $this->endToken($token);
} | php | {
"resource": ""
} |
q9889 | State.filterScanners | train | private function filterScanners($scanners)
{
$scannerInstances = [];
$scanners = is_array($scanners) ? $scanners : [$scanners];
foreach ($scanners as $key => $scanner) {
if (!is_a($scanner, ScannerInterface::class, true)) {
throw new \InvalidArgumentException(
"The passed scanner with key `$key` doesn't seem to be either a valid ".ScannerInterface::class.
' instance or extended class'
);
}
$scannerInstances[] = $scanner instanceof ScannerInterface
? $scanner
: new $scanner();
}
return $scannerInstances;
} | php | {
"resource": ""
} |
q9890 | ResponseService.getRedirectResponse | train | public function getRedirectResponse(string $routeName, array $routeParameters = []): RedirectResponse
{
$url = $this->router->generate($routeName, $routeParameters);
return new RedirectResponse($url);
} | php | {
"resource": ""
} |
q9891 | CategorizeServiceProvider.registerCategoryProvider | train | protected function registerCategoryProvider()
{
$this->app['categorize.category'] = $this->app->share(function($app)
{
$model = $app['config']->get('categorize::categories.model');
return new CategoryProvider($model);
});
} | php | {
"resource": ""
} |
q9892 | CategorizeServiceProvider.registerCategoryHierarchyProvider | train | protected function registerCategoryHierarchyProvider()
{
$this->app['categorize.categoryHierarchy'] = $this->app->share(function($app)
{
$model = $app['config']->get('categorize::categoryHierarchy.model');
return new CategoryHierarchyProvider($model);
});
} | php | {
"resource": ""
} |
q9893 | CategorizeServiceProvider.registerCategoryRelateProvider | train | protected function registerCategoryRelateProvider()
{
$this->app['categorize.categoryRelate'] = $this->app->share(function($app)
{
$model = $app['config']->get('categorize::categoryRelates.model');
return new CategoryRelateProvider($model);
});
} | php | {
"resource": ""
} |
q9894 | SitemapService.configureRobotsFile | train | protected function configureRobotsFile(RobotsFileInterface $robots)
{
$robots->setCrawlDelay($this->robots['crawl_delay']);
foreach ($this->robots['allow'] as $path => $userAgent) {
if (strpos($path, '/') === false) {
$path = $this->router->generate($path);
}
$robots->addAllowEntry($path, $userAgent);
}
foreach ($this->robots['disallow'] as $path => $userAgent) {
if (strpos($path, '/') === false) {
$path = $this->router->generate($path);
}
$robots->addDisallowEntry($path, $userAgent);
}
foreach ($this->robots['clean_param'] as $path => $value) {
$robots->addCleanParamEntry($value['parameters'], $path);
}
} | php | {
"resource": ""
} |
q9895 | DoctrineThrottleRepository.bulkSave | train | protected function bulkSave(array $throttles)
{
$entityManager = $this->getEntityManager();
foreach ($throttles as $throttle)
{
$entityManager->persist($throttle);
}
$entityManager->flush();
} | php | {
"resource": ""
} |
q9896 | sfWidgetFormSelect2PropelChoiceSortable.configure | train | protected function configure($options = array(), $attributes = array())
{
$this->addOption('culture', sfContext::getInstance()->getUser()->getCulture());
$this->addOption('width', sfConfig::get('sf_sfSelect2Widgets_width'));
$this->addRequiredOption('model');
$this->addOption('add_empty', false);
$this->addOption('method', '__toString');
$this->addOption('key_method', 'getPrimaryKey');
$this->addOption('order_by', null);
$this->addOption('query_methods', array());
$this->addOption('criteria', null);
$this->addOption('connection', null);
$this->addOption('multiple', false);
// not used anymore
$this->addOption('peer_method', 'doSelect');
parent::configure($options, $attributes);
$this->setOption('type', 'hidden');
} | php | {
"resource": ""
} |
q9897 | DoctrinePersistenceRepository.findUserByPersistenceCode | train | public function findUserByPersistenceCode($code)
{
$persistence = $this->findByPersistenceCode($code);
if ($persistence)
{
return $persistence->getUser();
}
return false;
} | php | {
"resource": ""
} |
q9898 | DoctrinePersistenceRepository.persist | train | public function persist(PersistableInterface $persistable, $remember = false)
{
try
{
if ($this->single)
{
$this->flush($persistable);
}
$code = $persistable->generatePersistenceCode();
$this->session->put($code);
if ($remember === true) {
$this->cookie->put($code);
}
$persistence = $this->create($persistable, $code);
$entityManager = $this->getEntityManager();
$entityManager->persist($persistence);
$entityManager->flush();
return true;
}
catch (\Exception $e)
{
return false;
}
} | php | {
"resource": ""
} |
q9899 | DoctrinePersistenceRepository.remove | train | public function remove($code)
{
$entityManager = $this->getEntityManager();
$queryBuilder = $entityManager->createQueryBuilder();
$queryBuilder
->delete($this->entityName(), 'p')
->where('p.code = :code')
->setParameter('code', $code);
return $queryBuilder->getQuery()->execute();
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.