_id stringlengths 2 7 | title stringlengths 3 151 | partition stringclasses 3
values | text stringlengths 33 8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q10300 | Resolver.createRequest | train | protected function createRequest(string $host, int $type): Request
{
$request = new Request();
$request->addQuestion($host, $type);
| php | {
"resource": ""
} |
q10301 | Element.parseAttribute | train | private function parseAttribute(string $html) : string
{
$remainingHtml = ltrim($html);
try {
// Will match the first entire name/value attribute pair.
preg_match(
"/((([a-z0-9\-_]+:)?[a-z0-9\-_]+)(\s*=\s*)?)/i",
$remainingHtml,
$attributeMatches
);
$attributeName = $attributeMatches[2];
| php | {
"resource": ""
} |
q10302 | Retry.run | train | public function run()
{
$count = 0;
$start = microtime(true);
while (true) {
try {
return call_user_func($this->callable);
} catch (\Throwable $e) {
// Check exception
if (!$e instanceof $this->exceptionType) {
throw $e;
}
// Check timeout
if ($this->timeout > -1 && microtime(true) - $start > ($this->timeout / self::SECONDS)) {
throw $e;
}
// Check count
if ($this->count > -1 && ++$count >= $this->count) {
throw $e;
}
// Before pause | php | {
"resource": ""
} |
q10303 | Retry.setHook | train | public function setHook(string $hook, callable $callable): self
{
$availableHooks = [self::BEFORE_PAUSE_HOOK, self::AFTER_PAUSE_HOOK];
if (!in_array($hook, $availableHooks)) {
throw new \InvalidArgumentException('Invalid | php | {
"resource": ""
} |
q10304 | Retry.setExceptionType | train | public function setExceptionType(string $exceptionType): self
{
try {
$ref = new \ReflectionClass($exceptionType);
if (!$ref->implementsInterface(\Throwable::class)) {
throw new \InvalidArgumentException('Exception class must implement Throwable interface');
}
| php | {
"resource": ""
} |
q10305 | CloudService.update | train | public function update($params, $optParams = [])
{
if (!$params instanceof Cloud) {
throw new InvalidParamException(Cloud::class . ' is required!');
}
return $this->sendRequest([], [
'restAction' => 'update',
'restId' => $params->id,
| php | {
"resource": ""
} |
q10306 | CloudService.delete | train | public function delete($params, $optParams = [])
{
if ($params instanceof Cloud) {
$params = $params->id;
}
return $this->sendRequest([], [
'restAction' => 'delete',
'restId' => $params,
| php | {
"resource": ""
} |
q10307 | HtmlTokenizer.parse | train | public function parse(string $html) : TokenCollection
{
self::$allHtml = $html;
$tokens = new TokenCollection();
$remainingHtml = trim($html);
while (mb_strlen($remainingHtml) > 0) {
$token = TokenFactory::buildFromHtml(
$remainingHtml,
null,
$this->throwOnError
);
| php | {
"resource": ""
} |
q10308 | Arr.parse | train | public function parse(AbstractStream $stream)
{
try {
return parent::parse($stream);
} catch (\OutOfBoundsException | php | {
"resource": ""
} |
q10309 | Compiler.generateText | train | protected function generateText($node)
{
$buffer = '';
$value = explode("\n", $node['value']);
$last = count($value) - 1;
foreach ($value as $i => $line) {
$line = str_replace("'", '\\\'', $line);
if ($i === $last) {
| php | {
"resource": ""
} |
q10310 | Compiler.generatePartials | train | protected function generatePartials()
{
$partials = $this->handlebars->getPartials();
foreach ($partials as $name => $partial) {
$partials[$name] = sprintf(
self::BLOCK_OPTIONS_HASH_KEY_VALUE,
$name,
"'" . str_replace("'", '\\\'', $partial) . "'"
);
}
| php | {
"resource": ""
} |
q10311 | Compiler.parseArguments | train | protected function parseArguments($string)
{
//Argument 1 must be a string
Argument::i()->test(1, 'string');
$args = array();
$hash = array();
$regex = array(
'([a-zA-Z0-9]+\="[^"]*")', // cat="meow"
'([a-zA-Z0-9]+\=\'[^\']*\')', // mouse='squeak squeak'
'([a-zA-Z0-9]+\=[a-zA-Z0-9]+)', // dog=false
'("[^"]*")', // "some\'thi ' ng"
'(\'[^\']*\')', // 'some"thi " ng'
'([^\s]+)' // <any group with no spaces>
);
preg_match_all('#'.implode('|', $regex).'#is', $string, $matches);
$stringArgs = $matches[0];
$name = array_shift($stringArgs);
$hashRegex = array(
'([a-zA-Z0-9]+\="[^"]*")', // cat="meow"
'([a-zA-Z0-9]+\=\'[^\']*\')', // mouse='squeak squeak'
'([a-zA-Z0-9]+\=[a-zA-Z0-9]+)', // dog=false
);
foreach ($stringArgs as $arg) {
| php | {
"resource": ""
} |
q10312 | Compiler.parseArgument | train | protected function parseArgument($arg)
{
//if it's a literal string value
if (strpos($arg, '"') === 0
|| strpos($arg, "'") === 0
) {
return "'" . str_replace("'", '\\\'', substr($arg, 1, -1)) . "'";
}
//if it's null
if (strtolower($arg) === 'null'
|| strtolower($arg) === 'true'
|| strtolower($arg) === 'false'
|| is_numeric($arg)
| php | {
"resource": ""
} |
q10313 | LoggerAwareTrait.getLogger | train | protected function getLogger()
{
if (!isset($this->logger)) {
// When no logger is injected, create a new one
// that doesn't | php | {
"resource": ""
} |
q10314 | Ratings.addRating | train | public function addRating($videoId, $rating)
{
$this->validateRating($rating);
$customMetaData = $this->getVideo($videoId)->getCustomMetadata();
$average = $this->getRatingAverage($videoId);
$count = $this->getRatingCount($videoId);
$newCount = $count + 1;
$customMetaData[$this->metadataFieldCount] = $newCount; | php | {
"resource": ""
} |
q10315 | Ratings.getCustomMetaDataField | train | private function getCustomMetaDataField($videoId, $customMetaDataField)
{
$customMetaData = $this->getVideo($videoId)->getCustomMetadata();
| php | {
"resource": ""
} |
q10316 | Ratings.storeCustomMetaData | train | private function storeCustomMetaData($customMetaData, $videoId)
{
// only update custom meta data fields related to rating
$this->client->setCustomMetaData(
$this->vmId,
$videoId,
$this->filterCustomMetaData($customMetaData)
);
| php | {
"resource": ""
} |
q10317 | Ratings.getVideo | train | private function getVideo($videoId)
{
if (!array_key_exists($videoId, $this->videos)) {
$options = new VideoRequestParameters();
$options->setIncludeCustomMetadata(true);
| php | {
"resource": ""
} |
q10318 | Ratings.filterCustomMetaData | train | private function filterCustomMetaData($customMetaData)
{
foreach ($customMetaData as $key => $data) {
if (!in_array($key, [$this->metadataFieldCount, $this->metadataFieldAverage])) {
| php | {
"resource": ""
} |
q10319 | Sequence.push | train | public function push($value, int $repeat = null): self
{
if ($repeat !== null && $repeat <= 0) {
throw new InvalidArgumentException(sprintf(static::MSG_NEGATIVE_ARGUMENT_NOT_ALLOWED, 2, 1));
}
| php | {
"resource": ""
} |
q10320 | Sequence.pushAll | train | public function pushAll(array $values): self
{
foreach ($values | php | {
"resource": ""
} |
q10321 | AccessTokenService.update | train | public function update($params, $optParams = [])
{
if (!$params instanceof AccessToken) {
throw new InvalidParamException(AccessToken::class . ' is required!');
}
$class = get_class($params);
| php | {
"resource": ""
} |
q10322 | AccessTokenService.view | train | public function view($params, $optParams = [])
{
if (!$params instanceof AccessToken) {
throw new InvalidParamException(AccessToken::class . ' is required!');
}
$class = get_class($params);
return $this->sendRequest([], [
'restAction' => 'view',
| php | {
"resource": ""
} |
q10323 | AnnotationParser.extractContent | train | private function extractContent($docComment, $annotationClass)
{
$isRecording = false;
$content = '';
// remove doc comment stars at line start
$docComment = preg_replace('/^[ \t]*(\*\/? ?|\/\*\*)/m', '', $docComment);
$search = '(' .
preg_quote($annotationClass, '/')
. '|'
. substr($annotationClass, strrpos($annotationClass, '\\') + 1)
. ')';
$lines = preg_split('/\n|\r\n/', $docComment);
foreach ($lines as $line) {
if ($isRecording === false && preg_match('/^@' . $search . '(\s|\(|$)/', $line)) {
| php | {
"resource": ""
} |
q10324 | StringSupport.parametrize | train | public static function parametrize($str, $params)
{
$keys = array_keys($params);
$vals = array_values($params);
array_walk($keys, function(&$key) {
| php | {
"resource": ""
} |
q10325 | StringSupport.findOne | train | public static function findOne($pattern, $entries)
{
$found = [];
foreach ($entries as $entry)
{
if (static::match($pattern, $entry))
| php | {
"resource": ""
} |
q10326 | DumpAction.run | train | public function run($type = 'default')
{
$this->stdout("dump {$type}:\n", Console::FG_GREEN);
switch ($type) {
case 'default':
foreach ($this->ipv4->getQueries() as $name => $query) {
$this->dumpDefault($query, $name);
}
break;
case 'division':
foreach ($this->ipv4->getQueries() as $name => $query) {
$this->dumpDivision($query, $name);
}
break;
| php | {
"resource": ""
} |
q10327 | AssetFormHelper.typeField | train | public static function typeField($type = '', $locale = null, $name = 'type'): string
{
$result = '<input type="hidden" value="'.$type.'" name="';
if (! $locale) {
| php | {
"resource": ""
} |
q10328 | MenuHelper.setPageTitle | train | public function setPageTitle(array $config): void
{
foreach ($config as $item) {
if (isset($item['active']) && $item['active']) {
| php | {
"resource": ""
} |
q10329 | MenuHelper._hasAllowedChildren | train | protected function _hasAllowedChildren(array $children): bool
{
foreach ($children as $child) {
if ($this->Auth->urlAllowed($child['url'])) {
| php | {
"resource": ""
} |
q10330 | MenuHelper._isItemActive | train | protected function _isItemActive(array $item): bool
{
if (empty($item['url'])) {
return false;
}
$current = $this->_currentUrl;
if (!empty($item['url']['plugin']) && $item['url']['plugin'] != $current['plugin']) {
return false;
}
if ($item['url']['controller'] == $current['controller'] && $item['url']['action'] == $current['action']) {
$this->_controllerActive = $current['controller'];
$this->_actionActive = | php | {
"resource": ""
} |
q10331 | FeatureTypeAvMeta.setFeatureAv | train | public function setFeatureAv(ChildFeatureAv $v = null)
{
if ($v === null) {
$this->setFeatureAvId(NULL);
} else {
$this->setFeatureAvId($v->getId());
}
$this->aFeatureAv = $v;
// Add binding for other direction of this n:n relationship.
// If | php | {
"resource": ""
} |
q10332 | FeatureTypeAvMeta.getFeatureAv | train | public function getFeatureAv(ConnectionInterface $con = null)
{
if ($this->aFeatureAv === null && ($this->feature_av_id !== null)) {
$this->aFeatureAv = FeatureAvQuery::create()->findPk($this->feature_av_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 | php | {
"resource": ""
} |
q10333 | FeatureTypeAvMeta.setFeatureFeatureType | train | public function setFeatureFeatureType(ChildFeatureFeatureType $v = null)
{
if ($v === null) {
$this->setFeatureFeatureTypeId(NULL);
} else {
$this->setFeatureFeatureTypeId($v->getId());
}
$this->aFeatureFeatureType = $v;
// Add binding for other direction of | php | {
"resource": ""
} |
q10334 | FeatureTypeAvMeta.getFeatureFeatureType | train | public function getFeatureFeatureType(ConnectionInterface $con = null)
{
if ($this->aFeatureFeatureType === null && ($this->feature_feature_type_id !== null)) {
$this->aFeatureFeatureType = ChildFeatureFeatureTypeQuery::create()->findPk($this->feature_feature_type_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
| php | {
"resource": ""
} |
q10335 | HealthBuilder.status | train | public function status($status)
{
if (!($status instanceof Status)) {
$status = new Status($status);
| php | {
"resource": ""
} |
q10336 | HealthBuilder.withDetail | train | public function withDetail($key, $message)
{
assert(!is_null($key), 'Key must not be null');
assert(!is_null($message), 'Message must not be null');
| php | {
"resource": ""
} |
q10337 | DefaultDoctrineUserRepository.createUser | train | protected function createUser(array $credentials)
{
$entity = static::ENTITY_CLASSNAME;
if (count(array_only($credentials, ['email', 'password', 'username'])) < 3)
{
throw new \InvalidArgumentException("Missing arguments.");
}
/** @var User $user */
$user = new $entity(
$credentials['email'],
$credentials['password'],
| php | {
"resource": ""
} |
q10338 | SortableControllerTrait.sort | train | public function sort(): ServiceResponse
{
$this->request->allowMethod('post');
if (!empty($this->sortModelName) && !empty($this->request->getData('foreignKey'))) {
$table = TableRegistry::getTableLocator()->get($this->sortModelName);
$entity = $table->get($this->request->getData('foreignKey'));
| php | {
"resource": ""
} |
q10339 | IndentStyleTrait.setIndentStyle | train | public function setIndentStyle($indentStyle)
{
if (!in_array($indentStyle, [null, Lexer::INDENT_TAB, Lexer::INDENT_SPACE])) {
throw new \InvalidArgumentException(
| php | {
"resource": ""
} |
q10340 | IndentStyleTrait.setIndentWidth | train | public function setIndentWidth($indentWidth)
{
if (!is_null($indentWidth) &&
(!is_int($indentWidth) || $indentWidth < 1)
) {
throw new \InvalidArgumentException(
| php | {
"resource": ""
} |
q10341 | ObjectManager.getHydratorFor | train | public function getHydratorFor($objectClass)
{
if (! isset($this->hydratorInstances[$objectClass])) { | php | {
"resource": ""
} |
q10342 | ObjectManager.createHydratorFor | train | public function createHydratorFor($objectClass)
{
$metadata = $this->getMetadata($objectClass);
$propertyAccessStrategy = $metadata->isPropertyAccessStrategyEnabled();
$hydrator = new Hydrator\Hydrator($this, $propertyAccessStrategy);
if ($this->classResolver) {
$hydrator->setClassResolver($this->classResolver);
}
$fieldsWithHydrationStrategy = $metadata->computeFieldsWithHydrationStrategy();
$mappedFieldNames = $metadata->getMappedFieldNames();
foreach ($mappedFieldNames as $mappedFieldName) {
$strategy = null;
if ($metadata->isMappedFieldWithStrategy($mappedFieldName)) {
$fieldStrategy = $fieldsWithHydrationStrategy[$mappedFieldName];
$strategy = new ClosureHydrationStrategy(
$fieldStrategy[$metadata::INDEX_EXTRACTION_STRATEGY],
$fieldStrategy[$metadata::INDEX_HYDRATION_STRATEGY]
);
}
if ($metadata->isMappedDateField($mappedFieldName)) {
$readDateConverter = $metadata->getReadDateFormatByMappedField($mappedFieldName, null);
$writeDateConverter = $metadata->getWriteDateFormatByMappedField($mappedFieldName, null);
if (! is_null($readDateConverter) && ! is_null($writeDateConverter)) {
| php | {
"resource": ""
} |
q10343 | ObjectManager.getMetadata | train | public function getMetadata($objectClass)
{
if (! $objectClass instanceof ObjectKey) {
$objectClass = new ObjectKey($objectClass);
}
$key = $objectClass->getKey();
return $this->classMetadataFactory->loadMetadata(
$objectClass,
| php | {
"resource": ""
} |
q10344 | DataMapperBuilder.instance | train | public function instance()
{
$settings = $this->getValidatedSettings();
$objectManager = $this->createObjectManager($settings);
$logger = isset($settings['logger']) ? isset($settings['logger']) : null;
| php | {
"resource": ""
} |
q10345 | DataMapperBuilder.getValidatedSettings | train | private function getValidatedSettings()
{
$processor = new Processor();
$settingsValidator = new SettingsValidator();
$validatedSettings = $processor->processConfiguration(
| php | {
"resource": ""
} |
q10346 | DefaultCache.getItemKey | train | private function getItemKey(
string $sectionHandle,
array $requestedFields = null,
string $context = null,
string $id | php | {
"resource": ""
} |
q10347 | DefaultCache.getFieldKey | train | private function getFieldKey(array $requestedFields = null): string
{
if (is_null($requestedFields)) {
return 'no-field-key';
| php | {
"resource": ""
} |
q10348 | DefaultCache.getRelationships | train | private function getRelationships(FullyQualifiedClassName $fullyQualifiedClassName): array
{
$fields = (string)$fullyQualifiedClassName;
if (!is_subclass_of($fields, CommonSectionInterface::class)) {
throw new NotASexyFieldEntityException;
}
/** @var CommonSectionInterface $fields */
$relationships = [];
| php | {
"resource": ""
} |
q10349 | Searchable.getIndices | train | public function getIndices()
{
$indices = $this->indices();
if (empty($indices)) { | php | {
"resource": ""
} |
q10350 | DoctrineReminderRepository.exists | train | public function exists(UserInterface $user, $code = null)
{
| php | {
"resource": ""
} |
q10351 | DoctrineReminderRepository.complete | train | public function complete(UserInterface $user, $code, $password)
{
$reminder = $this->findIncomplete($user, $code);
if ($reminder === null)
{
return false;
}
$credentials = ['password' => $password];
if (! $this->users->validForUpdate($user, $credentials))
{
return false;
}
$entityManager = $this->getEntityManager();
$entityManager->beginTransaction();
try
{
| php | {
"resource": ""
} |
q10352 | AlgoliaFactory.make | train | public function make(AlgoliaConfig $config)
{
return new AlgoliaManager(
new Client(
$config->getApplicationId(),
$config->getApiKey(),
$config->getHostsArray(),
| php | {
"resource": ""
} |
q10353 | Middleware.sendRequestThroughRouter | train | protected function sendRequestThroughRouter(Request $request)
{
return (new Pipeline($this->app))->send($request)->then(function ($request) {
/**
* @var Response $response
*/
$response = $this->router->dispatch($request);
| php | {
"resource": ""
} |
q10354 | AbstractCoreApiClient.generateCacheKey | train | private function generateCacheKey($method, $uri, array $options = [])
{
| php | {
"resource": ""
} |
q10355 | AbstractCoreApiClient.isCacheable | train | private function isCacheable($method, $uri, array $options, $response)
{
/** @var ResponseInterface $statusCode */
$statusCode = $response->getStatusCode();
//cache only 2** responses
if ($statusCode < 200 || $statusCode >= 300) {
return false;
}
//GET is always safe to cache
if ('GET' === $method) {
return true;
}
| php | {
"resource": ""
} |
q10356 | UserRepository.query | train | public function query($q = null)
{
return User::where(function ($query) use ($q) {
$query->where('email', 'like', "%{$q}")
| php | {
"resource": ""
} |
q10357 | Generator.shouldIgnore | train | protected function shouldIgnore(FieldInterface $field): bool
{
$fieldType = $this->container->get(
(string) $field->getFieldType()->getFullyQualifiedClassName()
);
// The field type generator config refers to how the field type itself is defined
// as a service. You can see that in the services.yml
$fieldTypeGeneratorConfig = $fieldType->getFieldTypeGeneratorConfig()->toArray();
if (!key_exists(static::GENERATE_FOR, $fieldTypeGeneratorConfig)) {
| php | {
"resource": ""
} |
q10358 | Generator.getFieldTypeTemplateDirectory | train | protected function getFieldTypeTemplateDirectory(
FieldInterface $field,
string $supportingDirectory
) {
/** @var FieldTypeInterface $fieldType */
$fieldType = $this->container->get((string) $field->getFieldType()->getFullyQualifiedClassName());
$fieldTypeDirectory = explode('/', $fieldType->directory());
foreach ($fieldTypeDirectory as $key => $segment) {
| php | {
"resource": ""
} |
q10359 | Watermark.applyWatermarkImagick | train | private function applyWatermarkImagick(Imagick $image)
{
$pictureWidth = $image->getImageWidth();
$pictureHeight = $image->getImageHeight();
$watermarkPicture = new Picture($this->watermark, NULL, Picture::WORKER_IMAGICK);
$opacity = new Opacity($this->opacity);
$opacity->apply($watermarkPicture);
if($this->size)
{
$resize = new Resize(
$pictureWidth / 100 * $this->size,
$pictureHeight / 100 * $this->size,
Resize::MODE_FIT
);
$resize->apply($watermarkPicture);
}
$watermark = $watermarkPicture->getResource(Picture::WORKER_IMAGICK);
$watermarkWidth = $watermark->getImageWidth();
$watermarkHeight = $watermark->getImageHeight();
switch($this->position)
{
case 'repeat':
for($w = 0; $w < $pictureWidth; $w += $watermarkWidth + $this->space)
{
| php | {
"resource": ""
} |
q10360 | Watermark.applyWatermarkGD | train | protected function applyWatermarkGD($resource, Picture $picture) {
// SOURCE IMAGE DIMENSIONS
$pictureWidth = imagesx($resource);
$pictureHeight = imagesy($resource);
// WATERMARK DIMENSIONS
$watermarkPicture = new Picture($this->watermark, NULL, Picture::WORKER_GD);
$opacity = new Opacity($this->opacity);
$opacity->apply($watermarkPicture);
if($this->size)
{
$resize = new Resize(
$pictureWidth / 100 * $this->size,
$pictureHeight / 100 * $this->size,
Resize::MODE_FIT
);
$resize->apply($watermarkPicture);
}
$watermark = $watermarkPicture->getResource($watermarkPicture::WORKER_GD);
imagealphablending($watermark, TRUE);
$watermarkWidth = imagesx($watermark);
$watermarkHeight = imagesx($watermark);
// CALCULATE WATERMARK POSITION
switch($this->position)
{
case 'repeat':
for($w = 0; $w < $pictureWidth; $w += $watermarkWidth + $this->space)
{
for($h = 0; $h < $pictureHeight; $h += $watermarkHeight + $this->space)
{
imagecopy($resource, $watermark, $w, $h, 0, 0, $watermarkWidth, $watermarkHeight);
}
}
return $resource;
case 'center':
$positionX = ($pictureWidth - $watermarkWidth) / 2 - $this->offsetX;
$positionY = ($pictureHeight - $watermarkHeight) / 2 - $this->offsetY;
break;
case 'topRight':
| php | {
"resource": ""
} |
q10361 | Application.run | train | public function run(Request $request = null)
{
\ini_set('display_errors', $this->config['debug'] ? 1 : 0);
\ini_set('display_startup_errors', $this->config['debug'] ? 1 : 0);
\date_default_timezone_set($this->config['timezone']);
// map all routes
foreach ($this->routes as $r => &$x) {
if (isset($x['controller'])) {
$this->router->map($x['method'], $r, $x['action'], $x['controller']);
} else foreach ($x as &$xx) {
$this->router->map($xx['method'], $r, $xx['action'], $xx['controller']);
}
}
// dispatch
try {
try {
$this->router->dispatch(
$request === null ? Request::createFromGlobals() : $request,
new class(
(new MultiControllerFactory(...$this->controller_factories))->close(),
$this->endobox,
$this->logger,
$this->config['app-namespace']) extends ControllerFactoryDecorator {
private $endobox;
private $logger;
private $namespace;
public function __construct(
ControllerFactory $factory,
BoxFactory $endobox,
Logger $logger,
string $namespace) {
| php | {
"resource": ""
} |
q10362 | Money.make | train | public static function make(string $country = null)
{
if (empty($country)) {
$country = config('default');
| php | {
"resource": ""
} |
q10363 | Money.setCurrency | train | public function setCurrency($country = null)
{
if (is_null($country)) {
$country = config('currency.default');
}
$config = config('currency.' . $country);
if (empty($config)) {
| php | {
"resource": ""
} |
q10364 | Money.getCurrency | train | public function getCurrency()
{
if (! empty($this->currency)) {
return $this->currency;
}
| php | {
"resource": ""
} |
q10365 | Money.toCommon | train | public function toCommon(int $amount, bool $format = true): string
{
$money = $this->castMoney($amount, $this->getCurrencySwiftCode());
$moneyFormatter = new DecimalMoneyFormatter(new ISOCurrencies());
| php | {
"resource": ""
} |
q10366 | Money.toMachine | train | public function toMachine(string $amount, string $swift_code = ''): int
{
$swift_code = empty($swift_code) ? config('currency.default_swift_code') : $swift_code;
return (new DecimalMoneyParser(
new ISOCurrencies()
| php | {
"resource": ""
} |
q10367 | Money.convertFixedRate | train | public function convertFixedRate(array $fixedExchange, int $amount, string $swift_code): MoneyPHP
{
return (new Converter(
new ISOCurrencies(),
| php | {
"resource": ""
} |
q10368 | AbstractReadableStream.handleCancel | train | protected function handleCancel(CancellationException $e): ?string | php | {
"resource": ""
} |
q10369 | XmlException.createUsingErrors | train | public static function createUsingErrors(array $errors)
{
$message = "An error was encountered reading an XML document:\n";
foreach ($errors as $error) {
switch ($error->level) {
case LIBXML_ERR_ERROR:
$message .= '[Error] ';
break;
case LIBXML_ERR_FATAL:
| php | {
"resource": ""
} |
q10370 | SwaggerUIServiceProvider.boot | train | public function boot(Application $app)
{
// Reference to $this, it's used for closure in anonymous function (PHP 5.3.x)
$self = &$this;
$app->get($app['swaggerui.path'], function(Request $request) use ($app) {
return str_replace(
array('{{swaggerui-root}}', '{{swagger-docs}}'),
array($request->getBasePath() . $app['swaggerui.path'], $request->getBasePath() . $app['swaggerui.apiDocPath']),
file_get_contents(__DIR__ . '/../../../../public/index.html')
);
});
$app->get($app['swaggerui.path'] . '/{resource}', function($resource) use ($app) {
$file = __DIR__ . '/../../../../public/' . $resource;
if (is_file($file)) {
return file_get_contents($file);
}
return '';
});
$app->get($app['swaggerui.path'] . '/lib/{resource}', function($resource) use ($app, $self) {
return $self->getFile(
__DIR__ . '/../../../../public/lib/' . $resource,
| php | {
"resource": ""
} |
q10371 | SwaggerUIServiceProvider.getFile | train | public function getFile($path, $contentType) {
if (is_file($path)) {
$response = new Response(file_get_contents($path));
$response->headers->set('Content-Type', $contentType);
| php | {
"resource": ""
} |
q10372 | Option.addMultiItem | train | private function addMultiItem()
{
$args = func_get_args();
$optionKey = array_shift($args);
| php | {
"resource": ""
} |
q10373 | PdfGenerator._getView | train | protected function _getView(): View
{
if (!$this->getConfig('view')) {
$view = new View();
foreach ($this->getConfig('helpers') as $helper) | php | {
"resource": ""
} |
q10374 | PdfGenerator._preparePdf | train | protected function _preparePdf($viewFile, $viewVars): Mpdf
{
$mpdf = new Mpdf($this->_config['mpdfSettings']);
if (is_callable($this->_config['mpdfConfigurationCallback'])) {
$this->_config['mpdfConfigurationCallback']($mpdf);
}
$styles = '';
if ($this->_config['cssFile']) {
$styles = file_get_contents($this->_config['cssFile']);
}
if ($this->_config['cssStyles']) {
$styles .= $this->_config['cssStyles'];
}
if (!empty($styles)) {
$mpdf->WriteHTML($styles, 1);
}
if ($this->_config['pdfSourceFile']) {
$mpdf->SetImportUse();
$pagecount = $mpdf->SetSourceFile($this->_config['pdfSourceFile']);
if ($pagecount > 1) {
for ($i = 0; $i <= $pagecount; ++$i) {
// Import next page from the pdfSourceFile
$pageNumber = $i + 1;
if ($pageNumber <= $pagecount) {
| php | {
"resource": ""
} |
q10375 | PdfGenerator.render | train | public function render($viewFile, array $options = [])
{
$options = Hash::merge([
'target' => self::TARGET_RETURN,
'filename' => 'pdf.pdf',
], $options);
$mpdf = $this->_preparePdf($viewFile, $options['viewVars']);
$options['viewVars']['mpdf'] = $mpdf;
if (!is_array($viewFile)) {
$wholeString = $this->_getView()->element($viewFile, $options['viewVars']);
// use 10% less than pcre.backtrack_limit to account for multibyte characters
$splitLength = ini_get('pcre.backtrack_limit') - (ini_get('pcre.backtrack_limit') / 10);
$splitString = str_split($wholeString, $splitLength);
foreach ($splitString as $string) {
$mpdf->WriteHTML($string);
}
}
switch ($options['target']) {
case self::TARGET_RETURN:
return $mpdf;
break;
case | php | {
"resource": ""
} |
q10376 | LazyPermissionsTrait.hasAccess | train | public function hasAccess($permissions)
{
if ($this->permissions->isEmpty())
{
$this->mergePermissions($this->userPermissions, $this->rolePermissions);
}
if (func_num_args() > 1)
{
$permissions = func_get_args();
| php | {
"resource": ""
} |
q10377 | LazyPermissionsTrait.add | train | protected function add(Permission $permission, $override = true)
{
if ($override || ! $this->permissions->containsKey($permission->getName()))
{
| php | {
"resource": ""
} |
q10378 | LazyPermissionsTrait.allows | train | protected function allows($permissionName)
{
foreach ($this->getMatchingPermissions($permissionName) as $key)
{
/** @var Permission $permission | php | {
"resource": ""
} |
q10379 | Scalar.setSize | train | public function setSize($size)
{
if (is_string($size) && $parsed = $this->parseSizeWord($size)) {
$this->size = $parsed;
| php | {
"resource": ""
} |
q10380 | Scalar.parse | train | public function parse(AbstractStream $stream)
{
$value = $this->format($this->read($stream));
| php | {
"resource": ""
} |
q10381 | Scalar.format | train | private function format($value)
{
if (is_callable($this->formatter)) { | php | {
"resource": ""
} |
q10382 | Scalar.parseSizeWord | train | private function parseSizeWord($word)
{
$sizeWord = strtoupper(preg_replace('/([a-z])([A-Z])/', '$1_$2', $word));
if (array_key_exists($sizeWord, $this->sizes)) {
| php | {
"resource": ""
} |
q10383 | Request.send | train | protected function send($url, array $headers = [], $body = []): ResponseContract
{
$endpoint = $url instanceof EndpointContract | php | {
"resource": ""
} |
q10384 | OrderedHealthAggregator.statusComparator | train | private function statusComparator($s1, $s2)
{
if (array_search($s1->getCode(), $this->statusOrder) === array_search($s2->getCode(), $this->statusOrder)) { | php | {
"resource": ""
} |
q10385 | DefaultDoctrineReminderRepository.create | train | public function create(UserInterface $user)
{
$entity = static::ENTITY_CLASSNAME;
$reminder = new $entity($user);
| php | {
"resource": ""
} |
q10386 | SerializableValueStub.makeSerializable | train | private function makeSerializable($value)
{
if (null === $value) {
return $value;
}
if ($value instanceof Traversable || is_array($value)) {
$value = ArrayUtils::iteratorToArray($value);
foreach ($value as $key => $val) {
$value[$key] = $this->makeSerializable($val);
}
return $value;
| php | {
"resource": ""
} |
q10387 | SerializableValueStub.makeReal | train | private function makeReal($value)
{
if (is_array($value)) {
foreach ($value as $key => $val) {
$value[$key] = $this->makeReal($val);
}
}
| php | {
"resource": ""
} |
q10388 | ViewBuilder.getView | train | public function getView(string $uri, Engine $engine, $type = null): View
{
if (null === $type) {
$view = $this->getViewFinder()->find([$uri], $engine);
| php | {
"resource": ""
} |
q10389 | ViewBuilder.addLocation | train | public function addLocation(Location $location)
{
$this->locations->add($location);
| php | {
"resource": ""
} |
q10390 | ViewBuilder.scanLocations | train | public function scanLocations(array $criteria)
{
$uris = $this->locations->map(function ($location) use ($criteria) {
/** @var Location $location */
return $location->getURI($criteria);
})->filter(function ($uri) {
return false !== $uri;
});
// Fall back for absolute paths on current filesystem.
if ($uris->isEmpty()) {
foreach | php | {
"resource": ""
} |
q10391 | ViewBuilder.getFinder | train | protected function getFinder($key)
{
$finderClass = $this->config->getKey($key, 'ClassName');
| php | {
"resource": ""
} |
q10392 | ViewBuilder.resolveType | train | protected function resolveType($type, string $uri, Engine $engine = null): View
{
$configKey = [static::VIEW_FINDER_KEY, 'Views', $type];
if (is_string($type) && $this->config->hasKey($configKey)) {
$className = $this->config->getKey($configKey);
$type = new $className($uri, $engine, $this);
}
if (is_string($type)) {
$type = new $type($uri, $engine, $this);
}
if (is_callable($type)) {
| php | {
"resource": ""
} |
q10393 | ViewBuilder.getConfig | train | protected function getConfig($config = []): ConfigInterface
{
$defaults = ConfigFactory::create(dirname(__DIR__, 2) . '/config/defaults.php', $config);
$config = $config
| php | {
"resource": ""
} |
q10394 | Asset.attachToModel | train | public function attachToModel(Model $model, $type = '', $locale = null): Model
{
if ($model->assets()->get()->contains($this)) {
throw AssetUploadException::create();
| php | {
"resource": ""
} |
q10395 | Asset.getImageUrl | train | public function getImageUrl($type = ''): string
{
if ($this->getMedia()->isEmpty()) {
return asset('assets/back/img/other.png');
}
$extension = $this->getExtensionType();
if ($extension === 'image') {
return $this->getFileUrl($type);
| php | {
"resource": ""
} |
q10396 | Asset.removeByIds | train | public static function removeByIds($imageIds)
{
if (is_array($imageIds)) {
foreach ($imageIds as $id) {
if (! $id) {
continue;
}
self::remove($id);
}
| php | {
"resource": ""
} |
q10397 | Asset.remove | train | public static function remove($id)
{
$asset = self::find($id)->first();
$media = $asset->media;
foreach ($media as $file) {
if (! is_file(public_path($file->getUrl())) | php | {
"resource": ""
} |
q10398 | Asset.registerMediaConversions | train | public function registerMediaConversions(Media $media = null)
{
$conversions = config('assetlibrary.conversions');
foreach ($conversions as $key => $value) {
$conversionName = $key;
$this->addMediaConversion($conversionName)
->width($value['width'])
->height($value['height'])
->keepOriginalImageFormat()
->optimize();
| php | {
"resource": ""
} |
q10399 | AccessorTrait.checkArguments | train | protected function checkArguments(array $args, $min, $max, $methodName)
{
$argc = count($args);
| php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.