_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q8400
Initializations.initStrictExceptionsMode
train
protected static function initStrictExceptionsMode ($strictExceptionsMode) { $errorLevelsToExceptions = []; if ($strictExceptionsMode !== FALSE) { $sysCfgDebug = static::getSystemCfgDebugSection(); if (isset($sysCfgDebug['strictExceptions'])) { $rawStrictExceptions = $sysCfgDebug['strictExceptions']; $rawStrictExceptions = is_array($rawStrictExceptions) ? $rawStrictExceptions : explode(',', trim($rawStrictExceptions, '[]')); $errorLevelsToExceptions = array_map( function ($rawErrorLevel) { $rawErrorLevel = trim($rawErrorLevel); if (is_numeric($rawErrorLevel)) return intval($rawErrorLevel); return constant($rawErrorLevel); }, $rawStrictExceptions ); } else { $errorLevelsToExceptions = self::$strictExceptionsModeDefaultLevels; } } return self::SetStrictExceptionsMode($strictExceptionsMode, $errorLevelsToExceptions); }
php
{ "resource": "" }
q8401
Initializations.initHandlers
train
protected static function initHandlers () { $className = version_compare(PHP_VERSION, '5.5', '>') ? static::class : get_called_class(); foreach (static::$handlers as $key => $value) { static::$handlers[$key] = [$className, $value]; } register_shutdown_function(static::$handlers['shutdownHandler']); }
php
{ "resource": "" }
q8402
Initializations.initLogDirectory
train
protected static function initLogDirectory () { //if (static::$logDirectoryInitialized) return; $sysCfgDebug = static::getSystemCfgDebugSection(); $logDirConfiguredPath = isset($sysCfgDebug['logDirectory']) ? $sysCfgDebug['logDirectory'] : static::$LogDirectory; if (mb_substr($logDirConfiguredPath, 0, 1) === '~') { $app = static::$app ?: (static::$app = & \MvcCore\Application::GetInstance()); $logDirAbsPath = $app->GetRequest()->GetAppRoot() . '/' . ltrim(mb_substr($logDirConfiguredPath, 1), '/'); } else { $logDirAbsPath = $logDirConfiguredPath; } static::$LogDirectory = $logDirAbsPath; try { if (!is_dir($logDirAbsPath)) { $selfClass = version_compare(PHP_VERSION, '5.5', '>') ? self::class : __CLASS__; if (!mkdir($logDirAbsPath, 0777, TRUE)) throw new \RuntimeException( '['.$selfClass."] It was not possible to create log directory: `".$logDirAbsPath."`." ); if (!is_writable($logDirAbsPath)) if (!chmod($logDirAbsPath, 0777)) throw new \RuntimeException( '['.$selfClass."] It was not possible to setup privileges to log directory: `".$logDirAbsPath."` to writeable mode 0777." ); } } catch (\Exception $e) { $selfClass = version_compare(PHP_VERSION, '5.5', '>') ? self::class : __CLASS__; die('['.$selfClass.'] ' . $e->getMessage()); } static::$logDirectoryInitialized = TRUE; return $logDirAbsPath; }
php
{ "resource": "" }
q8403
Instancing.&
train
public function & InitAll () { /** @var $this \MvcCore\Request */ $this->GetScriptName(); $this->GetAppRoot(); $this->GetMethod(); $this->GetBasePath(); $this->GetScheme(); $this->IsSecure(); $this->GetHostName(); $this->GetHost(); $this->GetRequestPath(); $this->GetFullUrl(); $this->GetReferer(); $this->GetMicrotime(); $this->IsAjax(); if ($this->port === NULL) $this->initUrlSegments(); if ($this->headers === NULL) $this->initHeaders(); if ($this->params === NULL) $this->initParams(); $this->GetServerIp(); $this->GetClientIp(); $this->GetContentLength(); return $this; }
php
{ "resource": "" }
q8404
Configuration.createResolver
train
public function createResolver() { $resolver = $this->getResolver(); if (isset($resolver)) { $resolver_class = get_class($resolver); // Create new retriever. $retriever = $resolver->getUriRetriever(); if (isset($retriever)) { $retriever_class = get_class($retriever); $new_retriever = new $retriever_class(); } else { $new_retriever = new UriRetriever(); } // Store max depth before init since maxDepth is set on the parent. $max_depth = $resolver::$maxDepth; // Create new resolver. $new_resolver = new $resolver_class($new_retriever); // Sync public static properties. $new_resolver::$maxDepth = $max_depth; } else { $new_retriever = new UriRetriever(); $new_resolver = new RefResolver($new_retriever); } return $new_resolver; }
php
{ "resource": "" }
q8405
DatabaseQuery.handle
train
public function handle(LogManager $logger): void { $db = \resolve('db'); $callback = $this->buildQueryCallback($logger); foreach ($db->getQueryLog() as $query) { $callback(new QueryExecuted($query['query'], $query['bindings'], $query['time'], $db)); } \resolve(Dispatcher::class)->listen(QueryExecuted::class, $callback); }
php
{ "resource": "" }
q8406
DatabaseQuery.buildQueryCallback
train
protected function buildQueryCallback(LogManager $logger): callable { return function (QueryExecuted $query) use ($logger) { $sql = Str::replaceArray('?', $query->connection->prepareBindings($query->bindings), $query->sql); $logger->info("<comment>{$sql} [{$query->time}ms]</comment>"); }; }
php
{ "resource": "" }
q8407
UrlRewriteSubject.storeIsActive
train
public function storeIsActive($storeViewCode) { // query whether or not, the requested store is available if (isset($this->stores[$storeViewCode])) { return 1 === (integer) $this->stores[$storeViewCode][MemberNames::IS_ACTIVE]; } // throw an exception, if not throw new \Exception( $this->appendExceptionSuffix( sprintf('Found invalid store view code %s', $storeViewCode) ) ); }
php
{ "resource": "" }
q8408
InternalInits.initReverseParamsGetGreedyInfo
train
protected function initReverseParamsGetGreedyInfo (& $reverseSectionsInfo, & $constraints, & $paramName, & $sectionIndex, & $greedyCaught) { // complete greedy flag by star character inside param name $greedyFlag = mb_strpos($paramName, '*') !== FALSE; $sectionIsLast = NULL; // check greedy param specifics if ($greedyFlag) { if ($greedyFlag && $greedyCaught) { $selfClass = version_compare(PHP_VERSION, '5.5', '>') ? self::class : __CLASS__; throw new \InvalidArgumentException( "[".$selfClass."] Route pattern definition can have only one greedy `<param_name*>` " ." with star (to include everything - all characters and slashes . `.*`) ($this)." ); } $reverseSectionsCount = count($reverseSectionsInfo); $sectionIndexPlusOne = $sectionIndex + 1; if (// next section is optional $sectionIndexPlusOne < $reverseSectionsCount && !($reverseSectionsInfo[$sectionIndexPlusOne]->fixed) ) { // check if param is really greedy or not $constraintDefined = isset($constraints[$paramName]); $constraint = $constraintDefined ? $constraints[$paramName] : NULL ; $greedyReal = !$constraintDefined || ($constraintDefined && ( mb_strpos($constraint, '.*') !== FALSE || mb_strpos($constraint, '.+') !== FALSE )); if ($greedyReal) { $selfClass = version_compare(PHP_VERSION, '5.5', '>') ? self::class : __CLASS__; throw new \InvalidArgumentException( "[".$selfClass."] Route pattern definition can not have greedy `<param_name*>` with star " ."(to include everything - all characters and slashes . `.*`) immediately before optional " ."section ($this)." ); } } $greedyCaught = TRUE; $paramName = str_replace('*', '', $paramName); $sectionIsLast = $sectionIndexPlusOne === $reverseSectionsCount; } return [$greedyFlag, $sectionIsLast]; }
php
{ "resource": "" }
q8409
InternalInits.initFlagsByPatternOrReverse
train
protected function initFlagsByPatternOrReverse ($pattern) { $scheme = static::FLAG_SCHEME_NO; if (mb_strpos($pattern, '//') === 0) { $scheme = static::FLAG_SCHEME_ANY; } else if (mb_strpos($pattern, 'http://') === 0) { $scheme = static::FLAG_SCHEME_HTTP; } else if (mb_strpos($pattern, 'https://') === 0) { $scheme = static::FLAG_SCHEME_HTTPS; } $host = static::FLAG_HOST_NO; if ($scheme) { if (mb_strpos($pattern, static::PLACEHOLDER_HOST) !== FALSE) { $host = static::FLAG_HOST_HOST; } else if (mb_strpos($pattern, static::PLACEHOLDER_DOMAIN) !== FALSE) { $host = static::FLAG_HOST_DOMAIN; } else { if (mb_strpos($pattern, static::PLACEHOLDER_TLD) !== FALSE) $host += static::FLAG_HOST_TLD; if (mb_strpos($pattern, static::PLACEHOLDER_SLD) !== FALSE) $host += static::FLAG_HOST_SLD; } if (mb_strpos($pattern, static::PLACEHOLDER_BASEPATH) !== FALSE) $host += static::FLAG_HOST_BASEPATH; } $queryString = mb_strpos($pattern, '?') !== FALSE ? static::FLAG_QUERY_INCL : static::FLAG_QUERY_NO; $this->flags = [$scheme, $host, $queryString]; }
php
{ "resource": "" }
q8410
InternalInits.throwExceptionIfKeyPropertyIsMissing
train
protected function throwExceptionIfKeyPropertyIsMissing ($propsNames) { $propsNames = func_get_args(); $selfClass = version_compare(PHP_VERSION, '5.5', '>') ? self::class : __CLASS__; throw new \LogicException( "[".$selfClass."] Route configuration property/properties is/are" ." missing: `" . implode("`, `", $propsNames) . "`, to parse and" ." complete key properties `match` and/or `reverse` to route" ." or build URL correctly ($this)." ); }
php
{ "resource": "" }
q8411
Cookies.SetCookie
train
public function SetCookie ( $name, $value, $lifetime = 0, $path = '/', $domain = NULL, $secure = NULL, $httpOnly = TRUE ) { if ($this->IsSent()) { $selfClass = version_compare(PHP_VERSION, '5.5', '>') ? self::class : __CLASS__; throw new \RuntimeException( "[".$selfClass."] Cannot set cookie after HTTP headers have been sent." ); } $request = \MvcCore\Application::GetInstance()->GetRequest(); return \setcookie( $name, $value, $lifetime === 0 ? 0 : time() + $lifetime, $path, $domain === NULL ? $request->GetHostName() : $domain, $secure === NULL ? $request->IsSecure() : $secure, $httpOnly ); }
php
{ "resource": "" }
q8412
Cookies.DeleteCookie
train
public function DeleteCookie ($name, $path = '/', $domain = NULL, $secure = NULL) { return $this->SetCookie($name, '', 0, $path, $domain, $secure); }
php
{ "resource": "" }
q8413
AttributeTrait.withAttribute
train
public function withAttribute($key, $value) { $newAttributes = $this->attributes->withAttribute($key, $value); $that = clone($this); $that->attributes = $newAttributes; return $that; }
php
{ "resource": "" }
q8414
AttributeTrait.withoutAttribute
train
public function withoutAttribute($key) { $newAttributes = $this->attributes->withoutAttribute($key); $that = clone($this); $that->attributes = $newAttributes; return $that; }
php
{ "resource": "" }
q8415
HttpRequest.createCurl
train
protected function createCurl() { $ch = curl_init(); // Add the body first so we can calculate a content length. $body = ''; if ($this->method === self::METHOD_HEAD) { curl_setopt($ch, CURLOPT_NOBODY, true); } elseif ($this->method !== self::METHOD_GET) { curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $this->method); $body = $this->makeCurlBody(); if ($body) { curl_setopt($ch, CURLOPT_POSTFIELDS, $body); } } // Decode the headers. $headers = []; foreach ($this->getHeaders() as $key => $values) { foreach ($values as $line) { $headers[] = "$key: $line"; } } if (is_string($body) && !$this->hasHeader('Content-Length')) { $headers[] = 'Content-Length: '.strlen($body); } if (!$this->hasHeader('Expect')) { $headers[] = 'Expect:'; } curl_setopt( $ch, CURLOPT_HTTP_VERSION, $this->getProtocolVersion() == '1.0' ? CURL_HTTP_VERSION_1_0 : CURL_HTTP_VERSION_1_1 ); curl_setopt($ch, CURLOPT_URL, $this->url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_TIMEOUT, $this->getTimeout()); curl_setopt($ch, CURLOPT_MAXREDIRS, 10); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_HEADER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $this->verifyPeer); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, $this->verifyPeer ? 2 : 0); curl_setopt($ch, CURLOPT_ENCODING, ''); //"utf-8"); curl_setopt($ch, CURLOPT_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS); if (!empty($this->auth)) { curl_setopt($ch, CURLOPT_USERPWD, $this->auth[0].":".((empty($this->auth[1])) ? "" : $this->auth[1])); } return $ch; }
php
{ "resource": "" }
q8416
HttpRequest.makeCurlBody
train
protected function makeCurlBody() { $body = $this->body; if (is_string($body)) { return (string)$body; } $contentType = $this->getHeader('Content-Type'); if (stripos($contentType, 'application/json') === 0) { $body = json_encode($body); } return $body; }
php
{ "resource": "" }
q8417
HttpRequest.execCurl
train
protected function execCurl($ch) { curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HEADER, true); $response = curl_exec($ch); // Split the full response into its headers and body $info = curl_getinfo($ch); $code = $info["http_code"]; if ($response) { $header_size = $info["header_size"]; $rawHeaders = substr($response, 0, $header_size); $status = null; $rawBody = substr($response, $header_size); } else { $status = $code; $rawHeaders = []; $rawBody = curl_error($ch); } $result = new HttpResponse($status, $rawHeaders, $rawBody); $result->setRequest($this); return $result; }
php
{ "resource": "" }
q8418
RGBColor.isValidChannelValue
train
public function isValidChannelValue($value, $channel) { if (!in_array($channel, self::$channels)) { throw new \InvalidArgumentException('Invalid Channel Name'); } if ($channel == self::CHANNEL_ALPHA) { if ($value >= 0 && $value <= 127) { return true; } } else { if ($value >= 0 && $value <= 255) { return true; } } return false; }
php
{ "resource": "" }
q8419
RGBColor.setAlpha
train
public function setAlpha($alpha) { $this->assertChannelValue($alpha, self::CHANNEL_ALPHA); $this->alpha = $alpha; return $this; }
php
{ "resource": "" }
q8420
RGBColor.setRed
train
public function setRed($value) { $this->assertChannelValue($value, self::CHANNEL_RED); $this->red = $value; return $this; }
php
{ "resource": "" }
q8421
RGBColor.setGreen
train
public function setGreen($value) { $this->assertChannelValue($value, self::CHANNEL_GREEN); $this->green = $value; return $this; }
php
{ "resource": "" }
q8422
RGBColor.setBlue
train
public function setBlue($value) { $this->assertChannelValue($value, self::CHANNEL_BLUE); $this->blue = $value; return $this; }
php
{ "resource": "" }
q8423
RGBColor.getValue
train
public function getValue() { return (((int) $this->getRed() & 0xFF) << 16) | (((int) $this->getGreen() & 0xFF) << 8) | (((int) $this->getBlue() & 0xFF)) | (((int) $this->getAlpha() & 0xFF) << 24); }
php
{ "resource": "" }
q8424
RGBColor.setFromRGBColor
train
public function setFromRGBColor(RGBColor $color) { return $this->setRed($color->getRed()) ->setGreen($color->getGreen()) ->setBlue($color->getBlue()) ->setAlpha($color->getAlpha()); }
php
{ "resource": "" }
q8425
RGBColor.setFromArray
train
public function setFromArray(array $color) { return $this->setRed($color[0]) ->setGreen($color[1]) ->setBlue($color[2]) ->setAlpha($color[3]); }
php
{ "resource": "" }
q8426
RGBColor.setFromValue
train
public function setFromValue($rgb, $hasalpha = true) { $r = ($rgb >> 16) & 0xFF; $g = ($rgb >> 8) & 0xFF; $b = ($rgb >> 0) & 0xFF; if ($hasalpha) { $a = ($rgb >> 24) & 0xff; return $this->setRed($r) ->setGreen($g) ->setBlue($b) ->setAlpha($a); } return $this->setRed($r) ->setGreen($g) ->setBlue($b); }
php
{ "resource": "" }
q8427
RGBColor.setFromHex
train
public function setFromHex($hex, $alpha = 0) { if (!preg_match(self::$HexRegex, $hex)) { throw new \InvalidArgumentException(sprintf( 'Inavlid Hex Color "%s"', $hex )); } $ehex = ltrim($hex, '#'); if (strlen($ehex) === 3) { $ehex = $ehex[0] . $ehex[0] . $ehex[1] . $ehex[1] . $ehex[2] . $ehex[2]; } $color = array_map('hexdec', str_split($ehex, 2)); return $this->setRed($color[0]) ->setGreen($color[1]) ->setBlue($color[2]) ->setAlpha($alpha); }
php
{ "resource": "" }
q8428
RGBColor.getRGBColor
train
public function getRGBColor() { return new self( $this->getRed() , $this->getGreen() , $this->getBlue() , $this->getAlpha() ); }
php
{ "resource": "" }
q8429
RGBColor.brighter
train
public function brighter($shade = 0.7) { $r = $this->getRed(); $g = $this->getGreen(); $b = $this->getBlue(); $alpha = $this->getAlpha(); $i = (integer) (1.0 / (1.0 - $shade)); if ($r == 0 && $g == 0 && $b == 0) { return new self($i, $i, $i, $alpha); } if ($r > 0 && $r < $i) $r = $i; if ($g > 0 && $g < $i) $g = $i; if ($b > 0 && $b < $i) $b = $i; return $this->setFromArray(array( min(array((integer) ($r / $shade), 255)) , min(array((integer) ($g / $shade), 255)) , min(array((integer) ($b / $shade), 255)) , $alpha )); }
php
{ "resource": "" }
q8430
RGBColor.darker
train
public function darker($shade = 0.7) { return $this->setFromArray(array( max(array((integer) $this->getRed() * $shade, 0)) , max(array((integer) $this->getGreen() * $shade, 0)) , max(array((integer) $this->getBlue() * $shade, 0)) , $this->getAlpha() )); }
php
{ "resource": "" }
q8431
RGBColor.blend
train
public function blend(RGBColor $color, $amount) { return $this->setFromArray(array( min(255, min($this->getRed(), $color->getRed()) + round(abs($color->getRed() - $this->getRed()) * $amount)) , min(255, min($this->getGreen(), $color->getGreen()) + round(abs($color->getGreen() - $this->getGreen()) * $amount)) , min(255, min($this->getBlue(), $color->getBlue()) + round(abs($color->getBlue() - $this->getBlue()) * $amount)) , min(100, min($this->getAlpha(), $color->getAlpha()) + round(abs($color->getAlpha() - $this->getAlpha()) * $amount)) )); }
php
{ "resource": "" }
q8432
RGBColor.grayscale
train
public function grayscale() { $gray = min( 255 , round( 0.299 * $this->getRed() + 0.587 * $this->getGreen() + 0.114 * $this->getBlue() ) ); return $this->setFromArray(array( $gray, $gray, $gray, $this->getAlpha() )); }
php
{ "resource": "" }
q8433
RGBColor.assertChannelValue
train
protected function assertChannelValue($value, $channel) { if (!$this->isValidChannelValue($value, $channel)) { throw new \InvalidArgumentException( sprintf('Invalid Value "%s" For The %s Channel' , $value, ucfirst($value)) ); } return $this; }
php
{ "resource": "" }
q8434
BuildMetaModelOperationsListener.buildCommand
train
private function buildCommand($attribute, array $propertyData) { if ($attribute->get('check_listview') == 1) { $commandName = 'listviewtoggle_' . $attribute->getColName(); } else { $commandName = 'publishtoggle_' . $attribute->getColName(); } $toggle = new ToggleCommand(); $toggle->setName($commandName); $toggle->setLabel($GLOBALS['TL_LANG']['MSC']['metamodelattribute_checkbox']['toggle'][0]); $toggle->setDescription( \sprintf( $GLOBALS['TL_LANG']['MSC']['metamodelattribute_checkbox']['toggle'][1], $attribute->getName() ) ); $extra = $toggle->getExtra(); $extra['icon'] = 'visible.svg'; $objIconEnabled = FilesModel::findByUuid($attribute->get('check_listviewicon')); $objIconDisabled = FilesModel::findByUuid($attribute->get('check_listviewicondisabled')); if ($attribute->get('check_listview') == 1 && $objIconEnabled->path && $objIconDisabled->path) { $extra['icon'] = $objIconEnabled->path; $extra['icon_disabled'] = $objIconDisabled->path; } else { $extra['icon'] = 'visible.svg'; } $toggle->setToggleProperty($attribute->getColName()); if ($attribute->get('check_inverse') == 1) { $toggle->setInverse(true); } if (!empty($propertyData['eval']['readonly'])) { $toggle->setDisabled(true); } return $toggle; }
php
{ "resource": "" }
q8435
BuildMetaModelOperationsListener.createBackendViewDefinition
train
protected function createBackendViewDefinition($container) { if ($container->hasDefinition(Contao2BackendViewDefinitionInterface::NAME)) { $view = $container->getDefinition(Contao2BackendViewDefinitionInterface::NAME); } else { $view = new Contao2BackendViewDefinition(); $container->setDefinition(Contao2BackendViewDefinitionInterface::NAME, $view); } return $view; }
php
{ "resource": "" }
q8436
BuildMetaModelOperationsListener.handle
train
public function handle(BuildMetaModelOperationsEvent $event) { if (!$this->scopeMatcher->currentScopeIsBackend()) { return; } $allProps = $event->getScreen()['properties']; $properties = \array_map(function ($property) { return ($property['col_name'] ?? null); }, $allProps); foreach ($event->getMetaModel()->getAttributes() as $attribute) { if (!$this->wantToAdd($attribute, $properties)) { continue; } $info = []; foreach ($allProps as $prop) { if ($prop['col_name'] === $attribute->getColName()) { $info = $prop; } } $toggle = $this->buildCommand($attribute, $info); $container = $event->getContainer(); $view = $this->createBackendViewDefinition($container); $commands = $view->getModelCommands(); if (!$commands->hasCommandNamed($toggle->getName())) { if ($commands->hasCommandNamed('show')) { $info = $commands->getCommandNamed('show'); } else { $info = null; } $commands->addCommand($toggle, $info); } } }
php
{ "resource": "" }
q8437
BuildMetaModelOperationsListener.wantToAdd
train
private function wantToAdd($attribute, array $properties): bool { return ($attribute instanceof Checkbox) && (($attribute->get('check_publish') === '1') || ($attribute->get('check_listview') === '1')) && (\in_array($attribute->getColName(), $properties, true)); }
php
{ "resource": "" }
q8438
Select.buildBoostedFields
train
public function buildBoostedFields($fields) { // Assume strings are pre-formatted. if (is_string($fields)) { return $fields; } $processed = array(); foreach ($fields as $fieldName => $boost) { if (!is_array($boost)) { $processed[] = $fieldName . '^' . $boost; } else { $field = $fieldName . '~' . $boost[0]; if (isset($boost[1])) { $field .= '^' . $boost[1]; } $processed[] = $field; } } return join(',', $processed); }
php
{ "resource": "" }
q8439
AbstractPixelate.setBlockSize
train
public function setBlockSize($size) { if ($size <= 1) { throw new \InvalidArgumentException("Pixel Size Must Be Greater Than One"); } $this->size = (int) abs($size); return $this; }
php
{ "resource": "" }
q8440
Migrator.initialize
train
public function initialize() { if ($this->versionStorage->hasVersioningNode()) { throw new MigratorException('This repository has already been initialized. Will not re-initialize.'); } foreach (array_keys($this->versionCollection->getAllVersions()) as $timestamp) { $this->versionStorage->add($timestamp); } $this->session->save(); }
php
{ "resource": "" }
q8441
Migrator.resolveTo
train
private function resolveTo($to, $from) { if (is_string($to)) { $to = strtolower($to); } if ($to === 'down') { $to = $this->versionCollection->getPreviousVersion($from); } if ($to === 'up') { $to = $this->versionCollection->getNextVersion($from); } if ($to === 'bottom') { $to = 0; } if ($to === 'top' || null === $to) { $to = $this->versionCollection->getLatestVersion(); } if (0 !== $to && false === strtotime($to)) { throw new MigratorException(sprintf( 'Unknown migration action "%s". Known actions: "%s"', $to, implode('", "', $this->actions) )); } if (0 !== $to && !$this->versionCollection->has($to)) { throw new MigratorException(sprintf( 'Unknown version "%s"', $to )); } return $to; }
php
{ "resource": "" }
q8442
Directory.add
train
public function add($name, Closure $callback = null) { try { $path = $this->finder->find($name); if (isset($this->assets[$path])) { $asset = $this->assets[$path]; } else { $asset = $this->factory->get('asset')->make($path); $asset->isRemote() and $asset->raw(); } is_callable($callback) and call_user_func($callback, $asset); return $this->assets[$path] = $asset; } catch (AssetNotFoundException $e) { $this->getLogger()->error(sprintf('Asset "%s" could not be found in "%s"', $name, $this->path)); return $this->factory->get('asset')->make(null); } }
php
{ "resource": "" }
q8443
Directory.javascript
train
public function javascript($name, Closure $callback = null) { return $this->add($name, function($asset) use ($callback) { $asset->setGroup('javascripts'); is_callable($callback) and call_user_func($callback, $asset); }); }
php
{ "resource": "" }
q8444
Directory.directory
train
public function directory($path, Closure $callback = null) { try { $path = $this->finder->setWorkingDirectory($path); $this->directories[$path] = new Directory($this->factory, $this->finder, $path); // Once we've set the working directory we'll fire the callback so that any added assets // are relative to the working directory. After the callback we can revert the working // directory. is_callable($callback) and call_user_func($callback, $this->directories[$path]); $this->finder->resetWorkingDirectory(); return $this->directories[$path]; } catch (DirectoryNotFoundException $e) { $this->getLogger()->error(sprintf('Directory "%s" could not be found in "%s"', $path, $this->path)); return new Directory($this->factory, $this->finder, null); } }
php
{ "resource": "" }
q8445
Directory.requireDirectory
train
public function requireDirectory($path = null) { if ( ! is_null($path)) { return $this->directory($path)->requireDirectory(); } if ($iterator = $this->iterateDirectory($this->path)) { return $this->processRequire($iterator); } return $this; }
php
{ "resource": "" }
q8446
Directory.requireTree
train
public function requireTree($path = null) { if ( ! is_null($path)) { return $this->directory($path)->requireTree(); } if ($iterator = $this->recursivelyIterateDirectory($this->path)) { return $this->processRequire($iterator); } return $this; }
php
{ "resource": "" }
q8447
Directory.processRequire
train
protected function processRequire(Iterator $iterator) { // sort iterator by name $iterator = new SortingIterator($iterator, 'strnatcasecmp'); // Spin through each of the files within the iterator and if their a valid asset they // are added to the array of assets for this directory. foreach ($iterator as $file) { if ( ! $file->isFile()) continue; $this->add($file->getPathname()); } return $this; }
php
{ "resource": "" }
q8448
Directory.except
train
public function except($assets) { $assets = array_flatten(func_get_args()); // Store the directory instance on a variable that we can inject into the scope of // the closure below. This allows us to call the path conversion method. $directory = $this; $this->assets = $this->assets->filter(function($asset) use ($assets, $directory) { $path = $directory->getPathRelativeToDirectory($asset->getRelativePath()); return ! in_array($path, $assets); }); return $this; }
php
{ "resource": "" }
q8449
Directory.getPathRelativeToDirectory
train
public function getPathRelativeToDirectory($path) { // Get the last segment of the directory as asset paths will be relative to this // path. We can then replace this segment with nothing in the assets path. $directoryLastSegment = substr($this->path, strrpos($this->path, '/') + 1); return trim(preg_replace('/^'.$directoryLastSegment.'/', '', $path), '/'); }
php
{ "resource": "" }
q8450
Directory.rawOnEnvironment
train
public function rawOnEnvironment($environment) { $this->assets->each(function($asset) use ($environment) { $asset->rawOnEnvironment($environment); }); return $this; }
php
{ "resource": "" }
q8451
Directory.getAssets
train
public function getAssets() { $assets = $this->assets; // Spin through each directory and recursively merge the current directories assets // on to the directories assets. This maintains the order of adding in the array // structure. $this->directories->each(function($directory) use (&$assets) { $assets = $directory->getAssets()->merge($assets); }); // Spin through each of the filters and apply them to each of the assets. Every filter // is applied and then later during the build will be removed if it does not apply // to a given asset. $this->filters->each(function($filter) use (&$assets) { $assets->each(function($asset) use ($filter) { $asset->apply($filter); }); }); return $assets; }
php
{ "resource": "" }
q8452
LinearGradient.setType
train
public function setType($type) { if (!in_array($type, self::$supported)) { throw new \InvalidArgumentException(sprintf( 'Invalid LinearGradient Gradient Type ""', (string) $type )); } $this->type = $type; }
php
{ "resource": "" }
q8453
MelisPageTreeTable.getFullDatasPage
train
public function getFullDatasPage($id, $type = '') { $select = $this->tableGateway->getSql()->select(); $select->columns(array('*')); $select->join('melis_cms_page_lang', 'melis_cms_page_lang.plang_page_id = melis_cms_page_tree.tree_page_id', array('plang_lang_id')); $select->join('melis_cms_lang', 'melis_cms_lang.lang_cms_id = melis_cms_page_lang.plang_lang_id', array('*'), $select::JOIN_LEFT); $select->join('melis_cms_page_style', 'melis_cms_page_tree.tree_page_id = melis_cms_page_style.pstyle_page_id', array(), $select::JOIN_LEFT); $select->join('melis_cms_style', ' melis_cms_style.style_id = melis_cms_page_style.pstyle_style_id', array('*'), $select::JOIN_LEFT); if ($type == 'published' || $type == '') $select->join('melis_cms_page_published', 'melis_cms_page_published.page_id = melis_cms_page_tree.tree_page_id', array('*'), $select::JOIN_LEFT); if ($type == 'saved') $select->join('melis_cms_page_saved', 'melis_cms_page_saved.page_id = melis_cms_page_tree.tree_page_id', array('*'), $select::JOIN_LEFT); if ($type == '') { $columns = $this->aliasColumnsFromTableDefinition('MelisEngine\MelisPageColumns', 's_'); $select->join('melis_cms_page_saved', 'melis_cms_page_saved.page_id = melis_cms_page_tree.tree_page_id', $columns, $select::JOIN_LEFT); } $select->join('melis_cms_page_seo', 'melis_cms_page_seo.pseo_id = melis_cms_page_tree.tree_page_id', array('*'), $select::JOIN_LEFT); $select->where('tree_page_id = ' . $id); $resultSet = $this->tableGateway->selectWith($select); return $resultSet; }
php
{ "resource": "" }
q8454
MelisPageTreeTable.getPageChildrenByidPage
train
public function getPageChildrenByidPage($id, $publishedOnly = 0) { $select = $this->tableGateway->getSql()->select(); $select->columns(array('*')); $select->join('melis_cms_page_lang', 'melis_cms_page_lang.plang_page_id = melis_cms_page_tree.tree_page_id', array('plang_lang_id')); $select->join('melis_cms_lang', 'melis_cms_lang.lang_cms_id = melis_cms_page_lang.plang_lang_id', array('*'), $select::JOIN_LEFT); $select->join('melis_cms_page_published', 'melis_cms_page_published.page_id = melis_cms_page_tree.tree_page_id', array('*'), $select::JOIN_LEFT); $select->join('melis_cms_page_style', 'melis_cms_page_tree.tree_page_id = melis_cms_page_style.pstyle_page_id', array(), $select::JOIN_LEFT); $select->join('melis_cms_style', ' melis_cms_style.style_id = melis_cms_page_style.pstyle_style_id', array('*'), $select::JOIN_LEFT); if ($publishedOnly == 1) $select->where('melis_cms_page_published.page_status=1'); if ($publishedOnly == 0) { $columns = $this->aliasColumnsFromTableDefinition('MelisEngine\MelisPageColumns', 's_'); $select->join('melis_cms_page_saved', 'melis_cms_page_saved.page_id = melis_cms_page_tree.tree_page_id', $columns, $select::JOIN_LEFT); } $select->join('melis_cms_page_seo', 'melis_cms_page_seo.pseo_id = melis_cms_page_tree.tree_page_id', array('*'), $select::JOIN_LEFT); $select->join('melis_cms_page_default_urls', 'melis_cms_page_default_urls.purl_page_id = melis_cms_page_tree.tree_page_id', array('*'), $select::JOIN_LEFT); $select->where('tree_father_page_id = ' . $id); $select->order('tree_page_order ASC'); $resultSet = $this->tableGateway->selectWith($select); return $resultSet; }
php
{ "resource": "" }
q8455
MelisPageTreeTable.getPagesBySearchValue
train
public function getPagesBySearchValue($value, $type = '') { $select = $this->tableGateway->getSql()->select(); $select->columns(array('tree_page_id')); if ($type == 'published' || $type == ''){ $select->join('melis_cms_page_published', 'melis_cms_page_published.page_id = melis_cms_page_tree.tree_page_id', array(), $select::JOIN_LEFT); } if ($type == 'saved'){ $select->join('melis_cms_page_saved', 'melis_cms_page_saved.page_id = melis_cms_page_tree.tree_page_id', array(), $select::JOIN_LEFT); } $select->join('melis_cms_page_style', 'melis_cms_page_tree.tree_page_id = melis_cms_page_style.pstyle_page_id', array(), $select::JOIN_LEFT); $select->join('melis_cms_style', ' melis_cms_style.style_id = melis_cms_page_style.pstyle_style_id', array('*'), $select::JOIN_LEFT); $search = '%'.$value.'%'; $select->where->NEST->like('page_name', $search) ->or->like('melis_cms_page_tree.tree_page_id', $search); $resultSet = $this->tableGateway->selectWith($select); return $resultSet; }
php
{ "resource": "" }
q8456
MelisTemplateTable.getSortedTemplates
train
public function getSortedTemplates() { $select = new Select('melis_cms_template'); $select->order('tpl_zf2_website_folder ASC'); $select->order('tpl_name ASC'); $resultSet = $this->tableGateway->selectWith($select); return $resultSet; }
php
{ "resource": "" }
q8457
AbstractPreset.getOverlayCanvas
train
public function getOverlayCanvas($file) { $canvas = new Canvas(); $canvas->fromFile(Util::getResourcePath('Preset/'.$file)); return $canvas; }
php
{ "resource": "" }
q8458
Headers.&
train
public function & SetDisabledHeaders ($disabledHeaders) { /** @var $this \MvcCore\Response */ $this->disabledHeaders = []; $args = func_get_args(); if (count($args) === 1 && is_array($args[0])) $args = $args[0]; foreach ($args as $arg) $this->disabledHeaders[$arg] = TRUE; return $this; }
php
{ "resource": "" }
q8459
TranslationManagerServiceProvider.registerCommands
train
private function registerCommands() { if ($this->app->runningInConsole()) { $this->commands([ \Brotzka\TranslationManager\Module\Console\Commands\TranslationToDatabase::class, \Brotzka\TranslationManager\Module\Console\Commands\TranslationToFile::class ]); } }
php
{ "resource": "" }
q8460
IniDump.Dump
train
public function Dump () { $environment = static::GetEnvironment(TRUE); list($sections, $envSpecifics) = $this->dumpSectionsInfo(); $levelKey = ''; $basicData = []; $sectionsData = []; foreach ($this->data as $key => & $value) { if (is_object($value) || is_array($value)) { if ($sectionsData) $sectionsData[] = ''; $sectionType = isset($sections[$key]) ? $sections[$key] : 0; $environmentSpecificSection = $sectionType === 3; if ($sectionType) { unset($sections[$key]); $sectionsData[] = ($environmentSpecificSection ? '[' . $environment . ' > ' . $key . ']' : '[' . $key . ']'); $levelKey = ''; } else { $levelKey = (string) $key; } $this->dumpRecursive($levelKey, $value, $sectionsData); if ($environmentSpecificSection && isset($envSpecifics[$key])) { foreach ($envSpecifics[$key] as $envName => $sectionLines) { if ($envName === $environment) continue; $sectionsData[] = ''; foreach ($sectionLines as $sectionLine) $sectionsData[] = $sectionLine; } } } else { $basicData[] = $key . ' = ' . $this->dumpScalarValue($value); } } $result = ''; if ($basicData) $result = implode(PHP_EOL, $basicData); if ($sectionsData) $result .= PHP_EOL . PHP_EOL . implode(PHP_EOL, $sectionsData); return $result; }
php
{ "resource": "" }
q8461
IniDump.dumpScalarValue
train
protected function dumpScalarValue ($value) { if (is_numeric($value)) { return (string) $value; } else if (is_bool($value)) { return $value ? 'true' : 'false'; } else if ($value === NULL) { return 'null'; } else { static $specialChars = [ '=', '/', '.', '#', '&', '!', '?', '-', '@', "'", '"', '*', '^', '[', ']', '(', ')', '{', '}', '<', '>', '\n', '\r', ]; $valueStr = (string) $value; $specialCharCaught = FALSE; foreach ($specialChars as $specialChar) { if (mb_strpos($valueStr, $specialChar)) { $specialCharCaught = TRUE; break; } } if ($specialCharCaught) { return '"' . addcslashes($valueStr, '"') . '"'; } else { return $valueStr; } } }
php
{ "resource": "" }
q8462
LeafProperty.initDefaultProperties
train
public function initDefaultProperties() { if (isset($this->schema) && $this->setPropertyDefaultValue($this->schema)) { $this->property_value = $this->schema->default; } }
php
{ "resource": "" }
q8463
BuildCommand.gatherCollections
train
protected function gatherCollections() { if ( ! is_null($collection = $this->input->getArgument('collection'))) { if ( ! $this->environment->has($collection)) { $this->comment('['.$collection.'] Collection not found.'); return array(); } $this->comment('Gathering assets for collection...'); $collections = array($collection => $this->environment->collection($collection)); } else { $this->comment('Gathering all collections to build...'); $collections = $this->environment->all(); } $this->line(''); return $collections; }
php
{ "resource": "" }
q8464
AssetFactory.make
train
public function make($path) { $absolutePath = $this->buildAbsolutePath($path); $relativePath = $this->buildRelativePath($absolutePath); $asset = new Asset($this->files, $this->factory, $this->appEnvironment, $absolutePath, $relativePath); return $asset->setOrder($this->nextAssetOrder()); }
php
{ "resource": "" }
q8465
AssetFactory.buildRelativePath
train
public function buildRelativePath($path) { if (is_null($path)) return $path; $relativePath = str_replace(array(realpath($this->publicPath), '\\'), array('', '/'), $path); // If the asset is not a remote asset then we'll trim the relative path even further to remove // any unnecessary leading or trailing slashes. This will leave us with a nice relative path. if ( ! starts_with($path, '//') and ! (bool) filter_var($path, FILTER_VALIDATE_URL)) { $relativePath = trim($relativePath, '/'); // If the given path is the same as the built relative path then the asset appears to be // outside of the public directory. If this is the case then we'll use an MD5 hash of // the assets path as the relative path to the asset. if (trim(str_replace('\\', '/', $path), '/') == trim($relativePath, '/')) { $path = pathinfo($path); $relativePath = md5($path['dirname']).'/'.$path['basename']; } } return $relativePath; }
php
{ "resource": "" }
q8466
ReadWrite.&
train
public static function & GetConfig ($appRootRelativePath) { if (!isset(self::$configsCache[$appRootRelativePath])) { $app = self::$app ?: self::$app = & \MvcCore\Application::GetInstance(); $systemConfigClass = $app->GetConfigClass(); $system = $systemConfigClass::GetSystemConfigPath() === '/' . ltrim($appRootRelativePath, '/'); self::$configsCache[$appRootRelativePath] = & self::getConfigInstance( $appRootRelativePath, $system ); } return self::$configsCache[$appRootRelativePath]; }
php
{ "resource": "" }
q8467
ReadWrite.&
train
protected static function & getConfigInstance ($appRootRelativePath, $systemConfig = FALSE) { $app = self::$app ?: self::$app = & \MvcCore\Application::GetInstance(); $appRoot = self::$appRoot ?: self::$appRoot = $app->GetRequest()->GetAppRoot(); $fullPath = $appRoot . '/' . str_replace( '%appPath%', $app->GetAppDir(), ltrim($appRootRelativePath, '/') ); if (!file_exists($fullPath)) { $result = FALSE; } else { $systemConfigClass = $app->GetConfigClass(); $result = $systemConfigClass::CreateInstance(); if (!$result->Read($fullPath, $systemConfig)) $result = FALSE; } return $result; }
php
{ "resource": "" }
q8468
SolrClient.normalizeParams
train
public function normalizeParams(RequestHandler $handler, $params) { if (is_string($params)) { $params = array('q' => $params); } elseif (!is_array($params)) { $params = (array) $params; } return array_merge($handler->getDefaultParams(), $params); }
php
{ "resource": "" }
q8469
OopChecking.CheckClassInterface
train
public static function CheckClassInterface ($testClassName, $interfaceName, $checkStaticMethods = FALSE, $throwException = TRUE) { $result = FALSE; $errorMsg = ''; // check given test class for all implemented instance methods by given interface $interfaceName = trim($interfaceName, '\\'); $testClassType = new \ReflectionClass($testClassName); if (in_array($interfaceName, $testClassType->getInterfaceNames(), TRUE)) { $result = TRUE; } else { $errorMsg = "Class `$testClassName` doesn't implement interface `$interfaceName`."; } if ($result && $checkStaticMethods) { // check given test class for all implemented static methods by given interface $allStaticsImplemented = TRUE; $interfaceMethods = static::checkClassInterfaceGetPublicStaticMethods($interfaceName); foreach ($interfaceMethods as $methodName) { if (!$testClassType->hasMethod($methodName)) { $allStaticsImplemented = FALSE; $errorMsg = "Class `$testClassName` doesn't implement static method `$methodName` from interface `$interfaceName`."; break; } $testClassStaticMethod = $testClassType->getMethod($methodName); if (!$testClassStaticMethod->isStatic()) { $allStaticsImplemented = FALSE; $errorMsg = "Class `$testClassName` doesn't implement static method `$methodName` from interface `$interfaceName`, method is not static."; break; } // arguments compatibility in presented static method are automatically checked by PHP } if (!$allStaticsImplemented) $result = FALSE; } // return result or thrown an exception if ($result) return TRUE; if (!$throwException) return FALSE; $selfClass = version_compare(PHP_VERSION, '5.5', '>') ? self::class : __CLASS__; throw new \InvalidArgumentException("[".$selfClass."] " . $errorMsg); }
php
{ "resource": "" }
q8470
OopChecking.CheckClassTrait
train
public static function CheckClassTrait ($testClassName, $traitName, $checkParentClasses = FALSE, $throwException = TRUE) { $result = FALSE; $errorMsg = ''; // check given test class for all implemented instance methods by given interface $testClassType = new \ReflectionClass($testClassName); if (in_array($traitName, $testClassType->getTraitNames(), TRUE)) { $result = TRUE; } else if ($checkParentClasses) { $currentClassType = $testClassType; while (TRUE) { $parentClass = $currentClassType->getParentClass(); if ($parentClass === FALSE) break; $parentClassType = new \ReflectionClass($parentClass->getName()); if (in_array($traitName, $parentClassType->getTraitNames(), TRUE)) { $result = TRUE; break; } else { $currentClassType = $parentClassType; } } } if (!$result) $errorMsg = "Class `$testClassName` doesn't implement trait `$traitName`."; // return result or thrown an exception if ($result) return TRUE; if (!$throwException) return FALSE; $selfClass = version_compare(PHP_VERSION, '5.5', '>') ? self::class : __CLASS__; throw new \InvalidArgumentException("[".$selfClass."] " . $errorMsg); }
php
{ "resource": "" }
q8471
OopChecking.&
train
protected static function & checkClassInterfaceGetPublicStaticMethods ($interfaceName) { if (!isset(static::$interfacesStaticMethodsCache[$interfaceName])) { $methods = []; $interfaceType = new \ReflectionClass($interfaceName); $publicOrStaticMethods = $interfaceType->getMethods(\ReflectionMethod::IS_PUBLIC | \ReflectionMethod::IS_STATIC); /** @var $publicOrStaticMethod \ReflectionMethod */ foreach ($publicOrStaticMethods as $publicOrStaticMethod) { // filter methods for public and also static method only if ($publicOrStaticMethod->isStatic() && $publicOrStaticMethod->isPublic()) { $methods[] = $publicOrStaticMethod->getName(); } } static::$interfacesStaticMethodsCache[$interfaceName] = $methods; } return static::$interfacesStaticMethodsCache[$interfaceName]; }
php
{ "resource": "" }
q8472
HtmlAttributes.generateHtmlString
train
protected function generateHtmlString(...$attributesList): HtmlString { $attributesArray = $this->buildAttributesArray(...$attributesList); $html = $this->buildHtmlString($attributesArray); return new HtmlString($html); }
php
{ "resource": "" }
q8473
HtmlAttributes.buildHtmlString
train
protected function buildHtmlString(array $attributesArray): string { $html = ''; foreach ($attributesArray as $key => $attribute) { $spacer = strlen($html) ? ' ' : ''; if ($key && is_string($key)) { $html .= $spacer . $key . ($attribute ? '="' . $attribute . '"' : ''); } else { $html .= $spacer . $attribute; } } return $html; }
php
{ "resource": "" }
q8474
StatusCodeContainerTrait.withStatusCode
train
public function withStatusCode(int $code) { if ($this->statusCode == $code) { return $this; } $that = clone($this); $that->statusCode = $code; return $that; }
php
{ "resource": "" }
q8475
Text.setLineSpacing
train
public function setLineSpacing($spacing) { if ($spacing < 0) { throw new \InvalidArgumentException(sprintf( 'Invalid Line Spacing "%s" - Spacing Must Be Greater Than Zero' , (string) $spacing )); } $this->spacing = (float) $spacing; return $this; }
php
{ "resource": "" }
q8476
Text.getBoundingBox
train
public function getBoundingBox($padding = 10) { $bare = imageftbbox( $this->getFontSize() , 0 , $this->getFont() , $this->getString() , array('linespacing' => $this->getLineSpacing()) ); $a = deg2rad($this->getAngle()); $ca = cos($a); $sa = sin($a); $rect = array(); for ($i = 0; $i < 7; $i += 2) { $rect[$i] = round($bare[$i] * $ca + $bare[$i + 1] * $sa); $rect[$i + 1] = round($bare[$i + 1] * $ca - $bare[$i] * $sa); } $minX = min(array($rect[0], $rect[2], $rect[4], $rect[6])); $maxX = max(array($rect[0], $rect[2], $rect[4], $rect[6])); $minY = min(array($rect[1], $rect[3], $rect[5], $rect[7])); $maxY = max(array($rect[1], $rect[3], $rect[5], $rect[7])); $dx = $this->getCoordinate()->getX() - abs($minX) - 1; $dy = $this->getCoordinate()->getY() - abs($minY) - 1 + $this->getFontSize(); $width = $maxX - $minX; $height = $maxY - $minY; $padding = (int) $padding; $dimension = new Dimension( $width + 2 + ($padding * 2) , $height + 2 + ($padding * 2) ); $coordinate = new Coordinate( $dx - $padding , $dy - $padding ); return new Box($dimension, $coordinate); }
php
{ "resource": "" }
q8477
EndpointCompilerPass.createAuthentication
train
protected function createAuthentication(ContainerBuilder $container, $authentication, $type) { if ($authentication['type'] == 'basic' && (!isset($authentication['username']) || !isset($authentication['password']))) { throw new \LogicException('Username and password are mandatory if using the basic authentication'); } if ($authentication['type'] == 'basic') { // Create an authentication service $authenticationDefinition = new Definition( 'Bluetea\Api\Authentication\BasicAuthentication', array('username' => $authentication['username'], 'password' => $authentication['password']) ); } elseif ($authentication['type'] == 'anonymous') { // Create an authentication service $authenticationDefinition = new Definition( 'Bluetea\Api\Authentication\AnonymousAuthentication' ); } else { throw new InvalidConfigurationException('Invalid authentication'); } $container->setDefinition(sprintf('jira_rest_api.%s_authentication', $type), $authenticationDefinition); }
php
{ "resource": "" }
q8478
EndpointCompilerPass.createApiClient
train
protected function createApiClient(ContainerBuilder $container, $apiClient, $baseUrl, $type) { if ($apiClient == 'guzzle') { // Create an API client service $apiClientDefinition = new Definition( 'Bluetea\Api\Client\GuzzleClient', array($baseUrl, new Reference(sprintf('jira_rest_api.%s_authentication', $type))) ); $apiClientDefinition->addMethodCall('setContentType', array('application/json')); $apiClientDefinition->addMethodCall('setAccept', array('application/json')); } else { throw new \LogicException('Invalid api client'); } $container->setDefinition(sprintf('jira_rest_api.%s_api_client', $type), $apiClientDefinition); }
php
{ "resource": "" }
q8479
EndpointCompilerPass.initializeEndpoints
train
protected function initializeEndpoints(ContainerBuilder $container, $availableApi) { // Add the jira api client to the jira endpoints if (isset($availableApi['jira'])) { $taggedEndpoints = $container->findTaggedServiceIds('jira_rest_api.jira_endpoint'); foreach ($taggedEndpoints as $serviceId => $attributes) { $endpoint = $container->getDefinition($serviceId); // Override the arguments to prevent errors $endpoint->setArguments(array(new Reference('jira_rest_api.jira_api_client'))); } } // Add the crowd api client to the jira endpoints if (isset($availableApi['crowd'])) { $taggedEndpoints = $container->findTaggedServiceIds('jira_rest_api.crowd_endpoint'); foreach ($taggedEndpoints as $serviceId => $attributes) { $endpoint = $container->getDefinition($serviceId); // Override the arguments to prevent errors $endpoint->setArguments(array(new Reference('jira_rest_api.crowd_api_client'))); } } }
php
{ "resource": "" }
q8480
LoggingBackend.log
train
protected function log($operation, $id = null, $ttl = null, $hit = null) { $message = strtoupper($operation); if ($id !== null) { $id = implode(', ', (array) $id); if ($ttl !== null) { $message = sprintf('%s(%s, ttl=%s)', $message, $id, $ttl); } else { $message = sprintf('%s(%s)', $message, $id); } } if ($hit !== null) { $message .= ' = ' . ($hit ? 'HIT' : 'MISS'); } $this->logger->addRecord($this->logLevel, $message); }
php
{ "resource": "" }
q8481
PWELogger.debug_print
train
private static function debug_print($file, $level, $format, $data) { array_shift($data); foreach ($data as $k => $v) { if (is_string($v)) { $data[$k] = str_replace("\n", ' ', $v); } elseif ($v instanceof \Exception) { $data[$k] = $v->__toString(); } elseif (!is_numeric($v)) { $data[$k] = str_replace("\n", " ", json_encode($v)); } } $mtime = microtime(true); $time = 1000 * ($mtime - intval($mtime)); $trace = debug_backtrace(); $location = $trace[2]['function']; for ($n = 2; $n < sizeof($trace); $n++) { if (isset($trace[$n]['class'])) { $location = $trace[$n]['class']; break; } } $id = isset($_SERVER['REMOTE_PORT']) ? $_SERVER['REMOTE_PORT'] : getmypid(); $msg = sizeof($data) ? vsprintf($format, $data) : $format; error_log(sprintf("[%s.%03d %s %s %s] %s\n", date('d.m.Y H:m:s'), $time, $id, $level, $location, $msg), 3, $file); }
php
{ "resource": "" }
q8482
DBRecordTrait.getListQuery
train
public static function getListQuery( ?array $condition = [], $key = null, $value = null, $indexBy = true, $orderBy = true, $alias = null ) { if( !$alias && is_subclass_of( get_called_class(), ActiveRecord::class ) ) { $table = Yii::$app->db->schema->getRawTableName( ( get_called_class() )::tableName() ); } else if( $alias ) { $table = $alias; } else { $table = ''; } !$table ?: $table .= '.'; $key = $key ?? static::primaryKey()[0]; $value = $value ?? $key; $query = static::find() ->select( [ $table . $value, $table . $key, ] ) ->andFilterWhere( $condition ?? [] ) ; if( $orderBy === true ) { // $query->orderBy( $table . $value ); } else if( $orderBy !== false ) { // $query->orderBy( $table . $orderBy ); } if( $indexBy === true ) { // $query->indexBy( $key ); } else if( $indexBy !== false ) { // $query->indexBy( $indexBy ); } return $query; }
php
{ "resource": "" }
q8483
DBRecordTrait.getRawAttributes
train
public function getRawAttributes( ?array $only = null, ?array $except = [], ?bool $schemaOnly = false ) { $values = []; if( $only === null ) { $only = $this->attributes( $only, $except, $schemaOnly ); } foreach( $only as $name ) { $values[ $name ] = $this->getAttribute( $name ); } if( $except ) { $values = array_diff_key( $values, array_flip( $except ) ); } /* foreach( $except as $name ) { unset( $values[ $name ] ); } */ return $values; }
php
{ "resource": "" }
q8484
Connection.start
train
public function start($browserName) { if (!$this->customSidProvided) { $this->sid = uniqid(); $this->executeCommand('launchPreconfiguredBrowser', array('browserType' => $browserName)); } }
php
{ "resource": "" }
q8485
Connection.executeCommand
train
public function executeCommand($command, array $parameters = array()) { $content = $this->post( sprintf('http://%s:%d/_s_/dyn/Driver_%s', $this->host, $this->port, $command), array_merge($parameters, array('sahisid' => $this->sid)) )->getContent(); if (false !== strpos($content, 'SAHI_ERROR')) { throw new Exception\ConnectionException('Sahi proxy error. Full response:' . PHP_EOL . $content); } return $content; }
php
{ "resource": "" }
q8486
Connection.executeStep
train
public function executeStep($step, $limit = null) { $this->executeCommand('setStep', array('step' => $step)); $limit = $limit ?: $this->limit; $check = 'false'; while ('true' !== $check) { usleep(100000); if (--$limit <= 0) { throw new Exception\ConnectionException( 'Command execution time limit reached: `' . $step . '`' ); } $check = $this->executeCommand('doneStep'); if (0 === mb_strpos($check, 'error:')) { throw new Exception\ConnectionException($check); } } }
php
{ "resource": "" }
q8487
Connection.evaluateJavascript
train
public function evaluateJavascript($expression, $limit = null) { $key = '___lastValue___' . uniqid(); $this->executeStep( sprintf("_sahi.setServerVarPlain(%s, JSON.stringify(%s))", json_encode($key), $expression), $limit ); $resp = $this->executeCommand('getVariable', array('key' => $key)); return json_decode($resp, true); }
php
{ "resource": "" }
q8488
Connection.post
train
private function post($url, array $query = array()) { return $this->browser->post($url, array(), $this->prepareQueryString($query)); }
php
{ "resource": "" }
q8489
Connection.prepareQueryString
train
private function prepareQueryString(array $query) { $items = array(); foreach ($query as $key => $val) { $items[] = $key . '=' . urlencode($val); } return implode('&', $items); }
php
{ "resource": "" }
q8490
PluginRegistry.getPlugin
train
public function getPlugin($name) { if (!$this->has($name)) { throw new PluginNotFoundException($name, array_keys($this->plugins)); } return $this->plugins[$name]; }
php
{ "resource": "" }
q8491
LuceneIndexManager.getIndex
train
public function getIndex($indexName) { if (array_key_exists($indexName, $this->indices)) { return $this->indices[$indexName]; } return null; }
php
{ "resource": "" }
q8492
MelisFrontNavigation.getChildrenRecursive
train
public function getChildrenRecursive($idPage) { $results = array(); $melisTree = $this->serviceLocator->get('MelisEngineTree'); $publishedOnly = 1; $pages = $melisTree->getPageChildren($idPage,$publishedOnly); if ($pages) { $rpages = $pages->toArray(); foreach ($rpages as $page) { $tmp = $this->formatPageInArray($page); $children = $this->getChildrenRecursive($page['tree_page_id']); if (!empty($children)) $tmp['pages'] = $children; $results[] = $tmp; } } return $results; }
php
{ "resource": "" }
q8493
MelisFrontNavigation.getAllSubpages
train
public function getAllSubpages($pageId) { $results = array(); //Services $melisTree = $this->serviceLocator->get('MelisEngineTree'); $pagePub = $this->getServiceLocator()->get('MelisEngineTablePagePublished'); $pageSave = $this->getServiceLocator()->get('MelisEngineTablePageSaved'); $pageSearchType = null; $pages = $melisTree->getPageChildren($pageId,2); if($pages) { $rpages = $pages->toArray(); foreach ($rpages as $page) { $pageStat = $page['page_status'] ?? null; //if the page is published if($pageStat){ $pageData = $pagePub->getEntryById($page['tree_page_id'])->current(); $pageSearchType = $pageData->page_search_type ?? null; } //if the page is unpublished else{ $pageData = $pageSave->getEntryById($page['tree_page_id'])->current(); //if the unpublishedData is not present in page_saved table if(!$pageData){ //Get the pageData in page_published table $pageData = $pagePub->getEntryById($page['tree_page_id'])->current(); } $pageSearchType = $pageData->page_search_type ?? null; } $tmp = $this->formatPageInArray($page,$pageSearchType); $children = $this->getAllSubpages($page['tree_page_id'] ?? null); if (!empty($children)) $tmp['pages'] = $children; $results[] = $tmp; } } return $results; }
php
{ "resource": "" }
q8494
CropExtension.getCropEndpoint
train
public function getCropEndpoint( $endpoint, $parameters = array(), $absolute = UrlGeneratorInterface::ABSOLUTE_PATH ) { $parameters = array_merge($parameters, array('endpoint' => $endpoint)); return $this->router->generate($this->routeName, $parameters, $absolute); }
php
{ "resource": "" }
q8495
HOTP.setDigits
train
public function setDigits($digits) { $digits = abs(intval($digits)); if ($digits < 1 || $digits > 10) { throw new \InvalidArgumentException('Digits must be a number between 1 and 10 inclusive'); } $this->digits = $digits; return $this; }
php
{ "resource": "" }
q8496
HOTP.setHashFunction
train
public function setHashFunction($hashFunction) { $hashFunction = strtolower($hashFunction); if (!in_array($hashFunction, hash_algos())) { throw new \InvalidArgumentException("$hashFunction is not a supported hash function"); } $this->hashFunction = $hashFunction; return $this; }
php
{ "resource": "" }
q8497
HOTP.setWindow
train
public function setWindow($window) { $window = abs(intval($window)); $this->window = $window; return $this; }
php
{ "resource": "" }
q8498
Document.getFieldType
train
public function getFieldType($fieldName) { if (!array_key_exists($fieldName, $this->_fields)) { throw new \Exception("Field name \"$fieldName\" not found in document."); } return $this->_fields[$fieldName]->getType (); }
php
{ "resource": "" }
q8499
Net_SmartIRC_irccommands.message
train
public function message($type, $destination, $messagearray, $priority = SMARTIRC_MEDIUM ) { if (!is_array($messagearray)) { $messagearray = array($messagearray); } switch ($type) { case SMARTIRC_TYPE_CHANNEL: case SMARTIRC_TYPE_QUERY: foreach ($messagearray as $message) { $this->send('PRIVMSG '.$destination.' :'.$message, $priority); } break; case SMARTIRC_TYPE_ACTION: foreach ($messagearray as $message) { $this->send('PRIVMSG '.$destination.' :'.chr(1).'ACTION ' .$message.chr(1), $priority ); } break; case SMARTIRC_TYPE_NOTICE: foreach ($messagearray as $message) { $this->send('NOTICE '.$destination.' :'.$message, $priority); } break; case SMARTIRC_TYPE_CTCP: // backwards compatibility case SMARTIRC_TYPE_CTCP_REPLY: foreach ($messagearray as $message) { $this->send('NOTICE '.$destination.' :'.chr(1).$message .chr(1), $priority ); } break; case SMARTIRC_TYPE_CTCP_REQUEST: foreach ($messagearray as $message) { $this->send('PRIVMSG '.$destination.' :'.chr(1).$message .chr(1), $priority ); } break; default: return false; } return $this; }
php
{ "resource": "" }