_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q241100
ORM.reset
train
private function reset() { $vars = get_object_vars($this); // foreach ($vars as $key => $value) { unset($this->$key); } }
php
{ "resource": "" }
q241101
ORM.restore
train
public function restore() { if ($this->_kept) { $this->bring(); // Query::table(static::$table) ->set('deleted_at', 'NULL', false) ->where($this->_keyName, '=', $this->_keyValue) ->update(); } }
php
{ "resource": "" }
q241102
ORM.bring
train
private function bring() { foreach ($this->_keptData as $key => $value) { $this->$key = $value; } // $this->_keyValue = $this->_keptData[$this->_keyName]; // $this->_keptData = null; $this->_kept = false; }
php
{ "resource": "" }
q241103
ORM.all
train
public static function all() { $class = get_called_class(); $object = new $class(); $table = $object->_table; $key = $object->_keyName; // $data = Query::table($table)->select('*')->where("'true'", '=', 'true'); // if ($object->_canKept) { $data = $data->orGroup( 'and', Query::condition('deleted_at', '>', Time::current()), Query::condition('deleted_at', 'is', 'NULL', false)); } if ($object->_canStashed) { $data = $data->orGroup( 'and', Query::condition('appeared_at', '<=', Time::current()), Query::condition('appeared_at', 'is', 'NULL', false)); } // $data = $data->get(Query::GET_ARRAY); // return self::collect($data, $table, $key); }
php
{ "resource": "" }
q241104
ORM.onlyTrash
train
public static function onlyTrash() { $class = get_called_class(); $object = new $class(); $table = $object->_table; $key = $object->_keyName; // $data = Query::table($table)->select('*'); // if ($object->_canKept) { $data = $data->where('deleted_at', '<=', Time::current()); } // $data = $data->get(Query::GET_ARRAY); // return self::collect($data, $table, $key); }
php
{ "resource": "" }
q241105
ORM.where
train
public static function where($column, $relation, $value) { $self = self::instance(); $key = $self->_keyName; $data = \Query::from($self->_table)->select($key)->where($column, $relation, $value)->get(); $rows = []; if (!is_null($data)) { foreach ($data as $item) { $rows[] = self::instance($item->$key); } } return $rows; }
php
{ "resource": "" }
q241106
View.forge
train
public static function forge($file = null, $data = null, $auto_encode = null) { $class = null; if ($file !== null) { $extension = pathinfo($file, PATHINFO_EXTENSION); $class = \Config::get('parser.extensions.'.$extension, null); } if ($class === null) { $class = get_called_class(); } // Only get rid of the extension if it is not an absolute file path if ($file !== null and $file[0] !== '/' and $file[1] !== ':') { $file = $extension ? preg_replace('/\.'.preg_quote($extension).'$/i', '', $file) : $file; } // Class can be an array config if (is_array($class)) { $class['extension'] and $extension = $class['extension']; $class = $class['class']; } // Include necessary files foreach ((array) \Config::get('parser.'.$class.'.include', array()) as $include) { if ( ! array_key_exists($include, static::$loaded_files)) { require $include; static::$loaded_files[$include] = true; } } // Instantiate the Parser class without auto-loading the view file if ($auto_encode === null) { $auto_encode = \Config::get('parser.'.$class.'.auto_encode', null); } $view = new $class(null, $data, $auto_encode); if ($file !== null) { // Set extension when given $extension and $view->extension = $extension; // Load the view file $view->set_filename($file); } return $view; }
php
{ "resource": "" }
q241107
Smarty.setTemplateExtension
train
public function setTemplateExtension($extension) { $extension = (string) $extension; $extension = trim($extension); if ('.' == $extension[0]) { $extension = substr($extension, 1); } $this->extension = $extension; }
php
{ "resource": "" }
q241108
Smarty.setLayoutVariableName
train
public function setLayoutVariableName($name) { $name = (string) $name; $name = trim($name); if (! preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/', $name)) { throw new InvalidArgumentException('Invalid variable name'); } $this->layoutVariableName = $name; }
php
{ "resource": "" }
q241109
NestedSet.hasChildren
train
public function hasChildren(): bool { $children = (($this->getRgt() - $this->getLft()) - 1) / 2; return (0 === $children) ? false : true; }
php
{ "resource": "" }
q241110
Generator.generateSearchRules
train
public function generateSearchRules() { if (($table = $this->getTableSchema()) === false) { return ["[['" . implode("', '", $this->getColumnNames()) . "'], 'safe']"]; } $types = []; foreach ($table->columns as $column) { switch ($column->type) { case Schema::TYPE_SMALLINT: case Schema::TYPE_INTEGER: case Schema::TYPE_BIGINT: $types['integer'][] = $column->name; break; case Schema::TYPE_BOOLEAN: $types['boolean'][] = $column->name; break; case Schema::TYPE_FLOAT: case Schema::TYPE_DECIMAL: case Schema::TYPE_MONEY: //$types['number'][] = $column->name; //break; case Schema::TYPE_DATE: case Schema::TYPE_TIME: case Schema::TYPE_DATETIME: case Schema::TYPE_TIMESTAMP: default: $types['safe'][] = $column->name; break; } } $rules = []; foreach ($types as $type => $columns) { $sf = ""; if ($type == "safe") { $tabs = $this->generateRelations(); foreach ($tabs as $tab) { if ($tab) { $sf .= ($sf == ""?"/*, '":", '").$tab."Id'"; } } $sf .= ($sf == ""?"":"*/"); } $rules[] = "[['" . implode("', '", $columns) . "'".$sf."], '$type']"; } return $rules; }
php
{ "resource": "" }
q241111
Observer.instance
train
public static function instance($model_class) { $observer = get_called_class(); if (empty(static::$_instances[$observer][$model_class])) { static::$_instances[$observer][$model_class] = new static($model_class); } return static::$_instances[$observer][$model_class]; }
php
{ "resource": "" }
q241112
Compiler.compiledExists
train
public function compiledExists() { return $this->cached === false ? false : file_exists($this->cachePath.'/'.$this->getClassName().'.php'); }
php
{ "resource": "" }
q241113
Compiler.compile
train
public function compile() { if($this->compiledExists() === false) { if(is_file($this->filepath) === false) { throw new \Exception('File "'.$this->filepath.'" does not exists.'); } $this->raw = file_get_contents($this->filepath); if($this->options['add-source-line-numbers']) $this->prepared = $this->addLinesNumbers($this->raw); else $this->prepared = $this->raw; $this->removeComments(); $this->resolveExtending(); $this->compileRenders(); $this->compileEchoes(); $this->compileConditions(); $this->compileLoops(); $this->compileSpecialStatements(); $this->prepareSections(); $this->findSections(); $this->replaceSections(); } }
php
{ "resource": "" }
q241114
Compiler.resolveExtending
train
public function resolveExtending() { /** * Extending of view. */ preg_match_all('/@extends\(\'([a-zA-Z0-9\.\-]+)\'\)/', $this->prepared, $matches); if(isset($matches[1][0])) { $this->extends = trim($matches[1][0]); $this->prepared = trim(str_replace($matches[0][0], '', $this->prepared)); } /** * Tag means that this view should not be extending. */ preg_match_all('/@no-extends/', $this->prepared, $matches); if(isset($matches[0][0]) && count($matches[0][0]) == 1) { $this->extends = false; $this->prepared = trim(str_replace($matches[0][0], '', $this->prepared)); } }
php
{ "resource": "" }
q241115
Compiler.compileSpecialStatements
train
public function compileSpecialStatements() { /** * Statemet that sets the variable value. */ preg_match_all('/@set\s?(.*)/', $this->prepared, $matches); foreach($matches[0] as $key => $val) { $exploded = explode(' ', $matches[1][$key]); $varName = substr(trim(array_shift($exploded)), 1); $value = trim(ltrim(trim(implode(' ', $exploded)), '=')); $this->prepared = str_replace($matches[0][$key], "<?php $$varName = $value; \$this->appendData(['$varName' => $$varName]); ?>", $this->prepared); } /** * @todo Make possible to definie owv statements and parsing it. */ /*foreach($this->specialStatements as $statement => $callback) { preg_match_all('/@'.$statement.'\s?(.*)/', $this->prepared, $matches); call_user_func_array($callback, [$this, $matches]); }*/ }
php
{ "resource": "" }
q241116
Compiler.createFiltersMethods
train
public function createFiltersMethods(array $names, $variable) { if($names === array()) { return $variable; } $filter = array_shift($names); if($filter === 'raw') { $result = $this->createFiltersMethods($names, $variable); } else { $begin = ''; $end = ''; if(function_exists($filter)) { $begin = "{$filter}("; } else { $begin = "\$env->filter('{$filter}', "; } $result = $begin.$this->createFiltersMethods($names, $variable).')'; } return $result; }
php
{ "resource": "" }
q241117
Native.get
train
public function get($key) { $session = $this->getSessionData(); return $this->has($key) ? $session[$key] : null; }
php
{ "resource": "" }
q241118
Native.getSessionData
train
protected function getSessionData() { $data = isset($_SESSION[$this->config['key']]) ? $_SESSION[$this->config['key']] : []; return array_merge($data, $this->flash); }
php
{ "resource": "" }
q241119
TrackingParameterAppender.append
train
public function append($url, $formatterName = null) { $urlComponents = parse_url($url); $parameters = array(); if (isset($urlComponents['query'])) { parse_str($urlComponents['query'], $parameters); } $trackingParameters = $this->persister->getAllTrackingParameters(); if (null !== $formatterName) { $foundFormatter = $this->findFormatterByName($formatterName); if (null === $foundFormatter) { throw new InvalidConfigurationException(sprintf('Unknown formatter "%s".', $formatterName)); } $parameters = array_merge( $parameters, $this->formatters[$foundFormatter]->format($trackingParameters) ); $parameters = $this->formatters[$foundFormatter]->checkFormat($parameters); } /** Search for tracking parameters to replace in query's parameters. */ foreach ($parameters as $parameterName => $parameterValue) { if (!is_array($parameterValue) && preg_match('`^{\s?(?<parameter>[a-z0-9_]+)\s?}$`i', $parameterValue, $matches)) { $parameters[$parameterName] = $trackingParameters->get($matches['parameter'], null); } } /** Rebuild the query parameters string. */ $urlComponents['query'] = http_build_query($parameters, null, '&', PHP_QUERY_RFC3986); if (true === empty($urlComponents['query'])) { /* Force to null to avoid single "?" at the end of url */ $urlComponents['query'] = null; } return $this->buildUrl($urlComponents); }
php
{ "resource": "" }
q241120
CallQueue.execute
train
public function execute($objectContext) { if (!$this->ok) return; foreach ($this->entries as $entry) { if (!$this->ok) return; $entry->execute($objectContext); } }
php
{ "resource": "" }
q241121
Library.classMethod
train
protected function classMethod(&$class = NULL, &$method = NULL, $command) { $commandEx = explode(':', $command); $class = $commandEx[0]; $method = $commandEx[1] ?? NULL; }
php
{ "resource": "" }
q241122
FileConfigurationLoader.checkConfiguration
train
public final function checkConfiguration($deep = false) { if (!file_exists($this->filename) || !is_readable($this->filename)) { throw new ConfigurationNotFoundException("File $this->filename does not exist or is not readable"); } $fileExtension = pathinfo($this->filename, PATHINFO_EXTENSION); if (in_array($fileExtension, static::$supportedFileTypes)) { return true; } if (!$deep) { return false; } try { $this->parseAndCacheConfiguration(); return true; } catch (ParseException $e) { return false; } }
php
{ "resource": "" }
q241123
RedirectResponse.setTarget
train
public function setTarget($target) { if (!is_string($target) || $target == '') { throw new \InvalidArgumentException('No valid URL given.'); } $this->target = $target; // Set meta refresh content if header location is ignored $this->setContent( sprintf('<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <meta http-equiv="refresh" content="0; url=%1$s" /> </head> <body> <p>Redirecting to <a href="%1$s">%1$s</a>. </body> </html>', htmlspecialchars($target, ENT_QUOTES, 'UTF-8'))); // Set header location $this->setHeader('Location', $target); return $this; }
php
{ "resource": "" }
q241124
Editor.editFile
train
public function editFile(ProcessBuilder $processBuilder, $filePath) { $proc = $processBuilder->setPrefix($this->_editorCommand)->setArguments([$filePath])->getProcess(); $proc->setTty(true)->run(); return $proc; }
php
{ "resource": "" }
q241125
Editor.editData
train
public function editData(ProcessBuilder $processBuilder, $data) { $filePath = tempnam(sys_get_temp_dir(), 'sensibleEditor'); file_put_contents($filePath, $data); $proc = $this->editFile($processBuilder, $filePath); if ($proc->isSuccessful()) { $data = file_get_contents($filePath); } unlink($filePath); return $data; }
php
{ "resource": "" }
q241126
BaseAbstract.execute
train
public function execute() { $repositoryResponse = []; $arrayOfObjects = []; $resultCount = 0; $responseStatus = ResponseAbstract::STATUS_SUCCESS; try { $this->executeDataGateway(); if ($this->repository != null) { $arrayOfObjects = $this->repository->getEntitiesFromResponse(); $repositoryResponse = $this->repository->getResponse(); $responseStatus = $this->repository->isResponseStatusSuccess() == true ? ResponseAbstract::STATUS_SUCCESS : ResponseAbstract::STATUS_FAIL; } else { $arrayOfObjects = []; $repositoryResponse = []; } $resultCount = $this->getTotalResultCount(); } catch (\Exception $e) { $responseStatus = ResponseAbstract::STATUS_FAIL; $this->response->setMessages(['No result was found']); } $this->response->setStatus($responseStatus); $this->response->setResult($arrayOfObjects); $this->response->setSourceResponse($repositoryResponse); $this->response->setTotalResultCount($resultCount); }
php
{ "resource": "" }
q241127
ContentPackageDefinition.module
train
public function module(string $name, string $icon, callable $definitionCallback) { $definition = new ContentModuleDefinition($name, $icon, $this->config); $definitionCallback($definition); $this->customModules([ $name => function () use ($definition) { return $definition->loadModule( $this->iocContainer->get(IContentGroupRepository::class), $this->iocContainer->get(IAuthSystem::class), $this->iocContainer->get(IClock::class) ); }, ]); }
php
{ "resource": "" }
q241128
Num.value
train
public static function value($str, $round = false) { if (is_string($str)) { $str = strtr($str, '.', ''); $str = strtr($str, ',', '.'); } $val = floatval($str); if ($round !== false) { $val = round($val, intval($round)); } return $val; }
php
{ "resource": "" }
q241129
SimpleXMLNodeTypedAttributeGetter.getValue
train
public function getValue() { $type = (string) $this->element->attributes()->type; $type = (empty($type)) ? 'string' : $type; $value = (string) $this->element->attributes()->value; $casterClassName = $this->resolveCasterClassName($type); /** @type \BuildR\TestTools\Caster\CasterInterface $casterObject */ $casterObject = new $casterClassName($value); return $casterObject->cast(); }
php
{ "resource": "" }
q241130
SimpleXMLNodeTypedAttributeGetter.resolveCasterClassName
train
private function resolveCasterClassName($type) { foreach($this->casters as $typeNames => $casterClass) { $names = explode('|', $typeNames); if(!in_array($type, $names)) { continue; } return $casterClass; } throw CasterException::unresolvableType($type); }
php
{ "resource": "" }
q241131
Form.addFormDeclaration
train
private function addFormDeclaration($formTypeName) { $name = strtolower($this->model); $extension = $matches = preg_split('/(?=[A-Z])/', $this->bundle->getName(), -1, PREG_SPLIT_NO_EMPTY); $bundleName = $this->getBundlePrefix(); array_pop($extension); $path = $this->bundle->getPath() . '/Resources/config/forms.xml'; if (!file_exists($path)) { $this->renderFile('form/ServicesForms.xml.twig', $path, array()); $ref = 'protected $configFiles = array('; $this->dumpFile( $this->bundle->getPath() . '/DependencyInjection/' . implode('', $extension) . 'Extension.php', "\n 'forms',", $ref );die; } $this->addService($path, $bundleName, $name, $formTypeName); $this->addParameter($path, $bundleName, $name); }
php
{ "resource": "" }
q241132
Form.addService
train
private function addService($path, $bundleName, $name, $formTypeName) { $ref = '<services>'; $replaceBefore = true; $group = $bundleName . '_' . $name; $declaration = <<<EOF <service id="$bundleName.form.type.$name" class="%$bundleName.form.type.$name.class%"> <argument>%$bundleName.model.$name.class%</argument> <argument type="collection"> <argument>$group</argument> </argument> <tag name="form.type" alias="$formTypeName" /> </service> EOF; if ($this->refExist($path, $declaration)) { return; } if (!$this->refExist($path, $ref)) { $ref = '</container>'; $replaceBefore = false; $declaration = <<<EOF <services> $declaration </services> EOF; } $this->dumpFile($path, "\n" . $declaration . "\n", $ref, $replaceBefore); }
php
{ "resource": "" }
q241133
Form.addParameter
train
private function addParameter($path, $bundleName, $name) { $formPath = $this->configuration['namespace'] . '\\' . $this->model . 'Type'; $ref = '<parameters>'; $replaceBefore = true; $declaration = <<<EOF <parameter key="$bundleName.form.type.$name.class">$formPath</parameter> EOF; if ($this->refExist($path, $declaration)) { return; } if (!$this->refExist($path, $ref)) { $ref = ' <services>'; $replaceBefore = false; $declaration = <<<EOF <parameters> $declaration </parameters> EOF; } $this->dumpFile($path, "\n" . $declaration, $ref, $replaceBefore); }
php
{ "resource": "" }
q241134
CommentWalker.start_lvl
train
public function start_lvl(&$output, $depth = 0, $args = []) { $GLOBALS['comment_depth'] = $depth + 1; switch ($args['style']) { case 'div': break; case 'ol': $output .= '<ol class="children list-unstyled">'.PHP_EOL; break; case 'ul': default: $output .= '<ul class="children list-unstyled">'.PHP_EOL; break; } }
php
{ "resource": "" }
q241135
CommentWalker.end_lvl
train
public function end_lvl(&$output, $depth = 0, $args = []) { $tab = ' '; $indent = ($depth == 1) ? 8 + $depth : 7 + ($depth * 2); switch ($args['style']) { case 'div': break; case 'ol': case 'ul': default: $output .= str_repeat($tab, $indent); break; } parent::end_lvl($output, $depth, $args); }
php
{ "resource": "" }
q241136
Generator.next
train
public function next() { $operation = $this->operation; $this->value = $operation($this->value); $this->elementsGenerated++; }
php
{ "resource": "" }
q241137
Exception.create
train
public static function create($message, $messageVariables = null, $code = null, PhpException $previous = null) { $messageFormat = [ 'message' => $message, 'messageVariables' => $messageVariables ]; return new static($messageFormat, $code, $previous); }
php
{ "resource": "" }
q241138
Exception.setCode
train
public function setCode($code) { if (!is_scalar($code)) { throw new InvalidArgumentException( sprintf( 'Wrong parameters for %s([int|string $code]); %s given.', __METHOD__, is_object($code) ? get_class($code) : gettype($code) ), E_ERROR ); } $this->code = $code; return $this; }
php
{ "resource": "" }
q241139
Exception.setMessage
train
public function setMessage($message) { $messageVariables = null; if (is_array($message)) { if (array_key_exists('messageVariables', $message)) { $messageVariables = $message['messageVariables']; } if (array_key_exists('message', $message)) { $message = $message['message']; } else { $messageVariables = $message; $message = $this->messageTemplate; } } if (!is_string($message)) { throw new InvalidArgumentException( sprintf( 'Wrong parameters for %s([array|string $message]); %s given.', __METHOD__, is_object($message) ? get_class($message) : gettype($message) ), E_ERROR ); } $this->message = $this->createMessage($message, $messageVariables); return $this; }
php
{ "resource": "" }
q241140
Exception.createMessage
train
protected function createMessage($message, $variables = null) { if (null !== $variables && is_array($variables)) { $variables = array_merge($this->getMessageVariables(), $variables); } else { $variables = $this->getMessageVariables(); } foreach ($variables as $variableKey => $variable) { if (is_array($variable) || ($variable instanceof Traversable)) { $variable = implode(', ', array_values($variable)); } if (!is_scalar($variable)) { $variable = $this->switchType($variable); } $message = str_replace("%$variableKey%", (string) $variable, $message); } return $message; }
php
{ "resource": "" }
q241141
Exception.getCauseMessage
train
public function getCauseMessage() { $causes = []; $current = [ 'class' => get_class($this), 'message' => $this->getMessage(), 'code' => $this->getCode(), 'file' => $this->getFile(), 'line' => $this->getLine() ]; $causes[] = $current; $previous = $this->getPrevious(); while ($previous !== null) { if ($previous instanceof Exception) { $prevCauses = $previous->getCauseMessage(); foreach ($prevCauses as $cause) { $causes[] = $cause; } } elseif ($previous instanceof PhpException) { $causes[] = [ 'class' => get_class($previous), 'message' => $previous->getMessage(), 'code' => $previous->getCode(), 'file' => $previous->getFile(), 'line' => $previous->getLine() ]; } $previous = $previous->getPrevious(); } return $causes; }
php
{ "resource": "" }
q241142
Exception.getTraceSaveAsString
train
public function getTraceSaveAsString() { $traces = $this->getTrace(); $messages = ['STACK TRACE DETAILS : ']; foreach ($traces as $index => $trace) { $message = sprintf('#%d ', $index + 1); /** @noinspection UnSafeIsSetOverArrayInspection */ if (isset($trace['file'])) { if (!is_string($trace['file'])) { $message .= '[Unknown Function]: '; } else { $line = 0; /** @noinspection UnSafeIsSetOverArrayInspection */ if (isset($trace['line']) && is_int($trace['line'])) { $line = $trace['line']; } $message .= sprintf('%s(%d): ', $trace['file'], $line); } } else { $message .= '[Internal Function]: '; } /** @noinspection UnSafeIsSetOverArrayInspection */ if (isset($trace['class']) && is_string($trace['class'])) { $message .= $trace['class'] . ' '; } /** @noinspection UnSafeIsSetOverArrayInspection */ if (isset($trace['type']) && is_string($trace['type'])) { $message .= $trace['type'] . ' '; } /** @noinspection UnSafeIsSetOverArrayInspection */ if (isset($trace['function']) && is_string($trace['function'])) { $message .= $trace['function'] . '('; /** @noinspection UnSafeIsSetOverArrayInspection */ if (isset($trace['args']) && count($trace['args']) > 0) { /** @var array $arguments */ $arguments = $trace['args']; $argVariables = []; foreach ($arguments as $argument) { $argVariables[] = $this->switchType($argument); } $message .= implode(', ', $argVariables); } $message .= ')'; } $messages[] = trim($message); } return implode("\n", $messages); }
php
{ "resource": "" }
q241143
Exception.switchType
train
protected function switchType($argument) { $stringType = null; $type = strtolower(gettype($argument)); switch ($type) { case 'boolean': $stringType = sprintf( '[%s "%s"]', ucwords($type), ((int) $argument === 1) ? 'True' : 'False' ); break; case 'integer': case 'double': case 'float': case 'string': $stringType = sprintf('[%s "%s"]', ucwords($type), $argument); break; case 'array': $stringType = sprintf( '[%s {value: %s}]', ucwords($type), var_export($argument, true) ); break; case 'object': $stringType = sprintf('[%s "%s"]', ucwords($type), get_class($argument)); break; case 'resource': $stringType = sprintf('[%s]', ucwords($type)); break; case 'null': $stringType = '[NULL]'; break; default; $stringType = '[Unknown Type]'; break; } return $stringType; }
php
{ "resource": "" }
q241144
MysqlDriver.initialize
train
public function initialize() { $this->setDialect(new MysqlDialect($this)); $flags = $this->getConfig('flags'); if ($timezone = $this->getConfig('timezone')) { if ($timezone === 'UTC') { $timezone = '+00:00'; } $flags[PDO::MYSQL_ATTR_INIT_COMMAND] = sprintf('SET time_zone = "%s";', $timezone); } $this->setConfig('flags', $flags); }
php
{ "resource": "" }
q241145
ProductController.listJsonAction
train
public function listJsonAction() { $em = $this->getDoctrine()->getManager(); $adminManager = $this->get('admin_manager'); /** @var \AdminBundle\Services\DataTables\JsonList $jsonList */ $jsonList = $this->get('json_list'); $jsonList->setRepository($em->getRepository('EcommerceBundle:Product')); $user = $this->container->get('security.token_storage')->getToken()->getUser(); if ($user->isGranted('ROLE_USER')) { $jsonList->setActor($user); } $response = $jsonList->get(); return new JsonResponse($response); }
php
{ "resource": "" }
q241146
ProductController.statsAction
train
public function statsAction($id, $from, $to) { $em = $this->getDoctrine()->getManager(); /** @var Actor $entity */ $entity = $em->getRepository('EcommerceBundle:Product')->find($id); /** @var FrontManager $frontManager */ $adminManager = $this->container->get('admin_manager'); $stats = $adminManager->getProductStats($entity, $from, $to); $label = array(); $visits = array(); foreach ($stats as $stat) { $label[] = $stat['day']; $visits[] = $stat['visits']; } $returnValues = new \stdClass(); $returnValues->count = count($stats); $returnValues->labels = implode(',', $label); $returnValues->visits = implode(',', $visits); return new JsonResponse($returnValues); }
php
{ "resource": "" }
q241147
ProductController.editAction
train
public function editAction(Request $request, Product $product) { //access control $user = $this->container->get('security.token_storage')->getToken()->getUser(); if ($user->isGranted('ROLE_USER') && $product->getActor()->getId() != $user->getId()) { return $this->redirect($this->generateUrl('ecommerce_product_index')); } $formConfig = array(); if ($user->isGranted('ROLE_USER')) { $formConfig['actor'] = $user; } $deleteForm = $this->createDeleteForm($product); $editForm = $this->createForm('EcommerceBundle\Form\ProductType', $product, $formConfig); $attributesForm = $this->createForm('EcommerceBundle\Form\ProductAttributesType', $product, array('category' => $product->getCategory()->getId())); $featuresForm = $this->createForm('EcommerceBundle\Form\ProductFeaturesType', $product, array('category' => $product->getCategory()->getId())); $relatedProductsForm = $this->createForm('EcommerceBundle\Form\ProductRelatedType', $product); if($request->getMethod('POST')){ $redirectParams = array('id' => $product->getId()); if ($request->request->has('product_attributes')) { // attributes were submitted $editForm = $attributesForm; $redirectParams = array_merge($redirectParams, array('attributes' => 1)); } else if ($request->request->has('product_features')) { // features were submitted $editForm = $featuresForm; $redirectParams = array_merge($redirectParams, array('features' => 1)); } else if ($request->request->has('product_related')) { // related products were submitted $editForm = $relatedProductsForm; $redirectParams = array_merge($redirectParams, array('related' => 1)); } $editForm->handleRequest($request); if ($editForm->isSubmitted() && $editForm->isValid()) { $em = $this->getDoctrine()->getManager(); $em->persist($product); $em->flush(); $this->get('session')->getFlashBag()->add('success', 'product.edited'); return $this->redirectToRoute('ecommerce_product_show', $redirectParams); } } return array( 'entity' => $product, 'edit_form' => $editForm->createView(), 'attributes_form' => $attributesForm->createView(), 'features_form' => $featuresForm->createView(), 'related_form' => $relatedProductsForm->createView(), 'delete_form' => $deleteForm->createView(), ); }
php
{ "resource": "" }
q241148
ProductController.createDeleteForm
train
private function createDeleteForm(Product $product) { return $this->createFormBuilder() ->setAction($this->generateUrl('ecommerce_product_delete', array('id' => $product->getId()))) ->setMethod('DELETE') ->getForm() ; }
php
{ "resource": "" }
q241149
ProductController.updateImage
train
public function updateImage(Request $request) { $fileName = $request->query->get('file'); $type = $request->query->get('type'); $value = $request->query->get('value'); /** @var Image $entity */ $qb = $this->getDoctrine()->getManager()->getRepository('CoreBundle:Image') ->createQueryBuilder('i'); $image = $qb->where($qb->expr()->like('i.path', ':path')) ->setParameter('path','%'.$fileName.'%') ->getQuery() ->getOneOrNullResult(); // $image = $this->getDoctrine()->getManager()->getRepository('CoreBundle:Image')->findOneBy(array('path' => $fileName)); if (!$image) { throw new NotFoundHttpException('Unable to find Image entity.'); } if($type == 'title') $image->setTitle($value); if($type == 'alt') $image->setAlt($value); $this->getDoctrine()->getManager()->flush(); return new JsonResponse(array('success' => true)); }
php
{ "resource": "" }
q241150
VanillaStatsPlugin.Gdn_Dispatcher_BeforeDispatch_Handler
train
public function Gdn_Dispatcher_BeforeDispatch_Handler($Sender) { $Enabled = C('Garden.Analytics.Enabled', TRUE); if ($Enabled && !Gdn::PluginManager()->HasNewMethod('SettingsController', 'Index')) { Gdn::PluginManager()->RegisterNewMethod('VanillaStatsPlugin', 'StatsDashboard', 'SettingsController', 'Index'); } }
php
{ "resource": "" }
q241151
VanillaStatsPlugin.StatsDashboard
train
public function StatsDashboard($Sender) { $StatsUrl = $this->AnalyticsServer; if (!StringBeginsWith($StatsUrl, 'http:') && !StringBeginsWith($StatsUrl, 'https:')) $StatsUrl = Gdn::Request()->Scheme()."://{$StatsUrl}"; // Tell the page where to find the Vanilla Analytics provider $Sender->AddDefinition('VanillaStatsUrl', $StatsUrl); $Sender->SetData('VanillaStatsUrl', $StatsUrl); // Load javascript & css, check permissions, and load side menu for this page. $Sender->AddJsFile('settings.js'); $Sender->Title(T('Dashboard')); $Sender->RequiredAdminPermissions[] = 'Garden.Settings.Manage'; $Sender->RequiredAdminPermissions[] = 'Garden.Users.Add'; $Sender->RequiredAdminPermissions[] = 'Garden.Users.Edit'; $Sender->RequiredAdminPermissions[] = 'Garden.Users.Delete'; $Sender->RequiredAdminPermissions[] = 'Garden.Users.Approve'; $Sender->FireEvent('DefineAdminPermissions'); $Sender->Permission($Sender->RequiredAdminPermissions, '', FALSE); $Sender->AddSideMenu('dashboard/settings'); if (!Gdn_Statistics::CheckIsEnabled() && Gdn_Statistics::CheckIsLocalhost()) { $Sender->Render('dashboardlocalhost', '', 'plugins/VanillaStats'); } else { $Sender->AddJsFile('plugins/VanillaStats/js/vanillastats.js'); $Sender->AddJsFile('plugins/VanillaStats/js/picker.js'); $Sender->AddCSSFile('plugins/VanillaStats/design/picker.css'); $this->ConfigureRange($Sender); $VanillaID = Gdn::InstallationID(); $Sender->SetData('VanillaID', $VanillaID); $Sender->SetData('VanillaVersion', APPLICATION_VERSION); $Sender->SetData('SecurityToken', $this->SecurityToken()); // Render the custom dashboard view $Sender->Render('dashboard', '', 'plugins/VanillaStats'); } }
php
{ "resource": "" }
q241152
VanillaStatsPlugin.SettingsController_DashboardSummaries_Create
train
public function SettingsController_DashboardSummaries_Create($Sender) { // Load javascript & css, check permissions, and load side menu for this page. $Sender->AddJsFile('settings.js'); $Sender->Title(T('Dashboard Summaries')); $Sender->RequiredAdminPermissions[] = 'Garden.Settings.Manage'; $Sender->RequiredAdminPermissions[] = 'Garden.Users.Add'; $Sender->RequiredAdminPermissions[] = 'Garden.Users.Edit'; $Sender->RequiredAdminPermissions[] = 'Garden.Users.Delete'; $Sender->RequiredAdminPermissions[] = 'Garden.Users.Approve'; $Sender->FireEvent('DefineAdminPermissions'); $Sender->Permission($Sender->RequiredAdminPermissions, '', FALSE); $Sender->AddSideMenu('dashboard/settings'); $this->ConfigureRange($Sender); // Load the most active discussions during this date range $UserModel = new UserModel(); $Sender->SetData('DiscussionData', $UserModel->SQL ->Select('d.DiscussionID, d.Name, d.CountBookmarks, d.CountViews, d.CountComments') ->From('Discussion d') ->Where('d.DateLastComment >=', $Sender->DateStart) ->Where('d.DateLastComment <=', $Sender->DateEnd) ->OrderBy('d.CountViews', 'desc') ->OrderBy('d.CountComments', 'desc') ->OrderBy('d.CountBookmarks', 'desc') ->Limit(10, 0) ->Get() ); // Load the most active users during this date range $Sender->SetData('UserData', $UserModel->SQL ->Select('u.UserID, u.Name') ->Select('c.CommentID', 'count', 'CountComments') ->From('User u') ->Join('Comment c', 'u.UserID = c.InsertUserID', 'inner') ->GroupBy('u.UserID, u.Name') ->Where('c.DateInserted >=', $Sender->DateStart) ->Where('c.DateInserted <=', $Sender->DateEnd) ->OrderBy('CountComments', 'desc') ->Limit(10, 0) ->Get() ); // Render the custom dashboard view $Sender->Render('dashboardsummaries', '', 'plugins/VanillaStats'); }
php
{ "resource": "" }
q241153
Software.get
train
public function get() { $keys = $this->registry ->setRoot(Registry::HKEY_LOCAL_MACHINE) ->setPath($this->path) ->get(); $software = []; foreach ($keys as $key) { // Set a new temporary path for the software key $path = $this->path.$key; // Retrieve the name of the software $name = $this->registry->setPath($path)->getValue('DisplayName'); // If the name exists, we'll retrieve the rest of the software information if ($name) { $software[] = new Application([ 'name' => $name, 'version' => $this->registry->getValue('DisplayVersion'), 'publisher' => $this->registry->getValue('Publisher'), 'install_date' => $this->registry->getValue('InstallDate'), ]); } } return $software; }
php
{ "resource": "" }
q241154
AbstractDbMapper.getResultSet
train
protected function getResultSet() { if (!$this->resultSetPrototype instanceof HydratingResultSet) { $resultSetPrototype = new HydratingResultSet; $resultSetPrototype->setHydrator($this->getHydrator()); $resultSetPrototype->setObjectPrototype($this->getModel()); $this->resultSetPrototype = $resultSetPrototype; } return clone $this->resultSetPrototype; }
php
{ "resource": "" }
q241155
AbstractDbMapper.getById
train
public function getById($id, $col = null) { $col = ($col) ?: $this->getPrimaryKey(); $select = $this->getSelect()->where([$col => $id]); $resultSet = $this->fetchResult($select); if ($resultSet->count() > 1) { $rowSet = []; foreach ($resultSet as $row) { $rowSet[] = $row; } } elseif ($resultSet->count() === 1) { $rowSet = $resultSet->current(); } else { $rowSet = $this->getModel(); } return $rowSet; }
php
{ "resource": "" }
q241156
AbstractDbMapper.fetchAll
train
public function fetchAll($sort = null) { $select = $this->getSelect(); $select = $this->setSortOrder($select, $sort); $resultSet = $this->fetchResult($select); return $resultSet; }
php
{ "resource": "" }
q241157
AbstractDbMapper.search
train
public function search(array $search, $sort, $select = null) { $select = ($select) ?: $this->getSelect(); foreach ($search as $key => $value) { if (!$value['searchString'] == '') { if (substr($value['searchString'], 0, 1) == '=' && $key == 0) { $id = (int)substr($value['searchString'], 1); $select->where->equalTo($this->getPrimaryKey(), $id); } else { $where = $select->where->nest(); $c = 0; foreach ($value['columns'] as $column) { if ($c > 0) $where->or; $where->like($column, '%' . $value['searchString'] . '%'); $c++; } $where->unnest(); } } } $select = $this->setSortOrder($select, $sort); return $this->fetchResult($select); }
php
{ "resource": "" }
q241158
AbstractDbMapper.insert
train
public function insert(array $data, $table = null) { $table = ($table) ?: $this->getTable(); $sql = $this->getSql(); $insert = $sql->insert($table); $insert->values($data); $statement = $sql->prepareStatementForSqlObject($insert); $result = $statement->execute(); return $result->getGeneratedValue(); }
php
{ "resource": "" }
q241159
AbstractDbMapper.paginate
train
public function paginate($select, $resultSet = null) { $resultSet = $resultSet ?: $this->getResultSet(); $adapter = new DbSelect($select, $this->getAdapter(), $resultSet); $paginator = new Paginator($adapter); $options = $this->getPaginatorOptions(); if (isset($options['limit'])) { $paginator->setItemCountPerPage($options['limit']); } if (isset($options['page'])) { $paginator->setCurrentPageNumber($options['page']); } $paginator->setPageRange(5); return $paginator; }
php
{ "resource": "" }
q241160
AbstractDbMapper.fetchResult
train
protected function fetchResult(Select $select, AbstractResultSet $resultSet = null) { $resultSet = $resultSet ?: $this->getResultSet(); $resultSet->buffer(); if ($this->usePaginator()) { $this->setUsePaginator(false); $resultSet = $this->paginate($select, $resultSet); } else { $statement = $this->getSql()->prepareStatementForSqlObject($select); $result = $statement->execute(); $resultSet->initialize($result); } return $resultSet; }
php
{ "resource": "" }
q241161
AbstractDbMapper.setSortOrder
train
public function setSortOrder(Select $select, $sort) { if ($sort === '' || null === $sort || empty($sort)) { return $select; } $select->reset('order'); if (is_string($sort)) { $sort = explode(' ', $sort); } $order = []; foreach ($sort as $column) { if (strchr($column, '-')) { $column = substr($column, 1, strlen($column)); $direction = Select::ORDER_DESCENDING; } else { $direction = Select::ORDER_ASCENDING; } // COLLATE NOCASE // fix the sort order to make case insensitive for sqlite database. if ('sqlite' == $this->getAdapter()->getPlatform()->getName()) { $direction = 'COLLATE NOCASE ' . $direction; } $order[] = $column . ' ' . $direction; } return $select->order($order); }
php
{ "resource": "" }
q241162
Application.run
train
public static function run($root = '../', $routes = true, $session = true) { self::setScreen(); self::setRoot($root); // self::setCaseVars(false, false); // call the connector and run it self::callBus(); // Connector::run('web',$session); Bus::run('web', $session); self::setVersion(); // set version cookie for Wappalyzer self::$version->cookie(); // self::setSHA(); // self::ini(); // self::fetcher($routes); // return true; }
php
{ "resource": "" }
q241163
Application.console
train
public static function console($root = '', $session = true) { self::setCaseVars(true, false); // self::consoleServerVars(); // self::setScreen(); self::setRoot($root); // call the connector and run it self::consoleBus(); Bus::run('lumos'); self::setVersion(); // self::ini(false); // self::fetcher(false); // return true; }
php
{ "resource": "" }
q241164
Application.ini
train
protected static function ini($database = true, $test = false) { Alias::ini(self::$root); Url::ini(); Path::ini(); Template::run(); if (Component::isOn('faker')) { Faker::ini(); } Link::ini(); Lang::ini($test); if ($database && Component::isOn('database')) { Database::ini(); Schema::ini(); } Auth::ini(); Plugins::ini(); }
php
{ "resource": "" }
q241165
Application.vendor
train
public static function vendor() { self::checkVendor(); $path = is_null(self::$root) ? 'vendor/autoload.php' : self::$root.'vendor/autoload.php'; include_once $path; }
php
{ "resource": "" }
q241166
Routes.setRoutes
train
private function setRoutes(array $routes) { $this->routes = []; foreach ($routes as $name => $route) { $this->add($name, $route); } }
php
{ "resource": "" }
q241167
RepositoryManager.registerRepository
train
public function registerRepository(ManagedRepositoryInterface $repository) { $name = $repository->getName(); if($this->hasRepository($name)) { throw new \LogicException(sprintf('Repository %s is already registered.', $name)); } $event = new ManagedRepositoryEvent($repository); $this->eventDispatcher->dispatch(ManagedRepositoryEvent::REGISTER, $event); $repository = $event->getRepository(); $this->repositories[$name] = $repository; $this->classMap[$repository->getClassName()] = $name; return $repository; }
php
{ "resource": "" }
q241168
Parser.validate
train
public function validate ($object = null) { if (!isset ($this->context)) { throw new InvalidParameter ("You must set a context before validating or filtering."); } $result = $this->reduce ($this->context, $object); if ($result) { return true; } else { return false; } }
php
{ "resource": "" }
q241169
Configurator.loadEnv
train
public function loadEnv(string $path): Configurator { if (is_readable($path)) { $this->dotEnv->load($path); } return $this; }
php
{ "resource": "" }
q241170
Configurator.readConfigDir
train
public function readConfigDir(string $path): Configurator { if (!is_dir($path)) { throw new \InvalidArgumentException( sprintf("Config dir isn't a directory! %s given.", $path)); } $entitiesDir = new \DirectoryIterator($path); foreach ($entitiesDir as $fileInfo) { if (!$fileInfo->isFile() || ('php' !== $fileInfo->getExtension())) { continue; } require_once($fileInfo->getPathname()); } return $this; }
php
{ "resource": "" }
q241171
TextFormHandler.process
train
public function process(Request $request, FormInterface $form) { if ($request->isMethod('POST')) { $form->submit($request); if ($form->isValid()) { /** @var TextInterface $text */ $text = $form->getData(); foreach ($text->getTranslations() as $translation) { $translation->setText($text); } $this->textManager->add($form->getData()); return true; } } return false; }
php
{ "resource": "" }
q241172
Rules._init
train
protected function _init() { parent::_init(); $this->_rules += [ 'allowAll' => [ 'rule' => function() { return true; } ], 'denyAll' => [ 'rule' => function() { return false; } ], 'allowAnyUser' => [ 'message' => 'You must be logged in.', 'rule' => function($user) { return $user ? true : false; } ], 'allowIp' => [ 'message' => 'Your IP is not allowed to access this area.', 'rule' => function($user, $request, $options) { $options += ['ip' => false]; if (is_string($options['ip']) && strpos($options['ip'], '/') === 0) { return (boolean) preg_match($options['ip'], $request->env('REMOTE_ADDR')); } if (is_array($options['ip'])) { return in_array($request->env('REMOTE_ADDR'), $options['ip']); } return $request->env('REMOTE_ADDR') === $options['ip']; } ] ]; }
php
{ "resource": "" }
q241173
Rules.check
train
public function check($user, $request, array $options = []) { $defaults = ['rules' => $this->_defaults, 'allowAny' => $this->_allowAny]; $options += $defaults; if (empty($options['rules'])) { throw new RuntimeException("Missing `'rules'` option."); } $rules = (array) $options['rules']; $this->_error = []; $params = array_diff_key($options, $defaults); if (!isset($user) && is_callable($this->_user)) { $user = $this->_user->__invoke(); } foreach ($rules as $name => $rule) { $result = $this->_check($user, $request, $name, $rule, $params); if ($result === false && !$options['allowAny']) { return false; } if ($result === true && $options['allowAny']) { return true; } } return !$options['allowAny']; }
php
{ "resource": "" }
q241174
SNMP.realWalk
train
public function realWalk($oid, $suffixAsKey = false) { try { $return = $this->_lastResult = $this->_session->walk($oid, $suffixAsKey); } catch (Exception $exc) { $this->close(); throw new Exception("Erro '{$this->_session->getError()}' with execute WALK OID ({$oid}): " . $exc->getMessage()); } return $return; }
php
{ "resource": "" }
q241175
SNMP.realWalkToArray
train
public function realWalkToArray($oid, $suffixAsKey = false) { $arrayData = $this->realWalk($oid, $suffixAsKey); foreach ($arrayData as $_oid => $value) { $this->_lastResult[$_oid] = $this->parseSnmpValue($value); } return $this->_lastResult; }
php
{ "resource": "" }
q241176
SNMP.realWalk1d
train
public function realWalk1d($oid) { $arrayData = $this->realWalk($oid); $result = array(); foreach ($arrayData as $_oid => $value) { $oidPrefix = substr($_oid, 0, strrpos($_oid, '.')); if (!isset($result[$oidPrefix])) { $result[$oidPrefix] = Array(); } $aIndexOid = str_replace($oidPrefix . ".", "", $_oid); $result[$oidPrefix][$aIndexOid] = $this->parseSnmpValue($value); } return $result; }
php
{ "resource": "" }
q241177
SNMP.get
train
public function get($oid, $preserveKeys = false) { if ($this->cache() && ( $rtn = $this->getCache()->load($oid) ) !== null) { return $rtn; } try { $this->_lastResult = $this->_session->get($oid, $preserveKeys); } catch (Exception $exc) { $this->close(); throw new Exception("Erro '{$this->_session->getError()}' with execute GET OID ({$oid}): " . $exc->getMessage()); } if ($this->_lastResult === false) { $this->close(); throw new Exception('Could not perform walk for OID ' . $oid); } return $this->getCache()->save($oid, $this->parseSnmpValue($this->_lastResult)); }
php
{ "resource": "" }
q241178
SNMP.subOidWalk
train
public function subOidWalk($oid, $position, $elements = 1) { if ($this->cache() && ( $rtn = $this->getCache()->load($oid) ) !== null) { return $rtn; } $this->_lastResult = $this->realWalk($oid); if ($this->_lastResult === false) { $this->close(); throw new Exception('Could not perform walk for OID ' . $oid); } $result = array(); foreach ($this->_lastResult as $_oid => $value) { $oids = explode('.', $_oid); $index = $oids[$position]; for ($pos = $position + 1; $pos < sizeof($oids) && ( $elements == -1 || $pos < $position + $elements ); $pos++) { $index .= '.' . $oids[$pos]; } $result[$index] = $this->parseSnmpValue($value); } return $this->getCache()->save($oid, $result); }
php
{ "resource": "" }
q241179
SNMP.walkIPv4
train
public function walkIPv4($oid) { if ($this->cache() && ( $rtn = $this->getCache()->load($oid) ) !== null) { return $rtn; } $this->_lastResult = $this->realWalk($oid); if ($this->_lastResult === false) { throw new Exception('Could not perform walk for OID ' . $oid); } $result = array(); foreach ($this->_lastResult as $_oid => $value) { $oids = explode('.', $_oid); $len = count($oids); $result[$oids[$len - 4] . '.' . $oids[$len - 3] . '.' . $oids[$len - 2] . '.' . $oids[$len - 1]] = $this->parseSnmpValue($value); } return $this->getCache()->save($oid, $result); }
php
{ "resource": "" }
q241180
SNMP.parseSnmpValue
train
public function parseSnmpValue($v) { // first, rule out an empty string if ($v == '""' || $v == '') { return ""; } $type = substr($v, 0, strpos($v, ':')); $value = trim(substr($v, strpos($v, ':') + 1)); switch ($type) { case 'STRING': if (substr($value, 0, 1) == '"') { $rtn = (string) trim(substr(substr($value, 1), 0, -1)); } else { $rtn = (string) $value; } break; case 'INTEGER': if (!is_numeric($value)) { // find the first digit and offset the string to that point // just in case there is some mib strangeness going on preg_match('/\d/', $value, $m, PREG_OFFSET_CAPTURE); $rtn = (int) substr($value, $m[0][1]); } else { $rtn = (int) $value; } break; case 'Counter32': $rtn = (int) $value; break; case 'Counter64': $rtn = (int) $value; break; case 'Gauge32': $rtn = (int) $value; break; case 'Hex-STRING': $rtn = (string) implode('', explode(' ', preg_replace('/[^A-Fa-f0-9]/', '', $value))); break; case 'IpAddress': $rtn = (string) $value; break; case 'OID': $rtn = (string) $value; break; case 'Timeticks': $rtn = (int) substr($value, 1, strrpos($value, ')') - 1); break; default: throw new Exception("ERR: Unhandled SNMP return type: $type\n"); } return $rtn; }
php
{ "resource": "" }
q241181
SNMP.setHost
train
public function setHost($h) { $this->_host = $h; // clear the temporary result cache and last result $this->_lastResult = null; unset($this->_resultCache); $this->_resultCache = array(); return $this; }
php
{ "resource": "" }
q241182
SNMP.getCache
train
public function getCache() { if ($this->_cache === null) { $this->_cache = new \Cityware\Snmp\Cache\Basic(); } return $this->_cache; }
php
{ "resource": "" }
q241183
SNMP.useExtension
train
public function useExtension($mib, $args) { $mib = '\\Cityware\\Snmp\\MIBS\\' . str_replace('_', '\\', $mib); $m = new $mib(); $m->setSNMP($this); return $m; }
php
{ "resource": "" }
q241184
SNMP.subOidWalkLong
train
public function subOidWalkLong($oid, $positionS, $positionE) { if ($this->cache() && ( $rtn = $this->getCache()->load($oid) ) !== null) { return $rtn; } $this->_lastResult = $this->realWalk($oid); if ($this->_lastResult === false) { throw new Exception('Could not perform walk for OID ' . $oid); } $result = array(); foreach ($this->_lastResult as $_oid => $value) { $oids = explode('.', $_oid); $oidKey = ''; for ($i = $positionS; $i <= $positionE; $i++) { $oidKey .= $oids[$i] . '.'; } $result[$oidKey] = $this->parseSnmpValue($value); } return $this->getCache()->save($oid, $result); }
php
{ "resource": "" }
q241185
Extension.addFormatter
train
protected function addFormatter(ServiceContainer $container, $name, $class) { $container->set( 'formatter.formatters.' . $name, function (ServiceContainer $c) use ($class) { $c->set('formatter.presenter', new StringPresenter($c->get('formatter.presenter.differ'))); /** @var ServiceContainer $c */ return new $class( $c->get('formatter.presenter'), $c->get('console.io'), $c->get('event_dispatcher.listeners.stats') ); } ); }
php
{ "resource": "" }
q241186
PluginList.getPluginClassNames
train
public function getPluginClassNames() { $plugins = array(); if (TRUE === $this->isEnabled('NamelessCoder\\GizzleGitPlugins\\GizzlePlugins\\ClonePlugin')) { $plugins[] = 'NamelessCoder\\GizzleGitPlugins\\GizzlePlugins\\ClonePlugin'; } if (TRUE === $this->isEnabled('NamelessCoder\\GizzleGitPlugins\\GizzlePlugins\\CheckoutPlugin')) { $plugins[] = 'NamelessCoder\\GizzleGitPlugins\\GizzlePlugins\\CheckoutPlugin'; } if (TRUE === $this->isEnabled('NamelessCoder\\GizzleGitPlugins\\GizzlePlugins\\PullPlugin')) { $plugins[] = 'NamelessCoder\\GizzleGitPlugins\\GizzlePlugins\\PullPlugin'; } if (TRUE === $this->isEnabled('NamelessCoder\\GizzleGitPlugins\\GizzlePlugins\\CommitPlugin')) { $plugins[] = 'NamelessCoder\\GizzleGitPlugins\\GizzlePlugins\\CommitPlugin'; } if (TRUE === $this->isEnabled('NamelessCoder\\GizzleGitPlugins\\GizzlePlugins\\PushPlugin')) { $plugins[] = 'NamelessCoder\\GizzleGitPlugins\\GizzlePlugins\\PushPlugin'; } return $plugins; }
php
{ "resource": "" }
q241187
UshiosElasticSearchExtension.clientSettings
train
protected function clientSettings(array $configs, ContainerBuilder $container) { foreach($configs as $key => $infos){ $clientDefinition = new Definition(); $clientDefinition->setClass($infos['class']); $hostsSettings = $this->hostSettings($infos); $logPathSettings = $this->logPathSettings($infos); $logLevelSettings = $this->logLevelSettings($infos); $options = array( 'hosts' => $hostsSettings, 'logPath' => $logPathSettings, 'logLevel' => $logLevelSettings ); $clientDefinition->setArguments(array($options)); $clientServiceId = 'ushios_elastic_search_client'; if ($key == 'default'){ $container->setDefinition($clientServiceId, $clientDefinition); $clientServiceId = $clientServiceId.'.default'; }else{ $clientServiceId = $clientServiceId.'.'.$key; } $container->setDefinition($clientServiceId, $clientDefinition); } }
php
{ "resource": "" }
q241188
iauApcg.Apcg
train
public static function Apcg($date1, $date2, array $ebpv, array $ehp, iauASTROM &$astrom) { /* Geocentric observer */ $pv = [ [ 0.0, 0.0, 0.0], [ 0.0, 0.0, 0.0]]; /* Compute the star-independent astrometry parameters. */ IAU::Apcs($date1, $date2, $pv, $ebpv, $ehp, $astrom); /* Finished. */ }
php
{ "resource": "" }
q241189
GroupDomainTrait.doRemoveSkills
train
protected function doRemoveSkills(Group $model, $data) { $errors = []; foreach ($data as $entry) { if (!isset($entry['id'])) { $errors[] = 'Missing id for Skill'; } else { $related = SkillQuery::create()->findOneById($entry['id']); $model->removeSkill($related); } } if (count($errors) > 0) { return new ErrorsException($errors); } }
php
{ "resource": "" }
q241190
GroupDomainTrait.doUpdateSkills
train
protected function doUpdateSkills(Group $model, $data) { // remove all relationships before SkillGroupQuery::create()->filterByGroup($model)->delete(); // add them $errors = []; foreach ($data as $entry) { if (!isset($entry['id'])) { $errors[] = 'Missing id for Skill'; } else { $related = SkillQuery::create()->findOneById($entry['id']); $model->addSkill($related); } } if (count($errors) > 0) { throw new ErrorsException($errors); } }
php
{ "resource": "" }
q241191
FormErrorsParser.realParseErrors
train
private function realParseErrors(FormInterface $form, array &$results) { $errors = $form->getErrors(); if (count($errors) > 0) { $config = $form->getConfig(); $name = $form->getName(); $label = $config->getOption('label'); $translation = $this->getTranslationDomain($form); if (empty($label)) { $label = ucfirst(trim(strtolower(preg_replace(array('/([A-Z])/', '/[_\s]+/'), array('_$1', ' '), $name)))); } $results[] = array( 'name' => $name, 'label' => $label, 'errors' => $errors, 'translation' => $translation, ); } $children = $form->all(); if (count($children) > 0) { foreach ($children as $child) { if ($child instanceof FormInterface) { $this->realParseErrors($child, $results); } } } return $results; }
php
{ "resource": "" }
q241192
FormErrorsParser.getTranslationDomain
train
private function getTranslationDomain(FormInterface $form) { $translation = $form->getConfig()->getOption('translation_domain'); if (empty($translation)) { $parent = $form->getParent(); if (empty($parent)) $translation = 'messages'; while (empty($translation)) { $translation = $parent->getConfig()->getOption('translation_domain'); $parent = $parent->getParent(); if (! $parent instanceof FormInterface && empty($translation)) $translation = 'messages'; } } return $translation = $translation === 'messages' ? null : $translation; // Allow the Symfony Default setting to be used by returning null. }
php
{ "resource": "" }
q241193
Entity.addFieldValidators
train
public function addFieldValidators(array $fieldValidators) { foreach ($fieldValidators as $fieldName => $validators) { $this->fieldValidators[$fieldName] = $validators; } }
php
{ "resource": "" }
q241194
Entity.getFieldsData
train
public function getFieldsData() { $fieldsData = array(); foreach ($this->getFields() as $field) { $fieldData = $this->$field; // If the field is an Entity, decode it. if ($fieldData instanceof self) { $fieldData = $fieldData->getFieldsData(); } elseif (@reset($fieldData) instanceof Entity) { // If the field is an array of Entity, decode them all. $newFieldData = array(); foreach ($fieldData as $key => $entity) { $newFieldData[$key] = $entity->getFieldsData(); } $fieldData = $newFieldData; } $fieldsData[$field] = $fieldData; } return $fieldsData; }
php
{ "resource": "" }
q241195
Entity.store
train
public function store() { // Check whether the object has ever been stored. if ($this->isNew) { Logger::get()->debug('Storing new entity ' . get_class($this) . '...'); // Create the record. Get an ID back. $this->id = $this->getDataSource()->create($this->getFieldsData()); // Store this object in the appropriate factory for further use. $this->getFactory()->registerEntity($this); } else { Logger::get()->debug('Updating entity ' . get_class($this) . ":{$this->id}..."); $this->getDataSource()->update($this->id, $this->getFieldsData()); } // Once stored, the entity is no longer new. $this->isNew = false; }
php
{ "resource": "" }
q241196
Entity.destroy
train
public function destroy() { // Delete from the persistence layer. $this->getDataSource()->destroy($this->id); // Remove from the registry. $this->getFactory()->unregisterEntity($this); // Done, garbage collection should do the rest. }
php
{ "resource": "" }
q241197
Compress.setOptions
train
public function setOptions($options) { if (!is_array($options) && !$options instanceof Traversable) { throw new Exception\InvalidArgumentException(sprintf( '"%s" expects an array or Traversable; received "%s"', __METHOD__, (is_object($options) ? get_class($options) : gettype($options)) )); } foreach ($options as $key => $value) { if ($key == 'options') { $key = 'adapterOptions'; } $method = 'set' . ucfirst($key); if (method_exists($this, $method)) { $this->$method($value); } } return $this; }
php
{ "resource": "" }
q241198
Compress.getAdapter
train
public function getAdapter() { if ($this->adapter instanceof Compress\CompressionAlgorithmInterface) { return $this->adapter; } $adapter = $this->adapter; $options = $this->getAdapterOptions(); if (!class_exists($adapter)) { $adapter = 'Zend\\Filter\\Compress\\' . ucfirst($adapter); if (!class_exists($adapter)) { throw new Exception\RuntimeException(sprintf( '%s unable to load adapter; class "%s" not found', __METHOD__, $this->adapter )); } } $this->adapter = new $adapter($options); if (!$this->adapter instanceof Compress\CompressionAlgorithmInterface) { throw new Exception\InvalidArgumentException("Compression adapter '" . $adapter . "' does not implement Zend\\Filter\\Compress\\CompressionAlgorithmInterface"); } return $this->adapter; }
php
{ "resource": "" }
q241199
Compress.setAdapter
train
public function setAdapter($adapter) { if ($adapter instanceof Compress\CompressionAlgorithmInterface) { $this->adapter = $adapter; return $this; } if (!is_string($adapter)) { throw new Exception\InvalidArgumentException('Invalid adapter provided; must be string or instance of Zend\\Filter\\Compress\\CompressionAlgorithmInterface'); } $this->adapter = $adapter; return $this; }
php
{ "resource": "" }