_id stringlengths 2 7 | title stringlengths 3 151 | partition stringclasses 3
values | text stringlengths 83 13k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q12300 | SickRage.episodeSetStatus | train | public function episodeSetStatus($tvdbId, $season, $status, $episode = null, $force = 0)
{
$uri = 'episode.setstatus';
$uriData = [
'tvdbid' => $tvdbId,
'season' => $season,
'status' => $status,
'force' => $force
];
if ( $episode ) { $uriData['episode'] = $episode; }
try {
$response = $this->_request(
[
'uri' => $uri,
'type' => 'get',
'data' => $uriData
]
);
} catch (\Exception $e) {
throw new InvalidException($e->getMessage());
}
return $response->getBody()->getContents();
} | php | {
"resource": ""
} |
q12301 | SickRage.future | train | public function future($sort = 'date', $type = 'missed|today|soon|later', $paused = null)
{
$uri = 'future';
$uriData = [
'sort' => $sort,
'type' => $type
];
if ( $paused ) { $uriData['paused'] = $paused; }
try {
$response = $this->_request(
[
'uri' => $uri,
'type' => 'get',
'data' => $uriData
]
);
} catch (\Exception $e) {
throw new InvalidException($e->getMessage());
}
return $response->getBody()->getContents();
} | php | {
"resource": ""
} |
q12302 | SickRage.logs | train | public function logs($minLevel = 'error')
{
$uri = 'history.trim';
$uriData = [
'min_level' => $minLevel
];
try {
$response = $this->_request(
[
'uri' => $uri,
'type' => 'get',
'data' => $uriData
]
);
} catch (\Exception $e) {
throw new InvalidException($e->getMessage());
}
return $response->getBody()->getContents();
} | php | {
"resource": ""
} |
q12303 | SickRage.showAddExisting | train | public function showAddExisting($tvdbId, $location, $flattenFolders = null, $initial = null, $archive = null)
{
$uri = 'show.addexisting';
$uriData = [
'tvdbid' => $tvdbId,
'location' => $location
];
if ( $flattenFolders ) { $uriData['flatten_folders'] = $flattenFolders; }
if ( $initial ) { $uriData['initial'] = $initial; }
if ( $archive ) { $uriData['archive'] = $archive; }
try {
$response = $this->_request(
[
'uri' => $uri,
'type' => 'get',
'data' => $uriData
]
);
} catch (\Exception $e) {
throw new InvalidException($e->getMessage());
}
return $response->getBody()->getContents();
} | php | {
"resource": ""
} |
q12304 | SickRage.showSeasons | train | public function showSeasons($tvdbId, $season = null)
{
$uri = 'show.seasons';
$uriData = [
'tvdbid' => $tvdbId
];
if ( is_numeric($season) ) { $uriData['season'] = $season; }
try {
$response = $this->_request(
[
'uri' => $uri,
'type' => 'get',
'data' => $uriData
]
);
} catch (\Exception $e) {
throw new InvalidException($e->getMessage());
}
return $response->getBody()->getContents();
} | php | {
"resource": ""
} |
q12305 | SickRage.showSetQuality | train | public function showSetQuality($tvdbId, $initial = null, $archive = null)
{
$uri = 'show.setquality';
$uriData = [
'tvdbid' => $tvdbId
];
if ( $initial ) { $uriData['initial'] = $initial; }
if ( $archive ) { $uriData['archive'] = $archive; }
try {
$response = $this->_request(
[
'uri' => $uri,
'type' => 'get',
'data' => $uriData
]
);
} catch (\Exception $e) {
throw new InvalidException($e->getMessage());
}
return $response->getBody()->getContents();
} | php | {
"resource": ""
} |
q12306 | SickRage.sbCheckScheduler | train | public function sbCheckScheduler()
{
$uri = 'sb.checkscheduler';
try {
$response = $this->_request(
[
'uri' => $uri,
'type' => 'get',
'data' => []
]
);
} catch (\Exception $e) {
throw new InvalidException($e->getMessage());
}
return $response->getBody()->getContents();
} | php | {
"resource": ""
} |
q12307 | SickRage.sbPauseBacklog | train | public function sbPauseBacklog($pause = 0)
{
$uri = 'sb.pausebacklog';
$uriData = [
'pause' => $pause
];
try {
$response = $this->_request(
[
'uri' => $uri,
'type' => 'get',
'data' => $uriData
]
);
} catch (\Exception $e) {
throw new InvalidException($e->getMessage());
}
return $response->getBody()->getContents();
} | php | {
"resource": ""
} |
q12308 | SickRage.sbSearchTvdb | train | public function sbSearchTvdb($name = null, $tvdbId = null, $lang = 'en')
{
$uri = 'sb.searchtvdb';
$uriData = [
'lang' => $lang
];
if ( $name ) { $uriData['name'] = $name; }
if ( $tvdbId ) { $uriData['tvdbid'] = $tvdbId; }
try {
$response = $this->_request(
[
'uri' => $uri,
'type' => 'get',
'data' => $uriData
]
);
} catch (\Exception $e) {
throw new InvalidException($e->getMessage());
}
return $response->getBody()->getContents();
} | php | {
"resource": ""
} |
q12309 | SickRage.sbSetDefaults | train | public function sbSetDefaults($futureShowPaused = null, $status = null,
$flattenFolders = null, $initial = null, $archive = null)
{
$uri = 'sb.setdefaults';
$uriData = [];
if ( $futureShowPaused ) { $uriData['future_show_paused'] = $futureShowPaused; }
if ( $status ) { $uriData['status'] = $status; }
if ( $flattenFolders ) { $uriData['flatten_folders'] = $flattenFolders; }
if ( $initial ) { $uriData['initial'] = $initial; }
if ( $archive ) { $uriData['archive'] = $archive; }
try {
$response = $this->_request(
[
'uri' => $uri,
'type' => 'get',
'data' => $uriData
]
);
} catch (\Exception $e) {
throw new InvalidException($e->getMessage());
}
return $response->getBody()->getContents();
} | php | {
"resource": ""
} |
q12310 | SessionValidator.isValid | train | public function isValid(SessionBagInterface $sessionBag)
{
return $sessionBag->get(self::PARAM_REMOTE_ADDR) === $this->hash($this->getRemoteAddr()) &&
$sessionBag->get(self::PARAM_USER_AGENT) === $this->hash($this->getUserAgent());
} | php | {
"resource": ""
} |
q12311 | SessionValidator.write | train | public function write(SessionBagInterface $sessionBag)
{
if ($this->hasRequiredParams()) {
// Writes hashes, not values themselves
$sessionBag->set(self::PARAM_REMOTE_ADDR, $this->hash($this->getRemoteAddr()));
$sessionBag->set(self::PARAM_USER_AGENT, $this->hash($this->getUserAgent()));
}
} | php | {
"resource": ""
} |
q12312 | SessionValidator.hasRequiredParams | train | private function hasRequiredParams()
{
return array_key_exists(self::PARAM_REMOTE_ADDR, $this->container) && array_key_exists(self::PARAM_USER_AGENT, $this->container);
} | php | {
"resource": ""
} |
q12313 | ColumnType.convertToArray | train | protected function convertToArray($value)
{
if (\is_string($value)) {
$value = [$value];
} elseif (null === $value) {
$value = [];
}
return $value;
} | php | {
"resource": ""
} |
q12314 | ColumnType.getParams | train | protected function getParams($type, $value)
{
if (false === strpos($value, '-')) {
throw new InvalidConfigurationException(sprintf('The "%s" option must be configured with "{prefix}-{size}"', $type));
}
list($prefix, $size) = explode('-', $value);
if (!\in_array($prefix, $this->validPrefix)) {
throw new InvalidConfigurationException(sprintf('The "%s" prefix option does not exist. Known options are: "'.implode('", "', $this->validPrefix).'"', $type));
}
if (!(int) $size) {
throw new InvalidConfigurationException(sprintf('The "%s" size option must be an integer', $type));
}
return [$prefix, $size];
} | php | {
"resource": ""
} |
q12315 | Controller.quit | train | public function quit($redirection = null)
{
if (!$this->response->getAjax()) {
if ($redirection) {
$this->redirection($redirection);
}
$this->shareMessages();
if (!GL_TESTING) {
Bootstrap::dispatch($this->response);
exit;
}
}
return true;
} | php | {
"resource": ""
} |
q12316 | Controller.addMessage | train | public function addMessage($message, $type = 'success')
{
Events::dispatch('onMessageDisplay', array('message' => $message, 'type' => $type));
$this->messages[] = array('message' => $message, 'type' => $type);
} | php | {
"resource": ""
} |
q12317 | Controller.getLink | train | public function getLink($controller, $params = array(), $fullPath = false)
{
if ($controller instanceof Controller) {
$controller = get_class($controller);
}
$controller = (string)$controller;
if(substr($controller, 0, 1) === "\\") {
$controller = substr($controller, 1);
}
try {
$url = Bootstrap::getSingleton()->getManager()->getRouter()->generate($controller, $params);
if ($fullPath) {
$protocol = 'http';
if (strpos($_SERVER['SCRIPT_URI'], 'https') !== false) {
$protocol = 'https';
}
return $protocol . '://' . $_SERVER['HTTP_HOST'] . $url;
}
return $url;
} catch (\Exception $ex) {
}
return "";
} | php | {
"resource": ""
} |
q12318 | WinCache.remove | train | public function remove($key)
{
if ($this->has($key)) {
return wincache_ucache_delete($key);
} else {
throw new RuntimeException(sprintf(
'Attempted to delete non-existing key "%s"', $key
));
}
} | php | {
"resource": ""
} |
q12319 | WinCache.getInfo | train | public function getInfo()
{
return array(
'ucache_meminfo' => wincache_ucache_meminfo(),
'ucache_info' => wincache_ucache_info(),
'session_cache_info' => wincache_scache_info(),
'session_cache_meminfo' => wincache_scache_meminfo(),
'rp_meminfo' => wincache_rplist_meminfo(),
'rp_fileinfo' => wincache_rplist_fileinfo(),
'opcode_fileinfo' => wincache_ocache_fileinfo(),
'opcode_meminfo' => wincache_ocache_meminfo(),
'filecache_meminfo' => wincache_fcache_fileinfo(),
'filecache_fileinfo' => wincache_fcache_meminfo()
);
} | php | {
"resource": ""
} |
q12320 | MinLength.isValid | train | public function isValid($target)
{
if (mb_strlen($target, $this->charset) < $this->length) {
$this->violate(sprintf($this->message, $this->length));
return false;
} else {
return true;
}
} | php | {
"resource": ""
} |
q12321 | Dispatcher.call | train | public function call($class, $action, array $params = array(), array $options = array())
{
$controller = $this->controllerFactory->build($class, $action, $options);
if (method_exists($controller, $action)) {
return call_user_func_array(array($controller, $action), $params);
} else {
throw new LogicException(sprintf(
'A %s controller must implement %s() method, because it has been defined in the map', $class, $action
));
}
} | php | {
"resource": ""
} |
q12322 | Dispatcher.forward | train | public function forward($notation, array $args = array())
{
$data = $this->mapManager->toCompliant($notation);
$controller = array_keys($data);
$controller = $controller[0];
$action = array_values($data);
$action = $action[0];
return $this->call($controller, $action, $args);
} | php | {
"resource": ""
} |
q12323 | Dispatcher.render | train | public function render($matchedURITemplate, array $params = array())
{
// For current URI template
$options = $this->mapManager->getDataByUriTemplate($matchedURITemplate);
$class = $this->mapManager->getControllerByURITemplate($matchedURITemplate);
$action = $this->mapManager->getActionByURITemplate($matchedURITemplate);
return $this->call($class, $action, $params, $options);
} | php | {
"resource": ""
} |
q12324 | OriginalSizeFactory.build | train | public function build($dir, $quality, array $options = array())
{
// Also, it would make sense to value user-provided prefix against regular [A-Z0-9] pattern
if (!isset($options['prefix'])) {
$options['prefix'] = 'original';
}
// By default, we don't want to limit dimensions
$maxWidth = 0;
$maxHeight = 0;
// If we have maximal dimensions limit, in configuration
if (isset($options['max_width']) && isset($options['max_height'])) {
$maxWidth = $options['max_width'];
$maxHeight = $options['max_height'];
}
return new OriginalSize($dir, $options['prefix'], $quality, $maxWidth, $maxHeight);
} | php | {
"resource": ""
} |
q12325 | Contact.setContacts | train | public function setContacts(array $contacts): SecurityTxt
{
if (!$this->validContacts($contacts, true)) {
throw new Exception('Contacts array must contain well-formed e-mails and/or URLs.');
}
$this->contacts = $contacts;
return $this;
} | php | {
"resource": ""
} |
q12326 | Contact.validContact | train | public function validContact(string $contact): bool
{
return filter_var($contact, FILTER_VALIDATE_EMAIL) !== false ||
filter_var($contact, FILTER_VALIDATE_URL) !== false;
} | php | {
"resource": ""
} |
q12327 | Contact.validContacts | train | public function validContacts(array $contacts, bool $use_keys = false): bool
{
if ($use_keys) {
$contacts = array_keys($contacts);
}
foreach ($contacts as $contact) {
if (!$this->validContact($contact)) {
return false;
}
}
return true;
} | php | {
"resource": ""
} |
q12328 | Contact.hasContacts | train | public function hasContacts(array $contacts): bool
{
foreach ($contacts as $contact) {
if (!$this->hasContact($contact)) {
return false;
}
}
return true;
} | php | {
"resource": ""
} |
q12329 | Filter.filterAttribute | train | public static function filterAttribute($value)
{
// Check whether current string has already been encoded
$isEncoded = TextUtils::strModified($value, function($target){
return self::escape($target);
});
// Decode if previous encoded or escaped
if ($isEncoded) {
$value = self::charsDecode($value);
}
// Convert special characters to make safe use of them
$value = self::specialChars($value);
return $value;
} | php | {
"resource": ""
} |
q12330 | Filter.stripTags | train | public static function stripTags($text, array $allowed = array())
{
// Based on [fernando at zauber dot es]'s solution
$allowed = array_map('strtolower', $allowed);
return preg_replace_callback('/<\/?([^>\s]+)[^>]*>/i', function ($matches) use (&$allowed) {
return in_array(strtolower($matches[1]), $allowed) ? $matches[0] : '';
}, $text);
} | php | {
"resource": ""
} |
q12331 | BaseRepository.remove | train | public function remove($target, $abort = true)
{
$entity = $this->find($target);
if ($abort) {
$this->isUsedByEntitys($entity);
}
$this->em()->remove($entity);
return $entity;
} | php | {
"resource": ""
} |
q12332 | CommandBuilder.formattedCommand | train | protected function formattedCommand($command)
{
$structure = [
$this->getEnvVariable(),
$this->executable,
$this->getOptions(),
$command
];
return implode(' ', array_filter($structure));
} | php | {
"resource": ""
} |
q12333 | MimeTypeGuesser.getTypeByExtension | train | public function getTypeByExtension($extension)
{
if ($this->isValidExtension($extension)) {
// We get back flipped copy
$list = $this->getList(true);
return $list[$extension];
} else {
// For all unknown extensions, the default Mime-Type is used
return 'application/octet-stream';
}
} | php | {
"resource": ""
} |
q12334 | MimeTypeGuesser.getExtensionByType | train | public function getExtensionByType($type)
{
if ($this->isValidType($type)) {
return $this->mime[$type];
} else {
throw new RuntimeException(sprintf('Invalid type "%s" supplied', $type));
}
} | php | {
"resource": ""
} |
q12335 | MimeTypeGuesser.getList | train | public function getList($flip = false)
{
if ($flip !== false) {
return array_flip($this->mime);
} else {
return $this->mime;
}
} | php | {
"resource": ""
} |
q12336 | MimeTypeGuesser.append | train | public function append(array $pair)
{
foreach ($pair as $key => $value) {
$this->mime[$key] = $value;
}
} | php | {
"resource": ""
} |
q12337 | ExportCommand.getGroupArgument | train | protected function getGroupArgument()
{
$groups = explode(',', preg_replace('/\s+/', '', $this->argument('group')));
return array_map(function ($group) {
return preg_replace('/\\.[^.\\s]{3,4}$/', '', $group);
}, $groups);
} | php | {
"resource": ""
} |
q12338 | ApplicationGateway.addMerchantPayment | train | public function addMerchantPayment($application, \DateTime $effectiveDate, $amount, $token)
{
return $this->postDocument(
'/v4/applications/' . $application . '/merchant-payments',
[
'amount' => $amount,
'effective_date' => $effectiveDate->format('Y-m-d'),
],
$token,
'Add Merchant Payment'
);
} | php | {
"resource": ""
} |
q12339 | Container.get | train | public function get(string $name)
{
$name = $this->getDefinitiveName($name);
if (!$this->has($name)) {
$instance = $this->build($name);
$this->store($instance);
}
return $this->instances[$name];
} | php | {
"resource": ""
} |
q12340 | Container.has | train | public function has(string $name): bool
{
$name = $this->getDefinitiveName($name);
return isset($this->instances[$name]);
} | php | {
"resource": ""
} |
q12341 | Container.createInstance | train | protected function createInstance(string $name, int $useStoredDependencies)
{
$name = $this->getDefinitiveName($name);
if (interface_exists($name)) {
throw new ContainerException(sprintf(
"Cannot create instance for interface `%s`.",
$name
));
}
try {
$dependencies = $this->getDependenciesFor($name, $useStoredDependencies);
} catch (Throwable $e) {
throw new ContainerException($e->getMessage());
}
return new $name(...$dependencies);
} | php | {
"resource": ""
} |
q12342 | Container.map | train | public function map(string $requested, string $replacement): void
{
$this->maps[$this->normalize($requested)] = $this->normalize($replacement);
} | php | {
"resource": ""
} |
q12343 | Container.getDependenciesFor | train | public function getDependenciesFor(
string $name,
int $useStoredDependencies = self::USE_STORED_DEPENDENCIES
): array {
$name = $this->getDefinitiveName($name);
try {
$reflection = new ReflectionClass($name);
} catch (Throwable $e) {
throw new ContainerException(sprintf(
'Could not create instance for class `%s`.',
$name
));
}
$constructor = $reflection->getConstructor();
if (!$constructor) {
return [];
}
$parameters = $constructor->getParameters();
$relationships = [];
$dependencies = [];
foreach ($parameters as $parameter) {
$class = $parameter->getClass();
if ($class === null) {
if (!$parameter->isOptional()) {
throw new ContainerException(sprintf(
'Cannot inject value for non-optional constructor parameter `$%s` without a default value.',
$parameter->name
));
}
$dependencies[] = $parameter->getDefaultValue();
continue;
}
$dependencyName = $this->getDefinitiveName($class->name);
$this->storeRelationship($name, $dependencyName);
$relationships[] = $dependencyName;
if ($useStoredDependencies === self::USE_NEW_DEPENDENCIES) {
$dependencies[] = $this->build($dependencyName);
} elseif ($useStoredDependencies === self::USE_STORED_DEPENDENCIES) {
$dependencies[] = $this->get($dependencyName);
} else {
throw new ContainerException(sprintf(
'Invalid dependency type value passed: `%d`.',
$useStoredDependencies
));
}
}
return $dependencies;
} | php | {
"resource": ""
} |
q12344 | Container.store | train | public function store($instance, string $name = null): void
{
if ($name === null) {
$name = get_class($instance);
}
$name = $this->getDefinitiveName($name);
$this->instances[$name] = $instance;
} | php | {
"resource": ""
} |
q12345 | Container.clear | train | public function clear(string $name): void
{
$name = $this->getDefinitiveName($name);
if (!$this->has($name)) {
throw NotFoundException::fromId($name);
}
unset($this->instances[$name]);
$this->clearRelationship($name);
} | php | {
"resource": ""
} |
q12346 | Container.clearExcept | train | public function clearExcept(array $keep): void
{
$kept = [];
foreach ($keep as $name) {
$name = $this->getDefinitiveName($name);
if (!$this->has($name)) {
throw NotFoundException::fromId($name);
}
$kept[$name] = $this->get($name);
}
$this->instances = $kept;
} | php | {
"resource": ""
} |
q12347 | Container.storeRelationship | train | protected function storeRelationship(string $class, string $dependency): void
{
$this->relationships[$class][$dependency] = true;
if (isset($this->relationships[$class][$dependency]) && isset($this->relationships[$dependency][$class])) {
throw new ContainerException(sprintf(
'Cyclical dependency found between `%s` and `%s`.',
$class,
$dependency
));
}
} | php | {
"resource": ""
} |
q12348 | Container.clearRelationship | train | protected function clearRelationship(string $name): void
{
// Clear from the left
unset($this->relationships[$name]);
// And clear from the right
foreach ($this->relationships as $left => &$objectNames) {
if (isset($objectNames[$name])) {
unset($objectNames[$name]);
}
}
} | php | {
"resource": ""
} |
q12349 | DocumentInstantiator.defineClass | train | protected function defineClass($fields)
{
//Rule to define class instance
$definition = $this->schema[DocumentEntity::SH_INSTANTIATION];
if (is_string($definition)) {
//Document has no variations
return $definition;
}
if (!is_array($fields)) {
//Unable to resolve for non array set, using same class as given
return $this->class;
}
$defined = $this->class;
foreach ($definition as $field => $child) {
if (array_key_exists($field, $fields)) {
//Apparently this is child
$defined = $child;
break;
}
}
return $defined;
} | php | {
"resource": ""
} |
q12350 | HashTrait.isCachable | train | public function isCachable(string $url, string $httpMethod) : bool
{
return $httpMethod === ClientInterface::HTTP_GET && $this->getCache() !== null;
} | php | {
"resource": ""
} |
q12351 | ColorHelper.getContrastYIQ | train | public static function getContrastYIQ($hexColor): string
{
$hexColor = str_replace('#', '', $hexColor);
$r = hexdec(substr($hexColor, 0, 2));
$g = hexdec(substr($hexColor, 2, 2));
$b = hexdec(substr($hexColor, 4, 2));
$yiq = (($r * 299) + ($g * 587) + ($b * 114)) / 1000;
return ($yiq >= 128) ? 'black' : 'white';
} | php | {
"resource": ""
} |
q12352 | PhpDocAuthorExtractor.setAuthors | train | protected function setAuthors($docBlock, $authors)
{
$newAuthors = array_unique(array_values($authors));
$lines = \explode("\n", $docBlock);
$lastAuthor = 0;
$indention = ' * @author ';
$cleaned = [];
foreach ($lines as $number => $line) {
if (\strpos($line, '@author') === false) {
continue;
}
$lastAuthor = $number;
$suffix = \trim(\substr($line, (\strpos($line, '@author') + 7)));
$indention = \substr($line, 0, (\strlen($line) - \strlen($suffix)));
$index = $this->searchAuthor($line, $newAuthors);
// Obsolete entry, remove it.
if (false === $index) {
$lines[$number] = null;
$cleaned[] = $number;
} else {
unset($newAuthors[$index]);
}
}
$lines = $this->addNewAuthors($lines, $newAuthors, $cleaned, $lastAuthor, $indention);
return \implode("\n", \array_filter($lines, function ($value) {
return null !== $value;
}));
} | php | {
"resource": ""
} |
q12353 | PhpDocAuthorExtractor.addNewAuthors | train | protected function addNewAuthors(array $lines, array $newAuthors, array $emptyLines, $lastAuthor, $indention)
{
if (empty($newAuthors)) {
return $lines;
}
// Fill the gaps we just made.
foreach ($emptyLines as $number) {
if (null === $author = \array_shift($newAuthors)) {
break;
}
$lines[$number] = $indention . $author;
}
if ((int) $lastAuthor === 0) {
$lastAuthor = (\count($lines) - 2);
}
if (0 === ($count = count($newAuthors))) {
return $lines;
}
// Still not empty, we have mooooore.
$lines = array_merge(
array_slice($lines, 0, ++$lastAuthor),
array_fill(0, $count, null),
array_slice($lines, $lastAuthor)
);
while ($author = \array_shift($newAuthors)) {
$lines[$lastAuthor++] = $indention . $author;
}
return $lines;
} | php | {
"resource": ""
} |
q12354 | PhpDocAuthorExtractor.searchAuthor | train | private function searchAuthor($line, $authors)
{
foreach ($authors as $index => $author) {
list($name, $email) = \explode(' <', $author);
$name = \trim($name);
$email = \trim(\substr($email, 0, -1));
if ((\strpos($line, $name) !== false) && (\strpos($line, $email) !== false)) {
unset($authors[$index]);
return $index;
}
}
return false;
} | php | {
"resource": ""
} |
q12355 | EngineTrait.getEngineOptions | train | protected function getEngineOptions()
{
$config = ProjectX::getProjectConfig();
$engine = $config->getEngine();
$options = $config->getOptions();
return isset($options[$engine])
? $options[$engine]
: [];
} | php | {
"resource": ""
} |
q12356 | EngineTrait.executeEngineCommand | train | protected function executeEngineCommand($command, $service = null, $options = [], $quiet = false, $localhost = false)
{
if ($command instanceof CommandBuilder) {
$command = $command->build();
}
$engine = $this->getEngineInstance();
if ($engine instanceof DockerEngineType && !$localhost) {
$results = $engine->execRaw($command, $service, $options, $quiet);
} else {
$results = $this->_exec($command);
}
$this->validateTaskResult($results);
return $results;
} | php | {
"resource": ""
} |
q12357 | ProductCSVBulkLoader.createRelationFromList | train | protected function createRelationFromList(
$object,
$relation,
$list,
$class,
$column,
$create = false
) {
$object->$relation()->removeAll();
foreach ($list as $name) {
$name = trim($name);
if (!empty($name)) {
$obj = $class::get()->find($column, $name);
if (empty($obj) && $create) {
$obj = $class::create();
$obj->$column = $name;
$obj->write();
}
if (!empty($obj)) {
$object->$relation()->add($obj);
}
}
}
} | php | {
"resource": ""
} |
q12358 | InheritanceHelper.makeDefinition | train | public function makeDefinition()
{
//Find only first level children stored in the same collection
$children = $this->findChildren(true, true);
if (empty($children)) {
//Nothing to inherit
return $this->schema->getClass();
}
//We must sort child in order or unique fields
uasort($children, [$this, 'sortChildren']);
//Fields which are common for parent and child models
$commonFields = $this->schema->getReflection()->getSchema();
$definition = [];
foreach ($children as $schema) {
//Child document fields
$fields = $schema->getReflection()->getSchema();
if (empty($fields)) {
throw new DefinitionException(
"Child document '{$schema->getClass()}' of '{$this->schema->getClass()}' does not have any fields"
);
}
$uniqueField = null;
if (empty($commonFields)) {
//Parent did not declare any fields, happen sometimes
$commonFields = $fields;
$uniqueField = key($fields);
} else {
foreach ($fields as $field => $type) {
if (!isset($commonFields[$field])) {
if (empty($uniqueField)) {
$uniqueField = $field;
}
//New non unique field (must be excluded from analysis)
$commonFields[$field] = true;
}
}
}
if (empty($uniqueField)) {
throw new DefinitionException(
"Child document '{$schema->getClass()}' of '{$this->schema->getClass()}' does not have any unique field"
);
}
$definition[$uniqueField] = $schema->getClass();
}
return $definition;
} | php | {
"resource": ""
} |
q12359 | InheritanceHelper.findChildren | train | public function findChildren(bool $sameCollection = false, bool $directChildren = false)
{
$result = [];
foreach ($this->schemas as $schema) {
//Only Document and DocumentEntity classes supported
if (!$schema instanceof DocumentSchema) {
continue;
}
//ReflectionEntity
$reflection = $schema->getReflection();
if ($reflection->isSubclassOf($this->schema->getClass())) {
if ($sameCollection && !$this->compareCollection($schema)) {
//Child changed collection or database
continue;
}
if (
$directChildren
&& $reflection->getParentClass()->getName() != $this->schema->getClass()
) {
//Grandson
continue;
}
$result[] = $schema;
}
}
return $result;
} | php | {
"resource": ""
} |
q12360 | InheritanceHelper.findPrimary | train | public function findPrimary(bool $sameCollection = true): string
{
$primary = $this->schema->getClass();
foreach ($this->schemas as $schema) {
//Only Document and DocumentEntity classes supported
if (!$schema instanceof DocumentSchema) {
continue;
}
if ($this->schema->getReflection()->isSubclassOf($schema->getClass())) {
if ($sameCollection && !$this->compareCollection($schema)) {
//Child changed collection or database
continue;
}
$primary = $schema->getClass();
}
}
return $primary;
} | php | {
"resource": ""
} |
q12361 | InheritanceHelper.compareCollection | train | protected function compareCollection(DocumentSchema $document)
{
if ($document->getDatabase() != $this->schema->getDatabase()) {
return false;
}
return $document->getCollection() == $this->schema->getCollection();
} | php | {
"resource": ""
} |
q12362 | InheritanceHelper.sortChildren | train | private function sortChildren(DocumentSchema $childA, DocumentSchema $childB)
{
return count($childA->getReflection()->getSchema()) > count($childB->getReflection()->getSchema());
} | php | {
"resource": ""
} |
q12363 | TwitterApi.authorizeUrl | train | public function authorizeUrl()
{
$request_token = $this->oauth('oauth/request_token', array('oauth_callback' => $this->callbackUrl));
if ($request_token)
{
Session::put('oauth_token', $request_token['oauth_token']);
Session::put('oauth_token_secret', $request_token['oauth_token_secret']);
$url = $this->url('oauth/authorize', array('oauth_token' => $request_token['oauth_token']));
return $url;
}
throw new TwitterOAuthException($request_token);
} | php | {
"resource": ""
} |
q12364 | TwitterApi.encodeAppAuthorization | train | private function encodeAppAuthorization($consumer)
{
// TODO: key and secret should be rfc 1738 encoded
$key = $consumer->key;
$secret = $consumer->secret;
return base64_encode($key . ':' . $secret);
} | php | {
"resource": ""
} |
q12365 | PlantUML.dump | train | public function dump(Graph $graph, $file, $format = PlantUML::FORMAT_TXT)
{
$format = $format ?: self::FORMAT_TXT;
try {
$content = implode(PHP_EOL, $graph->toArray()) . PHP_EOL;
if (self::FORMAT_UML === $format) {
$url = sprintf('http://www.plantuml.com/plantuml/uml/%s', $this->urlEncode($content));
if (false !== fwrite($file, $url . PHP_EOL)) {
return fclose($file);
}
return false;
}
if (self::FORMAT_TXT === $format) {
if (false !== fwrite($file, $content)) {
return fclose($file);
}
return false;
}
if (in_array($format, [self::FORMAT_PNG, self::FORMAT_SVG, self::FORMAT_ATXT, self::FORMAT_UTXT], true)) {
if (null === $this->java) {
return false;
}
$prefix = sys_get_temp_dir() . '/' . uniqid();
$txtPath = $prefix . '.txt';
$pngPath = $prefix . '.' . $format;
$clean = function () use ($txtPath, $pngPath) {
$this->fs->remove([$txtPath, $pngPath]);
};
$this->fs->dumpFile($txtPath, $content);
$builder = new ProcessBuilder();
$builder
->add($this->java)
->add('-jar')
->add(__DIR__ . '/../Resources/lib/plantuml.1.2017.19.jar')
->add($txtPath);
if (self::FORMAT_SVG === $format) {
$builder->add('-tsvg');
}
if (self::FORMAT_ATXT === $format) {
$builder->add('-txt');
}
if (self::FORMAT_UTXT === $format) {
$builder->add('-utxt');
}
$plantUml = $builder->getProcess();
$plantUml->run();
if ($plantUml->isSuccessful()) {
if (false !== $png = fopen($pngPath, 'r')) {
if (0 !== stream_copy_to_stream($png, $file)) {
$clean();
return fclose($file);
}
}
} else {
$this->logger->error($plantUml->getErrorOutput());
}
$clean();
return false;
}
return false;
} catch (\Exception $e) {
return false;
}
} | php | {
"resource": ""
} |
q12366 | PlantUML.urlAppend3bytes | train | private function urlAppend3bytes($b1, $b2, $b3)
{
$c1 = $b1 >> 2;
$c2 = (($b1 & 0x3) << 4) | ($b2 >> 4);
$c3 = (($b2 & 0xF) << 2) | ($b3 >> 6);
$c4 = $b3 & 0x3F;
return implode([
$this->urlEncode6bit($c1 & 0x3F),
$this->urlEncode6bit($c2 & 0x3F),
$this->urlEncode6bit($c3 & 0x3F),
$this->urlEncode6bit($c4 & 0x3F),
]);
} | php | {
"resource": ""
} |
q12367 | PlantUML.urlEncode6bit | train | private function urlEncode6bit($b)
{
if ($b < 10) {
return chr(48 + $b);
}
$b -= 10;
if ($b < 26) {
return chr(65 + $b);
}
$b -= 26;
if ($b < 26) {
return chr(97 + $b);
}
$b -= 26;
if ($b == 0) {
return '-';
}
if ($b == 1) {
return '_';
}
return '?';
} | php | {
"resource": ""
} |
q12368 | Writer.comment | train | public function comment(string $comment = ''): Writer
{
$comment = trim($comment);
if (!empty($comment)) {
$comment = ' ' . $comment;
}
return $this->line(trim('#' . $comment));
} | php | {
"resource": ""
} |
q12369 | Writer.spacers | train | public function spacers(int $count = 1): Writer
{
for ($x = 0; $x < $count; $x++) {
$this->spacer();
}
return $this;
} | php | {
"resource": ""
} |
q12370 | Writer.lines | train | public function lines(array $lines): Writer
{
foreach ($lines as $line) {
$this->line($line);
}
return $this;
} | php | {
"resource": ""
} |
q12371 | DocumentSchema.getCompositions | train | public function getCompositions(SchemaBuilder $builder): array
{
$result = [];
foreach ($this->reflection->getSchema() as $field => $type) {
if (is_string($type) && $builder->hasSchema($type)) {
$result[$field] = new CompositionDefinition(DocumentEntity::ONE, $type);
}
if (is_array($type) && isset($type[0]) && $builder->hasSchema($type[0])) {
$result[$field] = new CompositionDefinition(DocumentEntity::MANY, $type[0]);
}
}
return $result;
} | php | {
"resource": ""
} |
q12372 | DocumentSchema.packDefaults | train | protected function packDefaults(SchemaBuilder $builder, array $overwriteDefaults = []): array
{
//Defined compositions
$compositions = $this->getCompositions($builder);
//User defined default values
$userDefined = $overwriteDefaults + $this->getDefaults();
//We need mutators to normalize default values
$mutators = $this->getMutators();
$defaults = [];
foreach ($this->getFields() as $field => $type) {
$default = is_array($type) ? [] : null;
if (array_key_exists($field, $userDefined)) {
//No merge to keep fields order intact
$default = $userDefined[$field];
}
//Registering default values
$defaults[$field] = $this->mutateValue(
$builder,
$compositions,
$userDefined,
$mutators,
$field,
$default
);
}
return $defaults;
} | php | {
"resource": ""
} |
q12373 | DocumentSchema.packCompositions | train | public function packCompositions(SchemaBuilder $builder): array
{
$result = [];
foreach ($this->getCompositions($builder) as $name => $composition) {
$result[$name] = $composition->packSchema();
}
return $result;
} | php | {
"resource": ""
} |
q12374 | DocumentSchema.packAggregations | train | protected function packAggregations(SchemaBuilder $builder): array
{
$result = [];
foreach ($this->getAggregations() as $name => $aggregation) {
if (!$builder->hasSchema($aggregation->getClass())) {
throw new SchemaException(
"Aggregation {$this->getClass()}.'{$name}' refers to undefined document '{$aggregation->getClass()}'"
);
}
if ($builder->getSchema($aggregation->getClass())->isEmbedded()) {
throw new SchemaException(
"Aggregation {$this->getClass()}.'{$name}' refers to non storable document '{$aggregation->getClass()}'"
);
}
$result[$name] = $aggregation->packSchema();
}
return $result;
} | php | {
"resource": ""
} |
q12375 | DocumentSchema.mutateValue | train | protected function mutateValue(
SchemaBuilder $builder,
array $compositions,
array $userDefined,
array $mutators,
string $field,
$default
) {
//Let's process default value using associated setter
if (isset($mutators[DocumentEntity::MUTATOR_SETTER][$field])) {
try {
$setter = $mutators[DocumentEntity::MUTATOR_SETTER][$field];
$default = call_user_func($setter, $default);
return $default;
} catch (\Exception $exception) {
//Unable to generate default value, use null or empty array as fallback
}
}
if (isset($mutators[DocumentEntity::MUTATOR_ACCESSOR][$field])) {
$default = $this->accessorDefault(
$default,
$mutators[DocumentEntity::MUTATOR_ACCESSOR][$field]
);
}
if (isset($compositions[$field])) {
if (is_null($default) && !array_key_exists($field, $userDefined)) {
//Let's force default value for composite fields
$default = [];
}
$default = $this->compositionDefault($default, $compositions[$field], $builder);
return $default;
}
return $default;
} | php | {
"resource": ""
} |
q12376 | DocumentSchema.compositionDefault | train | protected function compositionDefault(
$default,
CompositionDefinition $composition,
SchemaBuilder $builder
) {
if (!is_array($default)) {
if ($composition->getType() == DocumentEntity::MANY) {
//Composition many must always defaults to array
return [];
}
//Composite ONE must always defaults to null if no default value are specified
return null;
}
//Nothing to do with value for composite many
if ($composition->getType() == DocumentEntity::MANY) {
return $default;
}
$embedded = $builder->getSchema($composition->getClass());
if (!$embedded instanceof self) {
//We can not normalize values handled by external schemas yet
return $default;
}
if ($embedded->getClass() == $this->getClass()) {
if (!empty($default)) {
throw new SchemaException(
"Possible recursion issue in '{$this->getClass()}', model refers to itself (has default value)"
);
}
//No recursions!
return null;
}
return $embedded->packDefaults($builder, $default);
} | php | {
"resource": ""
} |
q12377 | ParamBag.hasMany | train | public function hasMany(array $params)
{
foreach ($params as $param) {
if (!$this->has($param)) {
return false;
}
}
return true;
} | php | {
"resource": ""
} |
q12378 | ParamBag.setMany | train | public function setMany(array $params)
{
foreach ($params as $key => $value) {
$this->set($key, $value);
}
return $this;
} | php | {
"resource": ""
} |
q12379 | Tag.fieldLabels | train | public function fieldLabels($includerelations = true)
{
$labels = parent::fieldLabels($includerelations);
$tagLabels = array(
'Title' => _t('Tag.TITLE', 'Title'),
'Description' => _t('Tag.DESCRIPTION', 'Description'),
'Impression' => _t('Tag.IMPRESSION', 'Impression image'),
);
return array_merge($tagLabels, $labels);
} | php | {
"resource": ""
} |
q12380 | PatchingAuthorExtractorTrait.calculateUpdatedAuthors | train | protected function calculateUpdatedAuthors($path, $authors)
{
return \array_merge(\array_intersect_key($this->extractAuthorsFor($path), $authors), $authors);
} | php | {
"resource": ""
} |
q12381 | DefaultRateLimitCalculator.calculate | train | public function calculate(int $callsMade, int $callsLimit)
{
$callPercentage = floatval($callsMade / $callsLimit);
$limitPercentage = floatval(($callsLimit - $this->processes - $this->buffer) / $callsLimit);
return $callPercentage > $limitPercentage ? ($this->processes * $this->cycle) : $this->cycle;
} | php | {
"resource": ""
} |
q12382 | Aoe_Api2_Model_Auth_Adapter_Session.getUserParams | train | public function getUserParams(Mage_Api2_Model_Request $request)
{
$userParamsObj = new stdClass();
$userParamsObj->type = null;
$userParamsObj->id = null;
if ($this->isApplicableToRequest($request)) {
$userParamsObj->id = $this->getHelper()->getCustomerSession()->getCustomerId();
$userParamsObj->type = self::USER_TYPE_CUSTOMER;
}
return $userParamsObj;
} | php | {
"resource": ""
} |
q12383 | Aoe_Api2_Model_Auth_Adapter_Session.isApplicableToRequest | train | public function isApplicableToRequest(Mage_Api2_Model_Request $request)
{
// This auth adapter is for frontend use only
if (Mage::app()->getStore()->isAdmin()) {
return false;
}
// Ensure frontend sessions are initialized using the proper cookie name
$this->getHelper()->getCoreSession();
// We are only applicable if the customer is logged in already
return $this->getHelper()->getCustomerSession()->isLoggedIn();
} | php | {
"resource": ""
} |
q12384 | OneToMany.getResultSetWithoutSlaveColumnId | train | private function getResultSetWithoutSlaveColumnId(array $rows, $slaveColumnId)
{
// To be returned
$result = array();
foreach ($rows as $row) {
// Make sure the name is valid
if (isset($row[$slaveColumnId])) {
unset($row[$slaveColumnId]);
}
// Append filtered $row array to the outputting array
$result[] = $row;
}
return $result;
} | php | {
"resource": ""
} |
q12385 | FileEngineFactory.build | train | public static function build($file, $autoCreate = true)
{
$storage = new CacheFile(new NativeSerializer(), $file, $autoCreate);
$cache = new CacheEngine(new ArrayCache(), new ArraySignature(), $storage);
$cache->initialize();
return $cache;
} | php | {
"resource": ""
} |
q12386 | NewsControllerExtension.NewsArchive | train | public function NewsArchive($limit = 5, $random = null, $related = null)
{
if ($limit === 0) {
$limit = null;
}
$params = $this->owner->getURLParams();
$otherNews = null;
/** @var News $otherNews */
if ($related) {
$otherNews = $this->owner->getNews();
}
if (($otherNews && $otherNews->Tags()->count()) || !$related) {
return $this->getArchiveItems($otherNews, $limit, $random, $related, $params);
}
} | php | {
"resource": ""
} |
q12387 | NewsControllerExtension.NewsArchiveByHolderID | train | public function NewsArchiveByHolderID($holderID = null, $limit = 5)
{
$filter = array(
'Live' => 1,
'NewsHolderPageID' => $holderID,
'PublishFrom:LessThan' => SS_Datetime::now()->Rfc2822(),
);
if ($limit === 0) {
$limit = null;
}
if (class_exists('Translatable')) {
$filter['Locale'] = Translatable::get_current_locale();
}
$news = News::get()
->filter($filter)
->limit($limit);
if ($news->count() === 0) {
return null;
}
return $news;
} | php | {
"resource": ""
} |
q12388 | Normalizer.getUriFromGlobals | train | public static function getUriFromGlobals(array $serverParams): UriInterface
{
$uri = new Uri('');
$uri = $uri->withScheme(isset($serverParams['HTTPS']) && $serverParams['HTTPS'] !== 'off' ? 'https' : 'http');
$hasPort = false;
if (isset($serverParams['HTTP_HOST'])) {
$hostHeaderParts = explode(':', $serverParams['HTTP_HOST'], 2);
$uri = $uri->withHost($hostHeaderParts[0]);
if (count($hostHeaderParts) > 1) {
$hasPort = true;
$uri = $uri->withPort((int) $hostHeaderParts[1]);
}
} elseif (isset($serverParams['SERVER_NAME'])) {
$uri = $uri->withHost($serverParams['SERVER_NAME']);
} elseif (isset($serverParams['SERVER_ADDR'])) {
$uri = $uri->withHost($serverParams['SERVER_ADDR']);
}
if (!$hasPort && isset($serverParams['SERVER_PORT'])) {
$uri = $uri->withPort($serverParams['SERVER_PORT']);
}
$hasQuery = false;
if (isset($serverParams['REQUEST_URI'])) {
$requestUriParts = explode('?', $serverParams['REQUEST_URI'], 2);
$uri = $uri->withPath($requestUriParts[0]);
if (count($requestUriParts) > 1) {
$hasQuery = true;
$uri = $uri->withQuery($requestUriParts[1]);
}
}
if (!$hasQuery && isset($serverParams['QUERY_STRING'])) {
$uri = $uri->withQuery($serverParams['QUERY_STRING']);
}
return $uri;
} | php | {
"resource": ""
} |
q12389 | CheckoutUserAccountControllerExtension.updateAccountMenu | train | public function updateAccountMenu($menu)
{
$curr_action = $this->owner->request->param("Action");
$menu->add(new ArrayData(array(
"ID" => 11,
"Title" => _t('Checkout.Addresses', 'Addresses'),
"Link" => $this->owner->Link("addresses"),
"LinkingMode" => ($curr_action == "addresses") ? "current" : "link"
)));
} | php | {
"resource": ""
} |
q12390 | CheckoutUserAccountControllerExtension.updateEditAccountForm | train | public function updateEditAccountForm($form)
{
// Add company name field
$company_field = TextField::create(
"Company",
_t('CheckoutUsers.Company', "Company")
);
$company_field->setRightTitle(_t("Checkout.Optional", "Optional"));
$form->Fields()->insertBefore($company_field, "FirstName");
// Add contact phone number field
$phone_field = TextField::create(
"PhoneNumber",
_t("CheckoutUsers.PhoneNumber", "Phone Number")
);
$phone_field->setRightTitle(_t("Checkout.Optional", "Optional"));
$form->Fields()->add($phone_field);
} | php | {
"resource": ""
} |
q12391 | JsonAuthorExtractorTrait.loadFile | train | protected function loadFile($path)
{
$composerJson = $this->fileData($path);
return (null === $composerJson) ? null : (array) \json_decode($composerJson, true);
} | php | {
"resource": ""
} |
q12392 | SequenceGenerator.generateNextTemp | train | function generateNextTemp(\Doctrine\ORM\QueryBuilder $qb,$field)
{
$temporaryMask = $this->getTemporaryMask().'-{000}';
return $this->generate($qb,$temporaryMask ,$field,self::MODE_NEXT);
} | php | {
"resource": ""
} |
q12393 | Exception.getCodeAsString | train | public function getCodeAsString()
{
switch ($this->getCode()) {
case self::BURIED:
return 'Buried';
break;
case self::NOT_FOUND:
return 'Not Found';
break;
case self::EXPECTED_CRLF:
return 'Expected CRLF';
break;
case self::JOB_TOO_BIG:
return 'Job Too Big';
break;
case self::DEADLINE_SOON:
return 'Deadline Soon';
break;
case self::TIMED_OUT:
return 'Timed Out';
break;
case self::TUBE_NAME_TOO_LONG:
return 'Tube Name Too Long';
break;
case self::NOT_IGNORED:
return 'Not Ignored';
break;
case self::OUT_OF_MEMORY:
return 'Out of Memory';
break;
case self::INTERNAL_ERROR:
return 'Internal Error';
break;
case self::BAD_FORMAT:
return 'Bad Format';
break;
case self::UNKNOWN_COMMAND:
return 'Unknown Command';
break;
case self::SERVER_OFFLINE:
return 'Server Offline';
break;
case self::SERVER_READ:
return 'Server Read Error';
break;
case self::SERVER_WRITE:
return 'Server Write Error';
break;
default:
return 'Unknown';
break;
}
} | php | {
"resource": ""
} |
q12394 | InputValidator.factory | train | public static function factory(array $source, array $definitions, $translator)
{
return new self($source, $definitions, new DefinitionParser(new ConstraintFactory()), $translator);
} | php | {
"resource": ""
} |
q12395 | Response.clear | train | public function clear() {
$this->statusCode = self::HTTP_OK;
$this->headers = [];
$this->cookies = [];
$this->content = null;
$this->sent = false;
} | php | {
"resource": ""
} |
q12396 | Response.sendHeaders | train | private function sendHeaders() {
if (!headers_sent()) {
http_response_code($this->statusCode);
foreach ($this->headers as $header) {
header($header);
}
foreach ($this->cookies as $cookie) {
call_user_func_array("setcookie", $cookie);
}
}
} | php | {
"resource": ""
} |
q12397 | Response.sendConfig | train | private function sendConfig() {
if ($this->content !== null) {
if (($this->content instanceof stdClass) || is_array($this->content)) {
$content = ob_get_contents();
if (empty($content)) {
$this->contentType("application/json");
$this->content = json_encode($this->content);
}
}
}
} | php | {
"resource": ""
} |
q12398 | Response.sendContent | train | private function sendContent() {
if ($this->content !== null) {
if ($this->content instanceof View) {
$this->content->render();
}
else if (($this->content instanceof stdClass) || is_array($this->content)) {
echo "<pre>";
print_r ($this->content);
echo "</pre>";
}
else {
echo $this->content;
}
}
} | php | {
"resource": ""
} |
q12399 | ErrorCollector.formatExceptionData | train | public function formatExceptionData(GeneratedError $e)
{
$filePath = $e->getFile();
if ($filePath && file_exists($filePath)) {
$lines = file($filePath);
$start = $e->getLine() - 4;
$lines = array_slice($lines, $start < 0 ? 0 : $start, 7);
} else {
$lines = array("Cannot open the file ($filePath) in which the exception occurred ");
}
return array(
// 'type' => get_class($e),
'type' => '',
'message' => $e->getMessage(),
'code' => $e->getCode(),
'file' => $filePath,
'line' => $e->getLine(),
'surrounding_lines' => $lines
);
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.