_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q247600 | BufferedIterable.limit | validation | public function limit(int $limit) : BufferedIterable
{
Preconditions::checkArgument(0 < $limit, 'Limit must be a positive integer!');
return new BufferedIterable($this->chunkProvider, $this->filter, $limit, $this->providerCallLimit);
} | php | {
"resource": ""
} |
q247601 | BufferedIterable.filter | validation | public function filter(callable $predicate) : BufferedIterable
{
return new BufferedIterable($this->chunkProvider, $predicate, $this->limit, $this->providerCallLimit);
} | php | {
"resource": ""
} |
q247602 | TimeUnit.toDateInterval | validation | public function toDateInterval(float $duration) : DateInterval
{
Preconditions::checkState($this->dateIntervalFormat !== null, '[%s] does not support toDateInterval()', $this);
return new DateInterval(sprintf($this->dateIntervalFormat, $duration));
} | php | {
"resource": ""
} |
q247603 | TimeUnit.convert | validation | public function convert(float $duration, TimeUnit $timeUnit) : float
{
return $duration * ($timeUnit->inMicros / $this->inMicros);
} | php | {
"resource": ""
} |
q247604 | Profiler.start | validation | public function start($name) : Profiler
{
if (!$this->globalStopwatch->isRunning()) {
$this->globalStopwatch->start();
}
if ($this->entryStopwatch->isRunning()) {
$this->recordEntry();
}
$this->currentName = $name;
$this->entryStopwatch->start();
return $this;
} | php | {
"resource": ""
} |
q247605 | Ordering.nullsFirst | validation | public function nullsFirst() : Ordering
{
return Ordering::from(Collections::comparatorFrom(
function ($object1, $object2) {
return $object1 === null
? -1
: ($object2 === null
? 1
: $this->compare($object1, $object2));
}
));
} | php | {
"resource": ""
} |
q247606 | Ordering.onResultOf | validation | public function onResultOf(callable $function) : Ordering
{
return Ordering::from(Collections::comparatorFrom(
function ($object1, $object2) use ($function) {
return $this->compare(
Functions::call($function, $object1),
Functions::call($function, $object2)
);
}
));
} | php | {
"resource": ""
} |
q247607 | Ordering.compound | validation | public function compound(Comparator $secondaryComparator) : Ordering
{
return Ordering::from(Collections::comparatorFrom(
function ($object1, $object2) use ($secondaryComparator) {
$res = $this->compare($object1, $object2);
return $res !== 0 ? $res : $secondaryComparator->compare($object1, $object2);
}
));
} | php | {
"resource": ""
} |
q247608 | Ordering.min | validation | public function min(Traversable $traversable)
{
$array = iterator_to_array($traversable, false);
Arrays::sort($array, $this);
return Preconditions::checkElementExists($array, 0);
} | php | {
"resource": ""
} |
q247609 | TafDecoder.parseWithMode | validation | private function parseWithMode($raw_taf, $strict)
{
// prepare decoding inputs/outputs: (trim, remove linefeeds and returns, no more than one space)
$clean_taf = trim($raw_taf);
$clean_taf = preg_replace("#\n+#", ' ', $clean_taf);
$clean_taf = preg_replace("#\r+#", ' ', $clean_taf);
$clean_taf = preg_replace('#[ ]{2,}#', ' ', $clean_taf) . ' ';
$clean_taf = strtoupper($clean_taf);
if (strpos($clean_taf, 'CNL') === false) {
// appending END to it is necessary to detect the last line of evolution
// but only when the TAF wasn't cancelled (CNL)
$remaining_taf = trim($clean_taf) . ' END';
} else {
$remaining_taf = $clean_taf;
}
$decoded_taf = new DecodedTaf($clean_taf);
$with_cavok = false;
// call each decoder in the chain and use results to populate decoded taf
foreach ($this->decoder_chain as $chunk_decoder) {
try {
// try to parse a chunk with current chunk decoder
$decoded = $chunk_decoder->parse($remaining_taf, $with_cavok);
// map obtained fields (if any) to the final decoded object
$result = $decoded['result'];
if ($result != null) {
foreach ($result as $key => $value) {
if ($value !== null) {
$setter_name = 'set'.ucfirst($key);
$decoded_taf->$setter_name($value);
}
}
}
// update remaining taf for next round
$remaining_taf = $decoded['remaining_taf'];
} catch (ChunkDecoderException $cde) {
// log error in decoded taf and abort decoding if in strict mode
$decoded_taf->addDecodingException($cde);
// abort decoding if strict mode is activated, continue otherwise
if ($strict) {
break;
}
// update remaining taf for next round
$remaining_taf = $cde->getRemainingTaf();
}
// hook for CAVOK decoder, keep CAVOK information in memory
if ($chunk_decoder instanceof VisibilityChunkDecoder) {
$with_cavok = $decoded_taf->getCavok();
}
}
// weather evolutions
$evolutionDecoder = new EvolutionChunkDecoder($strict, $with_cavok);
while ($remaining_taf != null && trim($remaining_taf) != 'END') {
$evolutionDecoder->parse($remaining_taf, $decoded_taf);
$remaining_taf = $evolutionDecoder->getRemaining();
}
return $decoded_taf;
} | php | {
"resource": ""
} |
q247610 | Functions.compose | validation | public static function compose(callable $g, callable $f) : callable
{
return function ($input) use ($g, $f) {
return Functions::call($g, Functions::call($f, $input));
};
} | php | {
"resource": ""
} |
q247611 | Functions.forMap | validation | public static function forMap(array $map) : callable
{
return function ($index) use ($map) {
Preconditions::checkArgument(
array_key_exists($index, $map),
"The given key '%s' does not exist in the map",
$index
);
return $map[$index];
};
} | php | {
"resource": ""
} |
q247612 | Searchable.add | validation | public static function add($classname, $columns = array(), $title = null)
{
if ($title) {
Deprecation::notice(1.1, "Title is no longer used, instead set ClassName.PluralName in translations");
}
self::config()->objects[$classname] = $columns;
$cols_string = '"' . implode('","', $columns) . '"';
} | php | {
"resource": ""
} |
q247613 | FluentIterable.append | validation | public function append(IteratorAggregate $other) : FluentIterable
{
return self::from(Iterables::concat($this, $other));
} | php | {
"resource": ""
} |
q247614 | FluentIterable.filterBy | validation | public function filterBy(string $className) : FluentIterable
{
return self::from(Iterables::filterBy($this, $className));
} | php | {
"resource": ""
} |
q247615 | FluentIterable.transformAndConcat | validation | public function transformAndConcat(callable $transformer) : FluentIterable
{
return self::from(Iterables::concatIterables($this->transform($transformer)));
} | php | {
"resource": ""
} |
q247616 | FluentIterable.first | validation | public function first() : Optional
{
try {
return Optional::ofNullable($this->get(0));
} catch (OutOfBoundsException $e) {
return Optional::absent();
}
} | php | {
"resource": ""
} |
q247617 | FluentIterable.sorted | validation | public function sorted(Comparator $comparator) : FluentIterable
{
$array = $this->toArray();
Arrays::sort($array, $comparator);
return self::of($array);
} | php | {
"resource": ""
} |
q247618 | FluentIterable.toArray | validation | public function toArray() : array
{
$res = [];
Iterators::each($this->iterator(), function ($element) use (&$res) {
$res[] = $element;
});
return $res;
} | php | {
"resource": ""
} |
q247619 | Repository.readStoreRecord | validation | protected function readStoreRecord($type, array $query) {
$model = $this->store->get_record($type, $query);
if ($model === false) {
throw new Exception('Record not found.');
}
return $model;
} | php | {
"resource": ""
} |
q247620 | Repository.readStoreRecords | validation | protected function readStoreRecords($type, array $query) {
$model = $this->store->get_records($type, $query);
return $model;
} | php | {
"resource": ""
} |
q247621 | Repository.readAttempt | validation | public function readAttempt($id) {
$model = $this->readObject($id, 'quiz_attempts');
$model->url = $this->cfg->wwwroot . '/mod/quiz/attempt.php?attempt='.$id;
$model->name = 'Attempt '.$id;
return $model;
} | php | {
"resource": ""
} |
q247622 | Repository.readQuestionAttempts | validation | public function readQuestionAttempts($id) {
$questionAttempts = $this->readStoreRecords('question_attempts', ['questionusageid' => $id]);
foreach ($questionAttempts as $questionIndex => $questionAttempt) {
$questionAttemptSteps = $this->readStoreRecords('question_attempt_steps', ['questionattemptid' => $questionAttempt->id]);
foreach ($questionAttemptSteps as $stepIndex => $questionAttemptStep) {
$questionAttemptStep->data = $this->readStoreRecords('question_attempt_step_data', ['attemptstepid' => $questionAttemptStep->id]);
}
$questionAttempt->steps = $questionAttemptSteps;
}
return $questionAttempts;
} | php | {
"resource": ""
} |
q247623 | Repository.readQuestions | validation | public function readQuestions($quizId) {
$quizSlots = $this->readStoreRecords('quiz_slots', ['quizid' => $quizId]);
$questions = [];
foreach ($quizSlots as $index => $quizSlot) {
try {
$question = $this->readStoreRecord('question', ['id' => $quizSlot->questionid]);
$question->answers = $this->readStoreRecords('question_answers', ['question' => $question->id]);
$question->url = $this->cfg->wwwroot . '/mod/question/question.php?id='.$question->id;
if ($question->qtype == 'numerical') {
$question->numerical = (object)[
'answers' => $this->readStoreRecords('question_numerical', ['question' => $question->id]),
'options' => $this->readStoreRecord('question_numerical_options', ['question' => $question->id]),
'units' => $this->readStoreRecords('question_numerical_units', ['question' => $question->id])
];
} else if ($question->qtype == 'match') {
$question->match = (object)[
'options' => $this->readStoreRecord('qtype_match_options', ['questionid' => $question->id]),
'subquestions' => $this->readStoreRecords('qtype_match_subquestions', ['questionid' => $question->id])
];
} else if (strpos($question->qtype, 'calculated') === 0) {
$question->calculated = (object)[
'answers' => $this->readStoreRecords('question_calculated', ['question' => $question->id]),
'options' => $this->readStoreRecord('question_calculated_options', ['question' => $question->id])
];
} else if ($question->qtype == 'shortanswer') {
$question->shortanswer = (object)[
'options' => $this->readStoreRecord('qtype_shortanswer_options', ['questionid' => $question->id])
];
}
$questions[$question->id] = $question;
}
catch (\Exception $e) {
// Question not found; maybe it was deleted since the event.
// Don't add the question to the list, but also don't block the attempt event.
}
}
return $questions;
} | php | {
"resource": ""
} |
q247624 | Repository.readFeedbackAttempt | validation | public function readFeedbackAttempt($id) {
$model = $this->readObject($id, 'feedback_completed');
$model->url = $this->cfg->wwwroot . '/mod/feedback/complete.php?id='.$id;
$model->name = 'Attempt '.$id;
$model->responses = $this->readStoreRecords('feedback_value', ['completed' => $id]);
return $model;
} | php | {
"resource": ""
} |
q247625 | Repository.readFeedbackQuestions | validation | public function readFeedbackQuestions($id) {
$questions = $this->readStoreRecords('feedback_item', ['feedback' => $id]);
$expandedQuestions = [];
foreach ($questions as $index => $question) {
$expandedQuestion = $question;
$expandedQuestion->template = $this->readStoreRecord('feedback_template', ['id' => $question->template]);
$expandedQuestion->url = $this->cfg->wwwroot . '/mod/feedback/edit_item.php?id='.$question->id;
$expandedQuestions[$index] = $expandedQuestion;
}
return $expandedQuestions;
} | php | {
"resource": ""
} |
q247626 | Repository.readCourse | validation | public function readCourse($id) {
if ($id == 0) {
$courses = $this->store->get_records('course',array());
//since get_records will return the ids as Key values for the array,
//just use key to find the first id in the course table for the index page
$id = key($courses);
}
$model = $this->readObject($id, 'course');
$model->url = $this->cfg->wwwroot.($id > 0 ? '/course/view.php?id=' . $id : '');
return $model;
} | php | {
"resource": ""
} |
q247627 | Repository.readUser | validation | public function readUser($id) {
$model = $this->readObject($id, 'user');
$model->url = $this->cfg->wwwroot;
$model->fullname = $this->fullname($model);
if (isset($model->password)){
unset($model->password);
}
if (isset($model->secret)){
unset($model->secret);
}
if (isset($model->lastip)){
unset($model->lastip);
}
return $model;
} | php | {
"resource": ""
} |
q247628 | Repository.readDiscussion | validation | public function readDiscussion($id) {
$model = $this->readObject($id, 'forum_discussions');
$model->url = $this->cfg->wwwroot . '/mod/forum/discuss.php?d=' . $id;
return $model;
} | php | {
"resource": ""
} |
q247629 | Repository.readSite | validation | public function readSite() {
$model = $this->readCourse(1);
$model->url = $this->cfg->wwwroot;
$model->type = "site";
return $model;
} | php | {
"resource": ""
} |
q247630 | Repository.readFacetofaceSession | validation | public function readFacetofaceSession($id) {
$model = $this->readObject($id, 'facetoface_sessions');
$model->dates = $this->readStoreRecords('facetoface_sessions_dates', ['sessionid' => $id]);
$model->url = $this->cfg->wwwroot . '/mod/facetoface/signup.php?s=' . $id;
return $model;
} | php | {
"resource": ""
} |
q247631 | Repository.readFacetofaceSessionSignups | validation | public function readFacetofaceSessionSignups($sessionid, $timecreated) {
$signups = $this->readStoreRecords('facetoface_signups', ['sessionid' => $sessionid]);
foreach ($signups as $index => $signup) {
$signups[$index]->statuses = $this->readStoreRecords('facetoface_signups_status', ['signupid' => $signup->id]);
$signups[$index]->attendee = $this->readUser($signup->userid);
}
return $signups;
} | php | {
"resource": ""
} |
q247632 | Repository.readScormScoesTrack | validation | public function readScormScoesTrack($userid, $scormid, $scoid, $attempt) {
$trackingValues = [];
$scormTracking = $this->readStoreRecords('scorm_scoes_track', [
'userid' => $userid,
'scormid'=> $scormid,
'scoid' => $scoid,
'attempt' => $attempt
]);
foreach ($scormTracking as $st) {
if ($st->element == 'cmi.core.score.min') {
$trackingValues['scoremin'] = $st->value;
} else if ($st->element == 'cmi.core.score.max') {
$trackingValues['scoremax'] = $st->value;
} else if ($st->element == 'cmi.core.lesson_status') {
$trackingValues['status'] = $st->value;
}
}
return $trackingValues;
} | php | {
"resource": ""
} |
q247633 | Collections.reverseOrder | validation | public static function reverseOrder(Comparator $comparator = null) : Comparator
{
if ($comparator === null) {
$comparator = ComparableComparator::instance();
}
return new ReverseComparator($comparator);
} | php | {
"resource": ""
} |
q247634 | TryTo.run | validation | public static function run(callable $tryBlock, array $exceptions = [], callable $finallyBlock = null) : TryTo
{
try {
return Success::of(Functions::call($tryBlock));
} catch (Exception $e) {
if (count($exceptions) === 0) {
return Failure::of($e);
}
$error = FluentIterable::of($exceptions)
->filter(Predicates::assignableFrom(get_class($e)))
->first();
if ($error->isPresent()) {
return Failure::of($e);
}
throw $e;
} finally {
if ($finallyBlock !== null) {
Functions::call($finallyBlock);
}
}
} | php | {
"resource": ""
} |
q247635 | AndFinally.andFinally | validation | public function andFinally(callable $finallyBlock) : TryTo
{
return TryTo::run($this->tryBlock, $this->exceptions, $finallyBlock);
} | php | {
"resource": ""
} |
q247636 | FileStorage.init | validation | public function init()
{
parent::init();
$this->path = Yii::getAlias($this->path);
FileHelper::createDirectory($this->path, $this->dirMode, true);
} | php | {
"resource": ""
} |
q247637 | LockedRunnableWrapper.run | validation | public function run() : void
{
$thrownException = null;
try {
$this->lock->lock();
try {
$this->runnable->run();
} catch (Exception $e) {
self::getLogger()->error($e);
$thrownException = $e;
}
$this->lock->unLock();
} catch (LockException $e) {
throw new RunException('Lock error during running.', 0, $e);
}
if ($thrownException !== null) {
throw new RunException('Error during execution wrapped Runnable object.', 0, $thrownException);
}
} | php | {
"resource": ""
} |
q247638 | EvolutionChunkDecoder.addEvolution | validation | private function addEvolution($decoded_taf, $evolution, $result, $entity_name)
{
// clone the evolution entity
/** @var Evolution $newEvolution */
$new_evolution = clone($evolution);
// add the new entity to it
$new_evolution->setEntity($result[$entity_name]);
// possibly add cavok to it
if ($entity_name == 'visibility' && $this->with_cavok == true) {
$new_evolution->setCavok(true);
}
// get the original entity from the decoded taf or a new one decoded taf doesn't contain it yet
$getter_name = 'get'.ucfirst($entity_name);
$setter_name = 'set'.ucfirst($entity_name);
$decoded_entity = $decoded_taf->$getter_name();
if ($decoded_entity == null || $entity_name == 'clouds' || $entity_name == 'weatherPhenomenons') {
// that entity is not in the decoded_taf yet, or it's a cloud layer which is a special case
$decoded_entity = $this->instantiateEntity($entity_name);
}
// add the new evolution to that entity
$decoded_entity->addEvolution($new_evolution);
// update the decoded taf's entity or add the new one to it
if ($entity_name == 'clouds') {
$decoded_taf->addCloud($decoded_entity);
} elseif ($entity_name == 'weatherPhenomenons') {
$decoded_taf->addWeatherPhenomenon($decoded_entity);
} else {
$decoded_taf->$setter_name($decoded_entity);
}
} | php | {
"resource": ""
} |
q247639 | EvolutionChunkDecoder.instantiateEntity | validation | private function instantiateEntity($entity_name)
{
$entity = null;
if ($entity_name == 'weatherPhenomenons') {
$entity = new WeatherPhenomenon();
} else if ($entity_name == 'maxTemperature') {
$entity = new Temperature();
} else if ($entity_name == 'minTemperature') {
$entity = new Temperature();
} else if ($entity_name == 'clouds') {
$entity = new CloudLayer();
} else if ($entity_name == 'surfaceWind') {
$entity = new SurfaceWind();
} else if ($entity_name = 'visibility') {
$entity = new Visibility();
}
return $entity;
} | php | {
"resource": ""
} |
q247640 | Controller.createEvents | validation | public function createEvents(array $events) {
$results = [];
foreach ($events as $index => $opts) {
$route = isset($opts['eventname']) ? $opts['eventname'] : '';
if (isset(static::$routes[$route]) && ($opts['userid'] > 0 || $opts['relateduserid'] > 0)) {
try {
$event = '\LogExpander\Events\\'.static::$routes[$route];
array_push($results , (new $event($this->repo))->read($opts));
}
catch (\Exception $e) {
// Error processing event; skip it.
}
}
}
return $results;
} | php | {
"resource": ""
} |
q247641 | ObjectClass.init | validation | public static function init() : void
{
self::$classMap = new CallbackLazyMap(
function ($className) {
$trimmedClassName = trim($className, '\\');
return $trimmedClassName === $className
? new ObjectClass($className)
: ObjectClass::$classMap->$trimmedClassName;
}
);
} | php | {
"resource": ""
} |
q247642 | ObjectClass.getResource | validation | public function getResource($resource) : ?string
{
Preconditions::checkState($this->isPsr0Compatible(), "Class '%s' must be PSR-0 compatible!", $this->getName());
$slashedFileName = $this->getSlashedFileName();
$filePath = $resource[0] == '/'
? str_replace("/{$this->getSlashedName()}.php", '', $slashedFileName) . $resource
: dirname($slashedFileName) . '/' . $resource;
return is_file($filePath) ? $filePath : null;
} | php | {
"resource": ""
} |
q247643 | ErrorHandler.register | validation | public static function register()
{
set_error_handler(
function ($code, $message, $file, $line, $context) {
if (error_reporting() == 0) {
return false;
}
ErrorType::forCode($code)->throwException($message, $file, $line, $context);
}
);
} | php | {
"resource": ""
} |
q247644 | ForecastPeriod.isValid | validation | public function isValid()
{
// check that attribute aren't null
if (
$this->getFromDay() == null || $this->getFromHour() == null ||
$this->getToDay() == null || $this->getToHour() == null
) {
return false;
}
// check ranges
if ($this->getFromDay() < 1 || $this->getFromDay() > 31) {
return false;
}
if ($this->getToDay() < 1 || $this->getToDay() > 31) {
return false;
}
if ($this->getFromHour() > 24 || $this->getToHour() > 24) {
return false;
}
if ($this->getFromDay() == $this->getToDay() && $this->getFromHour() >= $this->getToHour()) {
return false;
}
return true;
} | php | {
"resource": ""
} |
q247645 | Exceptions.propagateIfInstanceOf | validation | public static function propagateIfInstanceOf(Exception $exception, string $exceptionClass) : void
{
if (is_a($exception, $exceptionClass)) {
throw $exception;
}
} | php | {
"resource": ""
} |
q247646 | TafChunkDecoder.consume | validation | public function consume($remaining_taf)
{
$chunk_regexp = $this->getRegexp();
// try to match chunk's regexp on remaining taf
if (preg_match($chunk_regexp, $remaining_taf, $matches)) {
$found = $matches;
} else {
$found = null;
}
// consume what has been previously found with the same regexp
$new_remaining_taf = preg_replace($chunk_regexp, '', $remaining_taf, 1);
return array(
'found' => $found,
'remaining' => $new_remaining_taf,
);
} | php | {
"resource": ""
} |
q247647 | PhpFileStorage.forceScriptCache | validation | protected function forceScriptCache($fileName)
{
if (
(PHP_SAPI !== 'cli' && ini_get('opcache.enable')) ||
ini_get('opcache.enable_cli')
) {
opcache_invalidate($fileName, true); // @codeCoverageIgnore
opcache_compile_file($fileName); // @codeCoverageIgnore
}
if (ini_get('apc.enabled')) {
apc_delete_file($fileName); // @codeCoverageIgnore
apc_bin_loadfile($fileName); // @codeCoverageIgnore
}
} | php | {
"resource": ""
} |
q247648 | Iterables.filter | validation | public static function filter(IteratorAggregate $unfiltered, callable $predicate) : IteratorAggregate
{
return new CallableIterable(
function () use ($unfiltered, $predicate) {
return Iterators::filter(Iterators::from($unfiltered->getIterator()), $predicate);
}
);
} | php | {
"resource": ""
} |
q247649 | Iterables.filterBy | validation | public static function filterBy(IteratorAggregate $unfiltered, string $className) : IteratorAggregate
{
return self::from(Iterators::filterBy(Iterators::from($unfiltered->getIterator()), $className));
} | php | {
"resource": ""
} |
q247650 | Iterables.concat | validation | public static function concat(IteratorAggregate $a, IteratorAggregate $b) : IteratorAggregate
{
return self::from(Iterators::concat(Iterators::from($a->getIterator()), Iterators::from($b->getIterator())));
} | php | {
"resource": ""
} |
q247651 | Iterables.concatIterables | validation | public static function concatIterables(IteratorAggregate $iterables) : IteratorAggregate
{
return self::from(
Iterators::concatIterators(
FluentIterable::from($iterables)
->transform(
function (Traversable $element) {
return Iterators::from($element);
}
)
->iterator()
)
);
} | php | {
"resource": ""
} |
q247652 | Iterables.any | validation | public static function any(IteratorAggregate $iterable, callable $predicate) : bool
{
return Iterators::any(Iterators::from($iterable->getIterator()), $predicate);
} | php | {
"resource": ""
} |
q247653 | Iterables.all | validation | public static function all(IteratorAggregate $iterable, callable $predicate) : bool
{
return Iterators::all(Iterators::from($iterable->getIterator()), $predicate);
} | php | {
"resource": ""
} |
q247654 | Iterables.transform | validation | public static function transform(IteratorAggregate $fromIterable, callable $transformer) : IteratorAggregate
{
return new CallableIterable(
function () use ($fromIterable, $transformer) {
return Iterators::transform(Iterators::from($fromIterable->getIterator()), $transformer);
}
);
} | php | {
"resource": ""
} |
q247655 | Iterables.limit | validation | public static function limit(IteratorAggregate $iterable, int $limitSize) : IteratorAggregate
{
return new CallableIterable(
function () use ($iterable, $limitSize) {
return Iterators::limit(Iterators::from($iterable->getIterator()), $limitSize);
}
);
} | php | {
"resource": ""
} |
q247656 | Iterables.get | validation | public static function get(IteratorAggregate $iterable, int $position)
{
return Iterators::get(Iterators::from($iterable->getIterator()), $position);
} | php | {
"resource": ""
} |
q247657 | Iterables.skip | validation | public static function skip(IteratorAggregate $iterable, int $numberToSkip) : IteratorAggregate
{
return new CallableIterable(
function () use ($iterable, $numberToSkip) {
$iterator = Iterators::from($iterable->getIterator());
Iterators::advance($iterator, $numberToSkip);
return $iterator;
}
);
} | php | {
"resource": ""
} |
q247658 | Iterables.size | validation | public static function size(IteratorAggregate $iterable) : int
{
if ($iterable instanceof Countable) {
return $iterable->count();
}
return Iterators::size(Iterators::from($iterable->getIterator()));
} | php | {
"resource": ""
} |
q247659 | Iterables.isEmpty | validation | public static function isEmpty(IteratorAggregate $iterable) : bool
{
return Iterators::isEmpty(Iterators::from($iterable->getIterator()));
} | php | {
"resource": ""
} |
q247660 | Stopwatch.start | validation | public function start() : Stopwatch
{
Preconditions::checkState(!$this->isRunning, 'This stopwatch is already running.');
$this->isRunning = true;
$this->startTick = $this->ticker->read();
return $this;
} | php | {
"resource": ""
} |
q247661 | Stopwatch.stop | validation | public function stop() : Stopwatch
{
$tick = $this->ticker->read();
Preconditions::checkState($this->isRunning, 'This stopwatch is already stopped.');
$this->isRunning = false;
$this->elapsedMicros += ($tick - $this->startTick);
return $this;
} | php | {
"resource": ""
} |
q247662 | Predicates.ands | validation | public static function ands(callable ...$predicates) : callable
{
return function ($element) use ($predicates) {
foreach ($predicates as $predicate) {
if (!self::call($predicate, $element)) {
return false;
}
}
return true;
};
} | php | {
"resource": ""
} |
q247663 | SearchResults.getMenu | validation | public function getMenu($level = 1)
{
if (class_exists(ContentController::class)) {
$controller = ContentController::singleton();
return $controller->getMenu($level);
}
} | php | {
"resource": ""
} |
q247664 | Google.isConfigured | validation | public function isConfigured() {
if (empty($this->options['application_name']) ||
empty($this->options['client_id']) ||
empty($this->options['client_secret'])) {
return false;
}
return true;
} | php | {
"resource": ""
} |
q247665 | Google.getClient | validation | protected function getClient($redirecturl = '') {
// keep only one instance during a session
if (is_object($this->google)) {
return $this->google;
}
if ($redirecturl == '') {
$redirecturl = $this->redirecturl;
} else {
$this->redirecturl = $redirecturl;
}
$client = new \Google_Client();
$client->setApplicationName($this->options['application_name']);
$client->setClientId($this->options['client_id']);
$client->setClientSecret($this->options['client_secret']);
$client->setRedirectUri($redirecturl);
$client->setDeveloperKey($this->options['api_key']);
$client->setScopes(array('https://www.googleapis.com/auth/userinfo.profile','https://www.googleapis.com/auth/userinfo.email'));
$this->google = $client;
return $client;
} | php | {
"resource": ""
} |
q247666 | Google.getLoginStartUrl | validation | public function getLoginStartUrl($redirecturl) {
$client = $this->getClient($redirecturl);
$authUrl = $client->createAuthUrl();
return $authUrl;
} | php | {
"resource": ""
} |
q247667 | Google.completeLogin | validation | public function completeLogin($extrainputs = array()) {
if ($extrainputs['code'] == '' && $extrainputs['error'] != '') {
throw new \Exception($extrainputs['error']);
}
$client = $this->getClient();
$client->authenticate($extrainputs['code']);
$this->access_token = $client->getAccessToken();
return $this->getUserProfile();
} | php | {
"resource": ""
} |
q247668 | Google.getUserProfile | validation | public function getUserProfile() {
$client = $this->getClient();
$client->setAccessToken($this->access_token);
$plus = new \Google_Service_Plus($client);
$oauth2 = new \Google_Service_Oauth2($client);
if ($client->getAccessToken()) {
$user = $oauth2->userinfo->get();
if (isset($user->id)) {
$name = $user->givenName;
if (!empty($user->familyName)) {
$name = $user->familyName.' '.$user->givenName;
}
$profile = array(
'userid'=>$user->id,
'name' => $name,
'imageurl' => $user->picture,
'email' => $user->email
);
return $profile;
}
}
throw new \Exception('Can not get google profile');
} | php | {
"resource": ""
} |
q247669 | Facebook.getFacebookObject | validation | protected function getFacebookObject() {
// keep only one instance during a session
if (is_object($this->fb)) {
return $this->fb;
}
$fb = new \Facebook\Facebook([
'app_id' => $this->options['api_key'],
'app_secret' => $this->options['secret_key'],
'default_graph_version' => 'v3.0',
]);
$this->fb = $fb;
return $fb;
} | php | {
"resource": ""
} |
q247670 | Facebook.getLoginStartUrl | validation | public function getLoginStartUrl($redirecturl) {
$facebook = $this->getFacebookObject();
$helper = $facebook->getRedirectLoginHelper();
$permissions = ['email']; // Optional permissions
$loginUrl = $helper->getLoginUrl($redirecturl, $permissions);
return $loginUrl;
} | php | {
"resource": ""
} |
q247671 | Facebook.completeLogin | validation | public function completeLogin($extrainputs = array()) {
$facebook = $this->getFacebookObject();
// we are not sure about $_GET contains all correct data
// as in this model data are posted with $extrainputs
// ideally it would be good if facebook lib accept data not only from _GET but also from any array
$old_GET = $_GET;
$_GET = $extrainputs;
$helper = $facebook->getRedirectLoginHelper();
// don't catch exceptions. it will be done in the model or controller
$accessToken = $helper->getAccessToken();
$_GET = $old_GET;
if (! isset($accessToken)) {
if ($helper->getError()) {
throw new \Exception($helper->getError().' '.
$helper->getErrorCode().' '.
$helper->getErrorReason().' '.
$helper->getErrorDescription());
} else {
throw new \Exception('Unknown error from Facebook');
}
}
$this->accesstoken = $accessToken;
return $this->getUserProfile();
} | php | {
"resource": ""
} |
q247672 | Facebook.getUserProfile | validation | public function getUserProfile() {
$facebook = $this->getFacebookObject();
$response = $facebook->get('/me', $this->accesstoken);
$me = $response->getGraphUser();
return array(
'userid'=>$me->getId(),
'name'=>$me->getName(),
'email'=>$me->getField('email'),
'imageurl'=>'https://graph.facebook.com/'.$me->getId().'/picture?type=large');
} | php | {
"resource": ""
} |
q247673 | Request.removeDisplayField | validation | public function removeDisplayField($displayField)
{
$key = array_search($displayField, $this->displayFields);
if ($key) {
unset($this->displayFields[$key]);
$this->displayFields = array_values($this->displayFields);
}
} | php | {
"resource": ""
} |
q247674 | Base.getSerializeVars | validation | protected function getSerializeVars($skip = array()) {
$vars = get_object_vars($this);
$servars = array();
foreach ($vars as $k=>$v) {
// skip what is in the array
if (in_array($k,$skip)) {
continue;
}
// skip 2 standars properties as no sence to serialize them
if ($k == 'options' || $k == 'logger') {
continue;
}
$servars[] = $k;
}
return $servars;
} | php | {
"resource": ""
} |
q247675 | Xingapi.getLoginStartUrl | validation | public function getLoginStartUrl($redirecturl) {
$credentials = array(
'identifier' => $this->options['consumer_key'],
'secret' => $this->options['consumer_secret'],
'callback_uri' => $redirecturl
);
$server = new \League\OAuth1\Client\Server\Xing($credentials);
$this->temp_credentials = $server->getTemporaryCredentials();
return $server->getAuthorizationUrl($this->temp_credentials);
} | php | {
"resource": ""
} |
q247676 | Xingapi.completeLogin | validation | public function completeLogin($extrainputs = array()) {
if (!isset($extrainputs['oauth_token']) || $extrainputs['oauth_token'] == '') {
throw new \Exception('Xing oauth. Somethign went wrong. No token in the session');
}
$credentials = array(
'identifier' => $this->options['consumer_key'],
'secret' => $this->options['consumer_secret']
);
$server = new \League\OAuth1\Client\Server\Xing($credentials);
$this->access_token = $server->getTokenCredentials($this->temp_credentials,
$extrainputs['oauth_token'], $extrainputs['oauth_verifier']);
return $this->getUserProfile();
} | php | {
"resource": ""
} |
q247677 | Xingapi.getUserProfile | validation | public function getUserProfile() {
$credentials = array(
'identifier' => $this->options['consumer_key'],
'secret' => $this->options['consumer_secret']
);
$server = new \League\OAuth1\Client\Server\Xing($credentials);
$user = $server->getUserDetails($this->access_token);
return array(
'userid'=>$user->uid,
'name'=>$user->display_name,
'imageurl'=>$user->imageUrl);
} | php | {
"resource": ""
} |
q247678 | Twitter.getLoginStartUrl | validation | public function getLoginStartUrl($redirecturl) {
$connection = new TwitterOAuth($this->options['consumer_key'],$this->options['consumer_secret']);
$connection->setTimeouts(10, 15);
$request_token = $connection->oauth('oauth/request_token', array('oauth_callback' => $redirecturl));
$this->request_token = array();
$this->request_token['oauth_token'] = $request_token['oauth_token'];
$this->request_token['oauth_token_secret'] = $request_token['oauth_token_secret'];
return $connection->url('oauth/authorize', array('oauth_token' => $request_token['oauth_token']));
} | php | {
"resource": ""
} |
q247679 | Twitter.completeLogin | validation | public function completeLogin($extrainputs = array()) {
$request_token = [];
$request_token['oauth_token'] = $this->request_token['oauth_token'];
$request_token['oauth_token_secret'] = $this->request_token['oauth_token_secret'];
$this->logQ('session token '.print_r($request_token,true),'twitter');
$this->logQ('extra options '.print_r($extrainputs,true),'twitter');
if (isset($extrainputs['oauth_token']) && $request_token['oauth_token'] !== $extrainputs['oauth_token']) {
throw new \Exception('Twitter oauth. Somethign went wrong. No token in the session');
}
$connection = new TwitterOAuth($this->options['consumer_key'],$this->options['consumer_secret'],
$request_token['oauth_token'], $request_token['oauth_token_secret']);
$connection->setTimeouts(10, 15);
$access_token = $connection->oauth("oauth/access_token", array("oauth_verifier" => $extrainputs['oauth_verifier']));
$this->access_token = $access_token;
return $this->getUserProfile();
} | php | {
"resource": ""
} |
q247680 | Twitter.getUserProfile | validation | public function getUserProfile() {
$connection = new TwitterOAuth($this->options['consumer_key'],$this->options['consumer_secret'],
$this->access_token['oauth_token'], $this->access_token['oauth_token_secret']);
$connection->setTimeouts(10, 15);
$user = $connection->get("account/verify_credentials");
return array(
'userid'=>$user->id,
'name'=>$user->screen_name,
'imageurl'=>$user->profile_image_url);
} | php | {
"resource": ""
} |
q247681 | Symfony2.transform | validation | public function transform( $target = null, $controller = null, $action = null, array $params = [], array $trailing = [], array $config = [] )
{
if( !empty( $trailing ) ) {
$params['trailing'] = join( '_', $trailing );
}
$params = $this->sanitize( $params );
$refType = \Symfony\Component\Routing\Generator\UrlGeneratorInterface::ABSOLUTE_PATH;
if( isset( $config['absoluteUri'] ) ) {
$refType = \Symfony\Component\Routing\Generator\UrlGeneratorInterface::ABSOLUTE_URL;
}
return $this->router->generate( $target, $params + $this->fixed, $refType );
} | php | {
"resource": ""
} |
q247682 | AuthFactory.getSocialLoginObject | validation | public static function getSocialLoginObject($network,$options = array(), $logger = null) {
// do some filters and checks for name
$network = preg_replace('![^a-z0-9]!i','',$network);
if ($network == '') {
throw new \Exception('Social Login Network can not be empty');
}
$class = '\\Gelembjuk\\Auth\\SocialLogin\\'.ucfirst($network);
if (!class_exists($class)) {
throw new \Exception(sprintf('Integration with a class name %s not found',$class));
}
// create an object
$object = new $class($options);
// set logger (even if it is null then no problem)
$object->setLogger($logger);
return $object;
} | php | {
"resource": ""
} |
q247683 | Client.getAllResources | validation | public function getAllResources($name, $full = false, array $filters = [], array $fields = []) {
$this->lastRequest = new Request;
$this->lastRequest->setMode(Request::MODE_READ);
$this->lastRequest->setResourceName($name);
if ($full) {
$this->lastRequest->enableFullResults();
}
$this->lastRequest->setFilters($filters);
$this->lastRequest->setFields($fields);
$data = [];
$page = 1;
do {
$this->lastRequest->setCurrentPage($page);
$response = $this->proceed();
$data = ArrayUtils::merge($data, $response->getData()->getData());
$page++;
} while ($response->getPagination()->getPage() != $response->getPagination()->getPages());
return $data;
} | php | {
"resource": ""
} |
q247684 | Http.httpRequest | validation | public function httpRequest($url)
{
if (DEBUG)
echo "HTTP request: $url\n";
// Initialize
$curl = curl_init();
// Setup the target
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, 0);
// Return in string
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// Timeout
curl_setopt($curl, CURLOPT_TIMEOUT, CURL_TIMEOUT);
// Webbot name
curl_setopt($curl, CURLOPT_USERAGENT, SPIDER_NAME);
// Minimize logs
curl_setopt($curl, CURLOPT_VERBOSE, false);
// Limit redirections to 4
curl_setopt($curl, CURLOPT_MAXREDIRS, 4);
// Follow redirects
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
// Create return array
$response['file'] = curl_exec($curl);
$response['status'] = curl_getinfo($curl);
$response['error'] = curl_error($curl);
// Execute the request
curl_exec($curl);
// Close the handler
curl_close($curl);
if (DEBUG === 'verbose')
{
echo "Retrieved HTTP:\n";
var_dump($response['status']);
var_dump($response['error']);
}
if ($response['file'] == '')
die("Error while making the HTTP request: no HTML retrieved.");
return $response;
} | php | {
"resource": ""
} |
q247685 | Linkedin.getClient | validation | protected function getClient($redirecturl = '') {
// keep only one instance during a session
if (is_object($this->linkedin)) {
return $this->linkedin;
}
if ($redirecturl == '') {
$redirecturl = $this->redirecturl;
} else {
$this->redirecturl = $redirecturl;
}
$this->logQ('redirect '.$redirecturl,'linkedin');
$API_CONFIG = array(
'api_key' => $this->options['api_key'],
'api_secret' => $this->options['api_secret'],
'callback_url' => $redirecturl
);
$this->linkedin = $linkedin = new \LinkedIn\LinkedIn($API_CONFIG);
return $this->linkedin;
} | php | {
"resource": ""
} |
q247686 | Linkedin.getLoginStartUrl | validation | public function getLoginStartUrl($redirecturl) {
$linkedin = $this->getClient($redirecturl);
$url = $linkedin->getLoginUrl(
array(
\LinkedIn\LinkedIn::SCOPE_BASIC_PROFILE,
\LinkedIn\LinkedIn::SCOPE_EMAIL_ADDRESS
)
);
return $url;
} | php | {
"resource": ""
} |
q247687 | Linkedin.completeLogin | validation | public function completeLogin($extrainputs = array()) {
$linkedin = $this->getClient();
$this->token = $linkedin->getAccessToken($extrainputs['code']);
return $this->getUserProfile();
} | php | {
"resource": ""
} |
q247688 | Linkedin.getUserProfile | validation | public function getUserProfile() {
$linkedin = $this->getClient();
$response = $linkedin->get('/people/~:(id,first-name,last-name,picture-url,public-profile-url,email-address)');
if (isset($response['emailAddress'])) {
return array(
'userid'=>$response['id'],
'name'=>$response['firstName'].' '.$response['lastName'],
'email'=>$response['emailAddress'],
'imageurl'=>$response['pictureUrl']
);
}
} | php | {
"resource": ""
} |
q247689 | LanguageMatcher.getBestLanguageMatch | validation | public function getBestLanguageMatch(array $supportedLanguages, array $languageHeaders): ?string
{
usort($languageHeaders, [$this, 'compareAcceptLanguageHeaders']);
$rankedLanguageHeaders = array_filter($languageHeaders, [$this, 'filterZeroScores']);
$rankedLanguageHeaderValues = $this->getLanguageValuesFromHeaders($rankedLanguageHeaders);
foreach ($rankedLanguageHeaderValues as $language) {
$languageParts = explode('-', $language);
// Progressively truncate this language tag and try to match a supported language
do {
foreach ($supportedLanguages as $supportedLanguage) {
if ($language === '*' || implode('-', $languageParts) === $supportedLanguage) {
return $supportedLanguage;
}
}
array_pop($languageParts);
} while (count($languageParts) > 0);
}
return null;
} | php | {
"resource": ""
} |
q247690 | LanguageMatcher.compareAcceptLanguageHeaders | validation | private function compareAcceptLanguageHeaders(AcceptLanguageHeaderValue $a, AcceptLanguageHeaderValue $b): int
{
$aQuality = $a->getQuality();
$bQuality = $b->getQuality();
if ($aQuality < $bQuality) {
return 1;
}
if ($aQuality > $bQuality) {
return -1;
}
$aValue = $a->getLanguage();
$bValue = $b->getLanguage();
if ($aValue === '*') {
if ($bValue === '*') {
return 0;
}
return 1;
}
if ($bValue === '*') {
return -1;
}
return 0;
} | php | {
"resource": ""
} |
q247691 | LanguageMatcher.getLanguageValuesFromHeaders | validation | private function getLanguageValuesFromHeaders(array $headers): array
{
$languages = [];
foreach ($headers as $header) {
$languages[] = $header->getLanguage();
}
return $languages;
} | php | {
"resource": ""
} |
q247692 | RawUserContext.isLoggedIn | validation | public function isLoggedIn()
{
$cookieName = session_name();
$cookie = $this->getSession()->getCookie($cookieName);
if (null !== $cookie) {
$this->getSession('goutte')->setCookie($cookieName, $cookie);
return true;
}
return false;
} | php | {
"resource": ""
} |
q247693 | RawPageContext.findLabels | validation | public function findLabels($text)
{
$xpath = new XPath\InaccurateText('//label[@for]', $this->getWorkingElement());
$labels = [];
foreach ($xpath->text($text)->findAll() as $label) {
$labels[$label->getAttribute('for')] = $label;
}
return $labels;
} | php | {
"resource": ""
} |
q247694 | NegotiatedResponseFactory.createBody | validation | private function createBody(
IHttpRequestMessage $request,
$rawBody,
ContentNegotiationResult &$contentNegotiationResult = null
): ?IHttpBody {
if ($rawBody === null || $rawBody instanceof IHttpBody) {
return $rawBody;
}
if ($rawBody instanceof IStream) {
return new StreamBody($rawBody);
}
if (is_scalar($rawBody)) {
return new StringBody((string)$rawBody);
}
if ((!is_object($rawBody) && !is_array($rawBody)) || is_callable($rawBody)) {
throw new InvalidArgumentException('Unsupported body type ' . gettype($rawBody));
}
$type = TypeResolver::resolveType($rawBody);
$contentNegotiationResult = $this->contentNegotiator->negotiateResponseContent($type, $request);
$mediaTypeFormatter = $contentNegotiationResult->getFormatter();
if ($mediaTypeFormatter === null) {
throw $this->createNotAcceptableException($type);
}
$bodyStream = new Stream(fopen('php://temp', 'r+b'));
try {
$mediaTypeFormatter->writeToStream(
$rawBody,
$bodyStream,
$contentNegotiationResult->getEncoding()
);
} catch (SerializationException $ex) {
throw new HttpException(
HttpStatusCodes::HTTP_INTERNAL_SERVER_ERROR,
'Failed to serialize response body',
0,
$ex
);
}
return new StreamBody($bodyStream);
} | php | {
"resource": ""
} |
q247695 | NegotiatedResponseFactory.createNotAcceptableException | validation | private function createNotAcceptableException(string $type): HttpException
{
$headers = new HttpHeaders();
$headers->add('Content-Type', 'application/json');
$body = new StringBody(json_encode($this->contentNegotiator->getAcceptableResponseMediaTypes($type)));
$response = new Response(HttpStatusCodes::HTTP_NOT_ACCEPTABLE, $headers, $body);
return new HttpException($response);
} | php | {
"resource": ""
} |
q247696 | FormValueAssertion.textual | validation | public function textual()
{
$this->restrictElements([
'textarea' => [],
'input' => [],
]);
self::debug([
'Expected: %s',
'Value: %s',
'Tag: %s',
], [
$this->expected,
$this->value,
$this->tag,
]);
$this->assert(trim($this->expected) === $this->value);
} | php | {
"resource": ""
} |
q247697 | FormValueAssertion.selectable | validation | public function selectable()
{
$this->restrictElements(['select' => []]);
$data = [$this->value, $this->element->find('xpath', "//option[@value='$this->value']")->getText()];
self::debug([
'Expected: %s',
'Value: %s',
'Tag: %s',
], [
$this->expected,
implode(' => ', $data),
$this->tag,
]);
$this->assert(in_array($this->expected, $data), 'selected');
} | php | {
"resource": ""
} |
q247698 | ResponseFormatter.redirectToUri | validation | public function redirectToUri(IHttpResponseMessage $response, $uri, int $statusCode = 302): void
{
if (is_string($uri)) {
$uriString = $uri;
} elseif ($uri instanceof Uri) {
$uriString = (string)$uri;
} else {
throw new InvalidArgumentException('Uri must be instance of ' . Uri::class . ' or string');
}
$response->setStatusCode($statusCode);
$response->getHeaders()->add('Location', $uriString);
} | php | {
"resource": ""
} |
q247699 | ResponseFormatter.writeJson | validation | public function writeJson(IHttpResponseMessage $response, array $content): void
{
$json = json_encode($content);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new InvalidArgumentException('Failed to JSON encode content: ' . json_last_error_msg());
}
$response->getHeaders()->add('Content-Type', 'application/json');
$response->setBody(new StringBody($json));
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.