_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 33
8k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q100 | RedirectLoginHelper.validateCsrf | train | protected function validateCsrf()
{
if (empty($this->getInput('state'))
|| ($this->getInput('state') !== $this->store->get('oauth2state'))
) {
| php | {
"resource": ""
} |
q101 | Client.getAccessToken | train | public function getAccessToken($code, $grant = 'authorization_code')
{
$token = $this->container->get(RedirectLoginHelper::class)
| php | {
"resource": ""
} |
q102 | Client.setAccessToken | train | public function setAccessToken(AccessToken $token)
{
$this->container->get('config')
| php | {
"resource": ""
} |
q103 | Profile.getData | train | public function getData($sEmail)
{
$this->sFormat = 'php';
$sProfile = file_get_contents($this->getUrl($sEmail));
$aProfile = unserialize($sProfile);
| php | {
"resource": ""
} |
q104 | Profile.format | train | public function format($sFormat= null)
{
if (null === $sFormat) {
return $this->getFormat();
| php | {
"resource": ""
} |
q105 | Profile.setFormat | train | public function setFormat($sFormat = null)
{
if (null === $sFormat) {
return $this;
}
if (!in_array($sFormat, $this->aValidFormats)) {
$message = sprintf(
'The format "%s" is not a valid one, profile format for Gravatar can be: %s',
| php | {
"resource": ""
} |
q106 | RegisterController.createSignup | train | protected function createSignup(array $data, $userId)
{
return Signup::create([
'user_id' => $userId,
'firstname' => $data['firstname'], | php | {
"resource": ""
} |
q107 | Guzzle.handleErrors | train | private static function handleErrors($response)
{
switch ($response->getStatusCode()) {
case 200:
return json_decode($response->getBody());
break;
case 401:
throw new UnauthorizedException('Unauthorized (Invalid API key or insufficient permissions)');
break;
case 404:
throw new NotFoundException('Object not found within your account scope');
| php | {
"resource": ""
} |
q108 | LatLong.primeCoordinateParsers | train | protected function primeCoordinateParsers() {
$this->latitude->getParser()->setDirection(N::LAT); | php | {
"resource": ""
} |
q109 | DefaultController.servicosDisponiveisUnidade | train | private function servicosDisponiveisUnidade($unidade)
{
$rs = $this
->getDoctrine()
->getManager()
->createQueryBuilder()
->select([
'e',
's',
'sub'
])
->from(ServicoUnidade::class, 'e')
->join('e.servico', 's')
->leftJoin('s.subServicos', 'sub')
->where('s.mestre IS NULL')
->andWhere('e.ativo = TRUE')
->andWhere('e.unidade = :unidade')
| php | {
"resource": ""
} |
q110 | PasswordlessProvider.registerEvents | train | public function registerEvents()
{
// Delete user tokens after login
if (config('passwordless.empty_tokens_after_login') === true) {
Event::listen(
Authenticated::class,
| php | {
"resource": ""
} |
q111 | Worker.processOne | train | public function processOne(ObjectId $id): void
{
$this->catchSignal();
$this->logger->debug('process job ['.$id.'] and exit', [
'category' => get_class($this),
]);
try {
$job = $this->scheduler->getJob($id)->toArray();
$this->queueJob($job);
| php | {
"resource": ""
} |
q112 | Worker.cleanup | train | public function cleanup()
{
$this->saveState();
if (null === $this->current_job) {
$this->logger->debug('received cleanup call on worker ['.$this->id.'], no job is currently processing, exit now', [
'category' => get_class($this),
'pm' => $this->process,
]);
$this->exit();
return null;
}
$this->logger->debug('received cleanup call on worker ['.$this->id.'], reschedule current processing job ['.$this->current_job['_id'].']', [
'category' => get_class($this),
'pm' => $this->process,
]);
$this->updateJob($this->current_job, JobInterface::STATUS_CANCELED);
$this->db->{$this->scheduler->getEventQueue()}->insertOne([
| php | {
"resource": ""
} |
q113 | Worker.saveState | train | protected function saveState(): self
{
foreach ($this->queue as $key => $job) {
$this->db->selectCollection($this->scheduler->getJobQueue())->updateOne(
['_id' => $job['_id'], '$isolated' => true],
| php | {
"resource": ""
} |
q114 | Worker.catchSignal | train | protected function catchSignal(): self
{
pcntl_async_signals(true);
pcntl_signal(SIGTERM, [$this, | php | {
"resource": ""
} |
q115 | Worker.queueJob | train | protected function queueJob(array $job): bool
{
if (!isset($job['status'])) {
return false;
}
if (true === $this->collectJob($job, JobInterface::STATUS_PROCESSING)) {
$this->processJob($job);
} elseif (JobInterface::STATUS_POSTPONED === $job['status']) {
$this->logger->debug('found postponed job ['.$job['_id'].'] to requeue', [
| php | {
"resource": ""
} |
q116 | Worker.processLocalQueue | train | protected function processLocalQueue(): bool
{
$now = time();
foreach ($this->queue as $key => $job) {
$this->db->{$this->scheduler->getJobQueue()}->updateOne(
['_id' => $job['_id'], '$isolated' => true],
['$setOnInsert' => $job],
['upsert' => true]
);
if ($job['options']['at'] <= $now) {
$this->logger->info('postponed job ['.$job['_id'].'] ['.$job['class'].'] can now be executed', [
'category' => get_class($this),
'pm' => | php | {
"resource": ""
} |
q117 | Worker.executeJob | train | protected function executeJob(array $job): bool
{
if (!class_exists($job['class'])) {
throw new InvalidJobException('job class does not exists');
}
if (null === $this->container) {
$instance = new $job['class']();
} else {
$instance = $this->container->get($job['class']);
}
if (!($instance instanceof JobInterface)) {
throw new InvalidJobException('job must implement JobInterface');
}
$instance
->setData($job['data'])
->setId($job['_id'])
| php | {
"resource": ""
} |
q118 | Loader.addToHTML | train | public static function addToHTML()
{
if (!self::isViewingHTMLPage()) {
return;
}
// js
$paths = self::getAssetFilePaths('js');
echo sprintf(
'<script>%s</script>',
self::getCombinedContents($paths)
); | php | {
"resource": ""
} |
q119 | Loader.isViewingHTMLPage | train | public static function isViewingHTMLPage()
{
if (!is_admin()) {
return false;
}
if (!array_key_exists('SCRIPT_NAME', $_SERVER)) {
return false;
}
$whitelisted_script_names = array(
'wp-admin/post-new.php',
'wp-admin/post.php',
| php | {
"resource": ""
} |
q120 | Loader.getAssetFilePaths | train | public static function getAssetFilePaths($type)
{
$path = sprintf('%s/assets/%s/', __DIR__, $type);
$filenames = preg_grep('/^[^\.]/', scandir($path));
if (!Arr::iterable($filenames)) {
return array();
}
| php | {
"resource": ""
} |
q121 | Loader.getCombinedContents | train | public static function getCombinedContents($paths)
{
if (!Arr::iterable($paths)) {
return '';
}
$out = array();
foreach ($paths as $path) {
| php | {
"resource": ""
} |
q122 | Prpcrypt.decode | train | public function decode($decrypted)
{
$pad = ord(substr($decrypted, -1));
if ($pad < | php | {
"resource": ""
} |
q123 | SchedulerValidator.validateOptions | train | public static function validateOptions(array $options): array
{
foreach ($options as $option => $value) {
switch ($option) {
case Scheduler::OPTION_AT:
case Scheduler::OPTION_INTERVAL:
case Scheduler::OPTION_RETRY:
case Scheduler::OPTION_RETRY_INTERVAL:
case Scheduler::OPTION_TIMEOUT:
if (!is_int($value)) {
throw new InvalidArgumentException('option '.$option.' must be an integer');
}
break;
case Scheduler::OPTION_IGNORE_DATA:
case Scheduler::OPTION_FORCE_SPAWN:
if (!is_bool($value)) {
throw new InvalidArgumentException('option '.$option.' must be a boolean');
| php | {
"resource": ""
} |
q124 | Helper.addRedirectUriToServiceConfig | train | protected static function addRedirectUriToServiceConfig(array $config)
{
if (!empty($config['constructor']) && is_array($config['constructor'])) {
$key = key($config['constructor']); // Key may be non-numeric
| php | {
"resource": ""
} |
q125 | Image.getUrl | train | public function getUrl($sEmail = null)
{
if (null !== $sEmail) {
$this->setEmail($sEmail);
}
return static::URL
.'avatar/'
| php | {
"resource": ""
} |
q126 | Image.size | train | public function size($iSize = null)
{
if (null === $iSize) {
return $this->getSize();
| php | {
"resource": ""
} |
q127 | Image.defaultImage | train | public function defaultImage($sDefaultImage = null, $bForce = false)
{
if (null === $sDefaultImage) {
return $this->getDefaultImage();
| php | {
"resource": ""
} |
q128 | Image.forceDefault | train | public function forceDefault($bForceDefault = null)
{
if (null === $bForceDefault) {
return $this->getForceDefault();
| php | {
"resource": ""
} |
q129 | Image.rating | train | public function rating($sRating = null)
{
if (null === $sRating) {
return $this->getMaxRating();
| php | {
"resource": ""
} |
q130 | Image.extension | train | public function extension($sExtension = null)
{
if (null === $sExtension) {
return $this->getExtension();
| php | {
"resource": ""
} |
q131 | Image.setExtension | train | public function setExtension($sExtension = null)
{
if (null === $sExtension) {
return $this;
}
if (!in_array($sExtension, $this->aValidExtensions)) {
$message = sprintf(
'The extension "%s" is not a valid one, extension image for Gravatar can be: %s',
| php | {
"resource": ""
} |
q132 | Image.getParams | train | protected function getParams()
{
$aParams = [];
if (null !== $this->getSize()) {
$aParams['s'] = $this->getSize();
}
if (null !== $this->getDefaultImage()) {
$aParams['d'] = $this->getDefaultImage();
| php | {
"resource": ""
} |
q133 | ResponsiveImageRenderer.render | train | public function render(FileInterface $file, $width, $height, array $options = [], $usedPathsRelativeToCurrentScript = false): string
{
if (!array_key_exists(self::OPTIONS_IMAGE_RELATVE_WIDTH_KEY, $options)
&& isset($GLOBALS['TSFE']->register[self::REGISTER_IMAGE_RELATVE_WIDTH_KEY])
) {
$options[self::OPTIONS_IMAGE_RELATVE_WIDTH_KEY] = (float)$GLOBALS['TSFE']->register[self::REGISTER_IMAGE_RELATVE_WIDTH_KEY];
}
$view = $this->initializeView();
$view->assignMultiple([
| php | {
"resource": ""
} |
q134 | Configuration.getPattern | train | public function getPattern(PackageInterface $package)
{
if (isset($this->packages[$package->getName()])) {
return $this->packages[$package->getName()];
} elseif (isset($this->packages[$package->getPrettyName()])) {
| php | {
"resource": ""
} |
q135 | Configuration.convert | train | protected function convert($extra)
{
if (isset($extra['custom-installer'])) {
foreach ($extra['custom-installer'] as $pattern => $specs) {
foreach ($specs as $spec) {
$match = array();
// Type matching
if (preg_match('/^type:(.*)$/', $spec, $match)) {
$this->types[$match[1]] = $pattern;
| php | {
"resource": ""
} |
q136 | Controller.getReturnUrl | train | protected function getReturnUrl()
{
$backUrl = $this->getRequest()->getSession()->get('oauth2.backurl');
if (!$backUrl || !Director::is_site_url($backUrl)) {
| php | {
"resource": ""
} |
q137 | Controller.authenticate | train | public function authenticate(HTTPRequest $request)
{
$providerName = $request->getVar('provider');
$context = $request->getVar('context');
$scope = $request->getVar('scope');
// Missing or invalid data means we can't proceed
if (!$providerName || !is_array($scope)) {
$this->httpError(404);
return null;
}
/** @var ProviderFactory $providerFactory */
$providerFactory = Injector::inst()->get(ProviderFactory::class);
$provider = $providerFactory->getProvider($providerName); | php | {
"resource": ""
} |
q138 | Controller.callback | train | public function callback(HTTPRequest $request)
{
$session = $request->getSession();
if (!$this->validateState($request)) {
$session->clear('oauth2');
$this->httpError(400, 'Invalid session state.');
return null;
}
$providerName = $session->get('oauth2.provider');
/** @var ProviderFactory $providerFactory */
$providerFactory = Injector::inst()->get(ProviderFactory::class);
$provider = $providerFactory->getProvider($providerName);
$returnUrl = $this->getReturnUrl();
try {
$accessToken = $provider->getAccessToken('authorization_code', [
'code' => $request->getVar('code')
]);
$handlers = $this->getHandlersForContext($session->get('oauth2.context'));
// Run handlers to process the token
$results = [];
foreach ($handlers as $handlerConfig) {
$handler = Injector::inst()->create($handlerConfig['class']);
$results[] = $handler->handleToken($accessToken, $provider);
}
// Handlers may return response objects
foreach ($results as $result) {
if ($result instanceof HTTPResponse) {
$session->clear('oauth2');
// If the response is redirecting to the login page (e.g. on Security::permissionFailure()),
// update the BackURL so it doesn't point to /oauth/callback/
if ($result->isRedirect()) {
$location = $result->getHeader('location');
$relativeLocation = Director::makeRelative($location);
// If the URL begins Security/login and a BackURL parameter is set...
if (
strpos($relativeLocation, Security::config()->uninherited('login_url')) === 0
&& strpos($relativeLocation, 'BackURL') !== -1
| php | {
"resource": ""
} |
q139 | Controller.getHandlersForContext | train | protected function getHandlersForContext($context = null)
{
$handlers = $this->config()->get('token_handlers');
if (empty($handlers)) {
throw new Exception('No token handlers were registered');
}
// If we've been given a context, limit to that context + global handlers.
// Otherwise only allow global handlers (i.e. exclude named ones)
$allowedContexts = ['*'];
if ($context) {
$allowedContexts[] = $context;
}
// Filter handlers by context
$handlers = array_filter($handlers, function ($handler) use ($allowedContexts) {
| php | {
"resource": ""
} |
q140 | Controller.validateState | train | public function validateState(HTTPRequest $request)
{
$state = $request->getVar('state');
$session = $request->getSession();
$data = $session->get('oauth2');
// If we're lacking any required data, or the session state doesn't match
// the one the provider returned, the request is invalid
if (empty($data['state']) || | php | {
"resource": ""
} |
q141 | Challonge.getTournaments | train | public function getTournaments() {
$response = Guzzle::get('tournaments');
$tournaments = [];
foreach ($response as $tourney) {
| php | {
"resource": ""
} |
q142 | Challonge.getParticipants | train | public function getParticipants($tournament)
{
$response = Guzzle::get("tournaments/{$tournament}/participants");
$participants = [];
foreach ($response | php | {
"resource": ""
} |
q143 | Challonge.randomizeParticipants | train | public function randomizeParticipants($tournament)
{
$response = Guzzle::post("tournaments/{$tournament}/participants/randomize");
$participants = [];
foreach ($response as $team) {
$participant = new Participant($team->participant);
| php | {
"resource": ""
} |
q144 | Challonge.getParticipant | train | public function getParticipant($tournament, $participant)
{
$response = Guzzle::get("tournaments/{$tournament}/participants/{$participant}");
| php | {
"resource": ""
} |
q145 | Challonge.getMatches | train | public function getMatches($tournament)
{
$response = Guzzle::get("tournaments/{$tournament}/matches");
$matches = [];
foreach | php | {
"resource": ""
} |
q146 | Challonge.getMatch | train | public function getMatch($tournament, $match)
{
$response = Guzzle::get("tournaments/{$tournament}/matches/{$match}");
| php | {
"resource": ""
} |
q147 | StubLocale.getCurrenciesData | train | public static function getCurrenciesData($locale)
{
if (null === self::$currencies) {
| php | {
"resource": ""
} |
q148 | StubLocale.getDisplayCurrencies | train | public static function getDisplayCurrencies($locale)
{
if (null === self::$currenciesNames) {
| php | {
"resource": ""
} |
q149 | TranslatedFile.updateCMSFields | train | public function updateCMSFields(FieldList $fields)
{
// only apply the update to files (not folders)
if ($this->owner->class != 'Folder') {
// add the tabs from the translatable tab set to the fields
/** @var TabSet $set */
$set = $this->owner->getTranslatableTabSet();
// Remove | php | {
"resource": ""
} |
q150 | TranslatableDataObject.get_extra_config | train | public static function get_extra_config($class, $extension, $args)
{
if (!self::is_translatable_installed()) {
// remain silent during a test
if (SapphireTest::is_running_test()) {
return null;
}
// raise an error otherwise
user_error('Translatable module is not installed but required.', E_USER_WARNING);
return null;
}
if ($args) {
| php | {
"resource": ""
} |
q151 | TranslatableDataObject.updateCMSFields | train | public function updateCMSFields(FieldList $fields)
{
parent::updateCMSFields($fields);
if (!isset(self::$collectorCache[$this->owner->class])) {
return;
}
// remove all localized fields from the list (generated through scaffolding)
foreach (self::$collectorCache[$this->owner->class] as $translatableField => $type) {
$fields->removeByName($translatableField);
}
// check if we're in a translation
if (Translatable::default_locale() != Translatable::get_current_locale()) {
/** @var TranslatableFormFieldTransformation $transformation */
$transformation = TranslatableFormFieldTransformation::create($this->owner);
// iterate through all localized fields
foreach (self::$collectorCache[$this->owner->class] as $translatableField => $type) {
| php | {
"resource": ""
} |
q152 | TranslatableDataObject.getLocalizedFormField | train | public function getLocalizedFormField($fieldName, $locale)
{
$baseName = $this->getBasename($fieldName);
$fieldLabels = $this->owner->fieldLabels();
$localizedFieldName = self::localized_field($fieldName, $locale);
$fieldLabel = isset($fieldLabels[$baseName]) ? $fieldLabels[$baseName] : $baseName;
if (!$this->canTranslate(null, $locale)) {
// if not allowed to translate, return the field as Readonly
return ReadonlyField::create($localizedFieldName, $fieldLabel);
}
$dbFields = array();
Config::inst()->get($this->owner->class, 'db', Config::EXCLUDE_EXTRA_SOURCES, $dbFields);
$type = isset($dbFields[$baseName]) ? $dbFields[$baseName] : '';
$typeClean = (($p = strpos($type, '(')) !== false) ? substr($type, 0, $p) : $type;
switch (strtolower($typeClean)) {
| php | {
"resource": ""
} |
q153 | TranslatableDataObject.getLocalizedRelationField | train | public function getLocalizedRelationField($fieldName, $locale)
{
$baseName = $this->getBasename($fieldName);
$localizedFieldName = self::localized_field($fieldName, $locale);
$field = null;
if ($field = $this->getFieldForRelation($fieldName)) {
| php | {
"resource": ""
} |
q154 | TranslatableDataObject.updateFieldLabels | train | public function updateFieldLabels(&$labels)
{
parent::updateFieldLabels($labels);
$statics = self::$collectorCache[$this->ownerBaseClass];
foreach ($statics as $field => $type) {
| php | {
"resource": ""
} |
q155 | TranslatableDataObject.isLocalizedField | train | public function isLocalizedField($fieldName)
{
$fields = self::get_localized_class_fields($thi | php | {
"resource": ""
} |
q156 | TranslatableDataObject.getLocalizedFieldName | train | public function getLocalizedFieldName($fieldName)
{
if ($this->isLocalizedField($fieldName) || $this->isLocalizedRelation($fieldName)) {
return self::localized_field($fieldName);
| php | {
"resource": ""
} |
q157 | TranslatableDataObject.getLocalizedRelation | train | public function getLocalizedRelation($fieldName, $strict = true)
{
$localizedField = $this->getLocalizedFieldName($fieldName);
if ($strict) {
return $this->owner->getRelation($localizedField);
}
// if not strict, check localized first and fallback to fieldname
| php | {
"resource": ""
} |
q158 | TranslatableDataObject.getLocalizedValue | train | public function getLocalizedValue($fieldName, $strict = true, $parseShortCodes = false)
{
$localizedField = $this->getLocalizedFieldName($fieldName);
// ensure that $strict is a boolean value
$strict = filter_var($strict, FILTER_VALIDATE_BOOLEAN);
/** @var DBField $value */
$value = $this->owner->dbObject($localizedField);
if (!$strict | php | {
"resource": ""
} |
q159 | TranslatableDataObject.onBeforeWrite | train | public function onBeforeWrite()
{
if (!isset(self::$localizedFields[$this->ownerBaseClass])) {
return;
}
$fields = self::$localizedFields[$this->ownerBaseClass];
foreach ($fields as $field => $localized) {
foreach (self::get_target_locales() as $locale) {
$fieldName = self::localized_field($field, $locale);
| php | {
"resource": ""
} |
q160 | TranslatableDataObject.get_localized_class_fields | train | public static function get_localized_class_fields($class)
{
$fieldNames = null;
$ancestry = array_reverse(ClassInfo::ancestry($class));
foreach ($ancestry as $className) {
if (isset(self::$localizedFields[$className])) {
if ($fieldNames === null) {
$fieldNames = array();
}
| php | {
"resource": ""
} |
q161 | TranslatableDataObject.localized_field | train | public static function localized_field($field, $locale = null)
{
if ($locale === null) {
$locale = Translatable::get_current_locale();
}
if | php | {
"resource": ""
} |
q162 | TranslatableDataObject.set_locales | train | public static function set_locales($locales)
{
if (is_array($locales)) {
$list = array();
foreach ($locales as $locale) {
if (i18n::validate_locale($locale)) {
$list[] = $locale;
}
}
$list = array_unique($list);
| php | {
"resource": ""
} |
q163 | TranslatableDataObject.collectDBFields | train | protected static function collectDBFields($class)
{
if (isset(self::$collectorCache[$class])) {
return self::$collectorCache[$class];
}
if (isset(self::$collectorLock[$class]) && self::$collectorLock[$class]) {
return null;
}
self::$collectorLock[$class] = true;
// Get all DB Fields
$fields = array();
Config::inst()->get($class, 'db', Config::EXCLUDE_EXTRA_SOURCES, $fields);
// Get all arguments
$arguments = self::get_arguments($class);
$locales = self::get_target_locales();
// remove the default locale
if (($index = array_search(Translatable::default_locale(), $locales)) !== false) {
array_splice($locales, $index, 1);
}
// fields that should be translated
$fieldsToTranslate = array();
// validate the arguments
if ($arguments) {
foreach ($arguments as $field) {
| php | {
"resource": ""
} |
q164 | TranslatableDataObject.get_target_locales | train | protected static function get_target_locales()
{
// if locales are explicitly set, use these
if (is_array(self::config()->locales)) {
return (array)self::config()->locales;
// otherwise check the allowed locales. If these have been set, use these
} else if (is_array(Translatable::get_allowed_locales())) {
return | php | {
"resource": ""
} |
q165 | TranslatableDataObject.get_arguments | train | protected static function get_arguments($class)
{
if (isset(self::$arguments[$class])) {
return self::$arguments[$class];
} else {
if ($staticFields = Config::inst()->get($class, 'translatable_fields', Config::FIRST_SET)) {
| php | {
"resource": ""
} |
q166 | TranslatableDataObject.setFieldForRelation | train | public function setFieldForRelation($fieldName, FormField $field)
{
if (self::isLocalizedRelation($fieldName)) {
| php | {
"resource": ""
} |
q167 | Locale.getDisplayCountries | train | public static function getDisplayCountries($locale)
{
if (!isset(self::$countries[$locale])) { | php | {
"resource": ""
} |
q168 | Locale.getDisplayLanguages | train | public static function getDisplayLanguages($locale)
{
if (!isset(self::$languages[$locale])) { | php | {
"resource": ""
} |
q169 | Locale.getDisplayLocales | train | public static function getDisplayLocales($locale)
{
if (!isset(self::$locales[$locale])) { | php | {
"resource": ""
} |
q170 | Queue.exitWorkerManager | train | public function exitWorkerManager(int $sig, array $pid): void
{
$this->logger->debug('fork manager ['.$pid['pid'].'] exit with ['.$sig.']', [
'category' => get_class($this),
]);
| php | {
"resource": ""
} |
q171 | Queue.initWorkerManager | train | protected function initWorkerManager()
{
$pid = pcntl_fork();
$this->manager_pid = $pid;
if (-1 === $pid) {
throw new SpawnForkException('failed to spawn fork manager');
}
if (!$pid) {
| php | {
"resource": ""
} |
q172 | Queue.main | train | protected function main(): void
{
$this->logger->info('start job listener', [
'category' => get_class($this),
]);
$cursor_jobs = $this->jobs->getCursor([
'$or' => [
['status' => JobInterface::STATUS_WAITING],
['status' => JobInterface::STATUS_POSTPONED],
],
]);
$cursor_events = $this->events->getCursor([
'timestamp' => ['$gte' => new UTCDateTime()],
'job' => ['$exists' => true],
'status' => ['$gt' => JobInterface::STATUS_POSTPONED],
]);
$this->catchSignal();
while ($this->loop()) {
while ($this->loop()) {
if (null === $cursor_events->current()) {
if ($cursor_events->getInnerIterator()->isDead()) {
$this->logger->error('event queue cursor is dead, is it a capped collection?', [
'category' => get_class($this),
]);
$this->events->create();
$this->main();
break;
}
$this->events->next($cursor_events, function () {
$this->main();
});
}
$event = $cursor_events->current();
$this->events->next($cursor_events, function () {
$this->main();
}); | php | {
"resource": ""
} |
q173 | WPUpdatePhp.does_it_meet_required_php_version | train | public function does_it_meet_required_php_version( $version = PHP_VERSION ) {
if ( $this->version_passes_requirement( $this->minimum_version, | php | {
"resource": ""
} |
q174 | WPUpdatePhp.does_it_meet_recommended_php_version | train | public function does_it_meet_recommended_php_version( $version = PHP_VERSION ) {
if ( $this->version_passes_requirement( $this->recommended_version, | php | {
"resource": ""
} |
q175 | WPUpdatePhp.get_admin_notice | train | public function get_admin_notice( $level = 'minimum' ) {
if ( 'recommended' === $level ) {
if ( ! empty( $this->plugin_name ) ) {
return '<p>' . $this->plugin_name . ' recommends a PHP version higher than ' . $this->recommended_version . '. Read more information about <a href="http://www.wpupdatephp.com/update/">how you can update</a>.</p>';
} else {
return '<p>This plugin recommends a PHP version higher than ' . $this->recommended_version . '. Read more information about <a href="http://www.wpupdatephp.com/update/">how you can update</a>.</p>';
}
}
if ( ! empty( $this->plugin_name ) ) {
return '<p>Unfortunately, ' | php | {
"resource": ""
} |
q176 | Navigator.splAutoloader | train | private static function splAutoloader($class_name) {
if('Treffynnon\\Navigator' === substr(ltrim($class_name, '\\'), 0, 20)) {
$class_path = realpath(__DIR__ | php | {
"resource": ""
} |
q177 | Navigator.distanceFactory | train | public static function distanceFactory($lat1, $long1, $lat2, $long2) {
$point1 = new L(new | php | {
"resource": ""
} |
q178 | Navigator.getDistance | train | public static function getDistance($lat1, $long1, $lat2, $long2) {
| php | {
"resource": ""
} |
q179 | WorkerManager.exitWorker | train | public function exitWorker(int $sig, array $pid): self
{
$this->logger->debug('worker ['.$pid['pid'].'] exit with ['.$sig.']', [
'category' => get_class($this),
]);
pcntl_waitpid($pid['pid'], $status, WNOHANG | WUNTRACED);
| php | {
"resource": ""
} |
q180 | WorkerManager.spawnInitialWorkers | train | protected function spawnInitialWorkers()
{
$this->logger->debug('spawn initial ['.$this->min_children.'] workers', [
'category' => get_class($this),
]);
if (self::PM_DYNAMIC === $this->pm || self::PM_STATIC === $this->pm) {
| php | {
"resource": ""
} |
q181 | WorkerManager.spawnMinimumWorkers | train | protected function spawnMinimumWorkers()
{
$this->logger->debug('verify that the minimum number ['.$this->min_children.'] of workers are running', [
'category' => get_class($this),
]);
| php | {
"resource": ""
} |
q182 | Scheduler.getJob | train | public function getJob(ObjectId $id): Process
{
$result = $this->db->{$this->job_queue}->findOne([
'_id' => $id,
], [
'typeMap' => self::TYPE_MAP,
]);
if (null === $result) {
| php | {
"resource": ""
} |
q183 | Scheduler.cancelJob | train | public function cancelJob(ObjectId $id): bool
{
$result = $this->updateJob($id, JobInterface::STATUS_CANCELED);
if (1 !== $result->getMatchedCount()) {
throw new JobNotFoundException('job '.$id.' was not found');
}
$this->db->{$this->event_queue}->insertOne([
| php | {
"resource": ""
} |
q184 | Scheduler.addJob | train | public function addJob(string $class, $data, array $options = []): Process
{
$document = $this->prepareInsert($class, $data, $options);
$result = $this->db->{$this->job_queue}->insertOne($document);
$this->logger->debug('queue job ['.$result->getInsertedId().'] added to ['.$class.']', [
'category' => get_class($this),
'params' => $options,
'data' => $data,
]);
$this->db->{$this->event_queue}->insertOne([
'job' => $result->getInsertedId(),
| php | {
"resource": ""
} |
q185 | Scheduler.addJobOnce | train | public function addJobOnce(string $class, $data, array $options = []): Process
{
$filter = [
'class' => $class,
'$or' => [
['status' => JobInterface::STATUS_WAITING],
['status' => JobInterface::STATUS_POSTPONED],
['status' => JobInterface::STATUS_PROCESSING],
],
];
$requested = $options;
$document = $this->prepareInsert($class, $data, $options);
if (true !== $options[self::OPTION_IGNORE_DATA]) {
$filter = ['data' => $data] + $filter;
}
$result = $this->db->{$this->job_queue}->updateOne($filter, ['$setOnInsert' => $document], [
'upsert' => true,
'$isolated' => true,
]);
if ($result->getMatchedCount() > 0) {
$document = $this->db->{$this->job_queue}->findOne($filter, [
'typeMap' => self::TYPE_MAP,
]);
if (array_intersect_key($document['options'], $requested) !== $requested || ($data !== $document['data'] && true === $options[self::OPTION_IGNORE_DATA])) {
$this->logger->debug('job ['.$document['_id'].'] options/data changed, reschedule new job', [
'category' => get_class($this),
'data' => $data,
| php | {
"resource": ""
} |
q186 | Scheduler.listen | train | public function listen(Closure $callback, array $query = []): self
{
if (0 === count($query)) {
$query = [
'timestamp' => ['$gte' => new UTCDateTime()],
];
}
$cursor = $this->events->getCursor($query);
while (true) {
if (null === $cursor->current()) {
if ($cursor->getInnerIterator()->isDead()) {
$this->logger->error('events queue cursor is dead, is it a capped collection?', [
'category' => get_class($this),
]);
$this->events->create();
return $this->listen($callback, $query);
}
$this->events->next($cursor, function () use ($callback, $query) {
| php | {
"resource": ""
} |
q187 | Scheduler.prepareInsert | train | protected function prepareInsert(string $class, $data, array &$options = []): array
{
$defaults = [
self::OPTION_AT => $this->default_at,
self::OPTION_INTERVAL => $this->default_interval,
self::OPTION_RETRY => $this->default_retry,
self::OPTION_RETRY_INTERVAL => $this->default_retry_interval,
self::OPTION_FORCE_SPAWN => false,
self::OPTION_TIMEOUT => $this->default_timeout,
self::OPTION_IGNORE_DATA => false,
];
$options = array_merge($defaults, $options);
$options = SchedulerValidator::validateOptions($options);
$document = [
'class' => $class,
| php | {
"resource": ""
} |
q188 | TranslatableFormFieldTransformation.transformFormField | train | public function transformFormField(FormField $field)
{
$newfield = $field->performReadOnlyTransformation();
$fieldname = $field->getName();
if ($this->original->isLocalizedField($fieldname)) {
$field->setName($this->original->getLocalizedFieldName($fieldname));
$value = $this->original->getLocalizedValue($fieldname);
if ($value instanceof DBField) {
| php | {
"resource": ""
} |
q189 | Tournament.start | train | public function start()
{
if ($this->state != 'pending') {
throw new AlreadyStartedException('Tournament is already underway.');
}
| php | {
"resource": ""
} |
q190 | Tournament.finalize | train | public function finalize()
{
if ($this->state != 'awaiting_review') {
throw new StillRunningException('Tournament is still running.');
}
| php | {
"resource": ""
} |
q191 | Tournament.update | train | public function update($params = [])
{
$response = Guzzle::put("tournaments/{$this->id}", $params);
| php | {
"resource": ""
} |
q192 | Distance.get | train | public function get(D\Calculator\CalculatorInterface $calculator = null, D\Converter\ConverterInterface $unit_converter = null) {
if (is_null($calculator)) {
$calculator = new | php | {
"resource": ""
} |
q193 | CustomInstaller.getPackageReplacementTokens | train | protected function getPackageReplacementTokens(PackageInterface $package)
{
$vars = array(
'{$type}' => $package->getType(),
);
$prettyName = $package->getPrettyName();
if (strpos($prettyName, '/') !== false) {
$pieces = explode('/', $prettyName);
| php | {
"resource": ""
} |
q194 | CustomInstaller.getPluginConfiguration | train | protected function getPluginConfiguration()
{
if (!isset($this->configuration)) {
$extra = $this->composer->getPackage()->getExtra();
// We check if we need to support the legacy configuration.
$legacy = false;
if (isset($extra['custom-installer'])) {
// Legacy
$legacy = true;
foreach ($extra['custom-installer'] as $key => $val) {
if (is_array($val)) {
$legacy = false;
break;
}
| php | {
"resource": ""
} |
q195 | Term.getTaxonomyKey | train | public function getTaxonomyKey()
{
$called_class_segments = explode('\\', get_called_class());
$class_name = end($called_class_segments);
return (is_null($this->taxonomy_key))
| php | {
"resource": ""
} |
q196 | Term.getOptionID | train | public function getOptionID($term_id = null)
{
return join('_', array(
$this->getTaxonomyKey(),
| php | {
"resource": ""
} |
q197 | Term.renderAdminColumn | train | public function renderAdminColumn($column_name, $term_id)
{
| php | {
"resource": ""
} |
q198 | Term.getEditPermalink | train | public function getEditPermalink($object_type = null)
{
// WordPress get_edit_term_link requires an object_type
// but if this object was created by \Taco\Post::getTerms
// then it will have an object_id, which also works
if (is_null($object_type)) {
$object_type = $this->get('object_id');
| php | {
"resource": ""
} |
q199 | Term.getWhere | train | public static function getWhere($args = array())
{
$instance = Term\Factory::create(get_called_class());
// Allow sorting both by core fields and custom fields
// See: http://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters
$default_args = array(
'orderby' => $instance->getDefaultOrderBy(),
'order' => $instance->getDefaultOrder(),
'hide_empty' => false, // Note: This goes against a WordPress get_terms default. But this seems more practical.
);
$criteria = array_merge($default_args, $args);
// Custom ordering
$orderby = null;
$order = null;
$wordpress_sortable_fields = array('id', 'name', 'count', 'slug', 'term_group', 'none');
if (array_key_exists('orderby', $criteria) && !in_array($criteria['orderby'], $wordpress_sortable_fields)) {
$orderby = $criteria['orderby'];
$order = (array_key_exists('order', $criteria))
? strtoupper($criteria['order'])
: 'ASC';
unset($criteria['orderby']);
unset($criteria['order']);
}
$criteria['taxonomy'] = $instance->getTaxonomyKey();
$terms = Term\Factory::createMultiple(get_terms($criteria));
// We might be done
if (!Arr::iterable($terms)) {
return $terms;
}
if (!$orderby) {
return $terms;
}
// Custom sorting that WordPress can't do
$field = $instance->getField($orderby);
// Make sure we're sorting numerically if appropriate
// because WordPress is storing strings for all vals
if ($field['type'] === 'number') {
foreach ($terms as &$term) {
if (!isset($term->$orderby)) {
continue;
}
if | php | {
"resource": ""
} |