_id stringlengths 2 7 | title stringlengths 3 151 | partition stringclasses 3
values | text stringlengths 83 13k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q9000 | App.deleteHostedAppStorage | train | protected static function deleteHostedAppStorage($id, $storageServiceId, $storageFolder)
{
$app = AppModel::whereId($id)->first();
if (empty($app) && !empty($storageServiceId) && !empty($storageFolder)) {
/** @type FileServiceInterface $storageService */
$storageService = ServiceManager::getServiceById($storageServiceId);
if ($storageService->folderExists($storageFolder)) {
$storageService->deleteFolder($storageFolder, true);
}
}
} | php | {
"resource": ""
} |
q9001 | DirectoryPlugin.getHash | train | private function getHash($stream, $algorithm = 'sha256')
{
$hash = hash_init($algorithm);
hash_update_stream($hash, $stream);
return hash_final($hash);
} | php | {
"resource": ""
} |
q9002 | Model.getRaw | train | public function getRaw($key = null){
if(null === $key){
return $this->_data;
}
else{
return isset($this->_data[$key])?$this->_data[$key]:null;
}
} | php | {
"resource": ""
} |
q9003 | Model.getWithRelation | train | public function getWithRelation($name){
$relations = $this->getRelations();
if(isset($relations[$name])){
$relation = $relations[$name];
if($relation['relation'] === 'OTO'){
return $this->getOneToOne($relation['target'], isset($relation['key'])?$relation['key']:null, isset($relation['target_key'])?$relation['target_key']:null);
}
elseif($relation['relation'] == 'OTM'){
return $this->getOneToMany($relation['target'], isset($relation['key'])?$relation['key']:null, isset($relation['target_key'])?$relation['target_key']:null);
}
elseif($relation['relation'] == 'MTO'){
return $this->getManyToOne($relation['target'], isset($relation['key'])?$relation['key']:null, isset($relation['target_key'])?$relation['target_key']:null);
}
elseif($relation['relation'] == 'MTM'){
return $this->getManyToMany($relation['target'], $relation['through'], isset($relation['key'])?$relation['key']:null, isset($relation['target_key'])?$relation['target_key']:null);
}
else{
throw new Exception('Invalid relation "'.$relation['relation'].'"');
}
}
else{
return false;
}
} | php | {
"resource": ""
} |
q9004 | Model.getManyToMany | train | public function getManyToMany($target, $through, $key = null, $target_key = null){
$factory = $this->_db->factory($target);
if(null === $key){
$key = $this->getPK();
}
if(null === $target_key){
$target_key = $factory->getPK();
}
$through = $this->parseThrough($through);
if(!$through[1]){
$through[1] = $key;
}
if(!$through[2]){
$through[2] = $target_key;
}
$rows = $this->_db->builder()
->select('t.*')
->from($factory->getTable().' t')
->leftJoin($through[0].' m', 'm.'.$through[2].'=t.'.$target_key)
->where('m.'.$through[1].'=:value', array(
':value' => $this->get($key)
))
->queryAll();
if(false === $rows){
return false;
}
return $factory->mapModels($rows);
} | php | {
"resource": ""
} |
q9005 | Model.save | train | public function save(){
if($this->beforeSave()){
if($this->isNew()){
$data = $this->_dirty;
//insert
if(false !== $rst = $this->_db->builder()->insert($this->getTable(), $data))
{
if(is_string($this->getPK()) && $id = $this->_db->lastInsertId()){
$data[$this->getPK()] = $id;
}
$this->_data = $data;
$this->_dirty = array();
$this->_isNew = false;
$this->afterSave();
return $rst;
}
}
else{
if($this->isDirty()){
//update
$pkConditions = $this->buildPKConditions();
if(false !== $rst = $this->_db->builder()->update($this->getTable(), $this->_dirty, $pkConditions[0], $pkConditions[1])){
$this->_data = array_merge($this->_data, $this->_dirty);
$this->_dirty = array();
$this->afterSave();
return $rst;
}
}
}
}
return false;
} | php | {
"resource": ""
} |
q9006 | TTextUtilities.createToc | train | public function createToc($text, $start = 2, $stop = 4)
{
$level = "$start-$stop";
$pattern = "#<(h[$level])([^>]*)>(.*)</h[$level]>#";
preg_match_all($pattern, $text, $matches, PREG_SET_ORDER);
$toc = [];
foreach ($matches as $val) {
preg_match("#id=['\"]([^>\"']+)#", $val[2], $id);
$id = isset($id[1]) ? $id[1] : null;
$toc[] = [
"level" => isset($val[1])
? $val[1]
: null,
"title" => isset($val[3])
? ltrim(strip_tags($val[3]), "#")
: null,
"id" => $id,
];
}
return $toc;
} | php | {
"resource": ""
} |
q9007 | TTextUtilities.addBaseurlToRelativeLinks | train | public function addBaseurlToRelativeLinks($text, $baseurl, $callback)
{
$pattern = "#<a(.+?)href=\"([^\"]*)\"([.^>]*)>#";
return preg_replace_callback(
$pattern,
function ($matches) use ($baseurl, $callback) {
$url = $callback($matches[2], $baseurl);
return "<a${matches[1]}href=\"$url\"${matches[3]}>";
},
$text
);
} | php | {
"resource": ""
} |
q9008 | TTextUtilities.addBaseurlToImageSource | train | public function addBaseurlToImageSource($text, $baseurl, $callback)
{
$pattern = "#<img(.+?)src=\"([^\"]*)\"(.*?)>#";
return preg_replace_callback(
$pattern,
function ($matches) use ($baseurl, $callback) {
$url = $callback($matches[2], $baseurl);
return "<img${matches[1]}src=\"$url\"${matches[3]}>";
},
$text
);
} | php | {
"resource": ""
} |
q9009 | TTextUtilities.addRevisionHistory | train | public function addRevisionHistory($text, $revision, $start, $end, $class, $source = null)
{
$text = $text . $start;
$text .= "<ul class=\"$class\">\n";
foreach ($revision as $date => $info) {
$text .= "<li>$date: $info</li>\n";
}
$text .= "</ul>\n";
if ($source) {
$text .= "<p><a class=\"$class\" href=\"$source\">"
. t("Document source")
. "</a>.</p>\n";
}
$text .= $end;
return $text;
} | php | {
"resource": ""
} |
q9010 | CodeGeneratorRequest.addFileToGenerate | train | public function addFileToGenerate($value)
{
if ($this->file_to_generate === null) {
$this->file_to_generate = new \Protobuf\ScalarCollection();
}
$this->file_to_generate->add($value);
} | php | {
"resource": ""
} |
q9011 | CodeGeneratorRequest.addProtoFile | train | public function addProtoFile(\google\protobuf\FileDescriptorProto $value)
{
if ($this->proto_file === null) {
$this->proto_file = new \Protobuf\MessageCollection();
}
$this->proto_file->add($value);
} | php | {
"resource": ""
} |
q9012 | UserPasswordResource.handlePOST | train | protected function handlePOST()
{
$oldPassword = $this->getPayloadData('old_password');
$newPassword = $this->getPayloadData('new_password');
$login = $this->request->getParameterAsBool('login');
if (!empty($oldPassword) && Session::isAuthenticated()) {
$user = Session::user();
return static::changePassword($user, $oldPassword, $newPassword, $login);
}
$email = $this->getPayloadData('email');
$username = $this->getPayloadData('username');
$code = $this->getPayloadData('code');
$answer = $this->getPayloadData('security_answer');
$loginAttribute = strtolower(config('df.login_attribute', 'email'));
if ($this->request->getParameterAsBool('reset')) {
if ($loginAttribute === 'username') {
return $this->passwordResetWithUsername($username);
}
return $this->passwordReset($email);
}
if (!empty($code)) {
if ($loginAttribute === 'username') {
return static::changePasswordByCodeWithUsername($username, $code, $newPassword, $login);
}
return static::changePasswordByCode($email, $code, $newPassword, $login);
}
if (!empty($answer)) {
if ($loginAttribute === 'username') {
return static::changePasswordBySecurityAnswerWithUsername($username, $answer, $newPassword, $login);
}
return static::changePasswordBySecurityAnswer($email, $answer, $newPassword, $login);
}
throw new BadRequestException('Not enough information provided to change password.');
} | php | {
"resource": ""
} |
q9013 | UserPasswordResource.changePasswordByCode | train | public static function changePasswordByCode($email, $code, $newPassword, $login = true)
{
if (empty($email)) {
throw new BadRequestException("Missing required email for password reset confirmation.");
}
if (empty($newPassword)) {
throw new BadRequestException("Missing new password for reset.");
}
if (empty($code) || 'y' == $code) {
throw new BadRequestException("Invalid confirmation code.");
}
/** @var User $user */
$user = User::whereEmail($email)->whereConfirmCode($code)->first();
if (null === $user) {
// bad code
throw new NotFoundException("The supplied email and/or confirmation code were not found in the system.");
} elseif ($user->isConfirmationExpired()) {
throw new BadRequestException("Confirmation code expired.");
}
static::isAllowed($user);
try {
$user->confirm_code = 'y';
$user->password = $newPassword;
$user->save();
} catch (\Exception $ex) {
throw new InternalServerErrorException("Error processing password reset.\n{$ex->getMessage()}");
}
if ($login) {
static::userLogin($email, $newPassword);
return ['success' => true, 'session_token' => Session::getSessionToken()];
}
return ['success' => true];
} | php | {
"resource": ""
} |
q9014 | UserPasswordResource.changePasswordBySecurityAnswer | train | protected static function changePasswordBySecurityAnswer($email, $answer, $newPassword, $login = true)
{
if (empty($email)) {
throw new BadRequestException("Missing required email for password reset confirmation.");
}
if (empty($newPassword)) {
throw new BadRequestException("Missing new password for reset.");
}
if (empty($answer)) {
throw new BadRequestException("Missing security answer.");
}
/** @var User $user */
$user = User::whereEmail($email)->first();
if (null === $user) {
// bad code
throw new NotFoundException("The supplied email and confirmation code were not found in the system.");
}
static::isAllowed($user);
try {
// validate answer
$isValid = \Hash::check($answer, $user->security_answer);
} catch (\Exception $ex) {
throw new InternalServerErrorException("Error validating security answer.\n{$ex->getMessage()}");
}
if (!$isValid) {
throw new BadRequestException("The answer supplied does not match.");
}
try {
$user->password = $newPassword;
$user->save();
} catch (\Exception $ex) {
throw new InternalServerErrorException("Error processing password change.\n{$ex->getMessage()}");
}
if ($login) {
static::userLogin($email, $newPassword);
return ['success' => true, 'session_token' => Session::getSessionToken()];
}
return ['success' => true];
} | php | {
"resource": ""
} |
q9015 | UserPasswordResource.sendPasswordResetEmail | train | protected function sendPasswordResetEmail(User $user)
{
$email = $user->email;
/** @var \DreamFactory\Core\User\Services\User $parent */
$parent = $this->getService();
if (!empty($parent->passwordEmailServiceId)) {
try {
/** @var EmailServiceInterface $emailService */
$emailService = ServiceManager::getServiceById($parent->passwordEmailServiceId);
if (empty($emailService)) {
throw new ServiceUnavailableException("Bad email service identifier.");
}
$data = [];
if (!empty($parent->passwordEmailTemplateId)) {
// find template in system db
$template = EmailTemplate::whereId($parent->passwordEmailTemplateId)->first();
if (empty($template)) {
throw new NotFoundException("Email Template id '{$parent->passwordEmailTemplateId}' not found");
}
$data = $template->toArray();
}
if (empty($data) || !is_array($data)) {
throw new ServiceUnavailableException("No data found in default email template for password reset.");
}
$data['to'] = $email;
$data['content_header'] = 'Password Reset';
$data['first_name'] = $user->first_name;
$data['last_name'] = $user->last_name;
$data['name'] = $user->name;
$data['phone'] = $user->phone;
$data['email'] = $user->email;
$data['link'] = url(\Config::get('df.confirm_reset_url')) .
'?code=' . $user->confirm_code .
'&email=' . $email .
'&username=' . $user->username .
'&admin=' . $user->is_sys_admin;
$data['confirm_code'] = $user->confirm_code;
$bodyHtml = array_get($data, 'body_html');
$bodyText = array_get($data, 'body_text');
if (empty($bodyText) && !empty($bodyHtml)) {
$bodyText = strip_tags($bodyHtml);
$bodyText = preg_replace('/ +/', ' ', $bodyText);
}
$emailService->sendEmail($data, $bodyText, $bodyHtml);
return true;
} catch (\Exception $ex) {
throw new InternalServerErrorException("Error processing password reset.\n{$ex->getMessage()}");
}
}
return false;
} | php | {
"resource": ""
} |
q9016 | ANSI.filter | train | public function filter($string, $replacement = '')
{
if ($replacement !== '') {
return preg_replace_callback(static::REGEX_ANSI, function ($matches) use ($replacement) {
return str_repeat($replacement, mb_strlen($matches[0]));
}, $string);
}
return preg_replace(static::REGEX_ANSI, $replacement, $string);
} | php | {
"resource": ""
} |
q9017 | ANSI.getCurrentFormatting | train | public function getCurrentFormatting($string)
{
$stack = [];
foreach ($this->getStyleStack($string) as $style) {
if (preg_match(static::REGEX_FIRST_KEY, $style, $matches)) {
$key = $matches[0];
// if this is a valid setting style, add it to the stack
if (array_key_exists($key, $this->formats)) {
$stack[] = ['key' => $key, 'style' => $style];
} else {
// otherwise remove all elements that this turns off from the current stack
if ($key === static::STYLE_RESET) {
$stack = [];
} else {
$stack = array_filter($stack, function ($item) use ($key) {
return !in_array($key, $this->formats[$item['key']]);
});
}
}
}
}
if (count($stack) === 0) {
return '';
}
$items = array_map(function ($item) {
return $item['style'];
}, $stack);
return sprintf(static::ESCAPE . '[%sm', implode(';', $items));
} | php | {
"resource": ""
} |
q9018 | ANSI.getStyleStack | train | private function getStyleStack($string)
{
if (preg_match_all(static::REGEX_FORMAT, $string, $matches)) {
foreach ($matches[1] as $grouping) {
if (preg_match_all(static::REGEX_STYLE_ITEM, $grouping, $styles)) {
foreach ($styles[0] as $style) {
yield $style;
}
} else {
yield static::STYLE_RESET;
}
}
}
return;
} | php | {
"resource": ""
} |
q9019 | FileHistoryManager.getAuthUserId | train | protected function getAuthUserId()
{
$token = $this->tokenStorage->getToken();
if (null === $token) {
return;
}
$user = $token->getUser();
if (!is_object($user)) {
return;
}
return $user->getId();
} | php | {
"resource": ""
} |
q9020 | Set.addToken | train | public function addToken(int $symbolId, int ...$tokenIdList): void
{
if (empty($tokenIdList)) {
return;
}
if (!isset($this->tokenMap[$symbolId])) {
$this->tokenMap[$symbolId] = $tokenIdList;
$this->increaseChangeCount(count($tokenIdList));
return;
}
$newTokenIdList = array_diff($tokenIdList, $this->tokenMap[$symbolId]);
if (empty($newTokenIdList)) {
return;
}
$this->tokenMap[$symbolId] = array_merge($this->tokenMap[$symbolId], $newTokenIdList);
$this->increaseChangeCount(count($newTokenIdList));
} | php | {
"resource": ""
} |
q9021 | Set.mergeTokens | train | public function mergeTokens(int $targetSymbolId, int $sourceSymbolId): void
{
$this->addToken($targetSymbolId, ...$this->getTokens($sourceSymbolId));
} | php | {
"resource": ""
} |
q9022 | ProductMediaObserver.processImages | train | protected function processImages()
{
// load the store view code
$storeViewCode = $this->getValue(ColumnKeys::STORE_VIEW_CODE);
$attributeSetCode = $this->getValue(ColumnKeys::ATTRIBUTE_SET_CODE);
// load the parent SKU from the row
$parentSku = $this->getValue(ColumnKeys::SKU);
// iterate over the available image fields
foreach ($this->getImageTypes() as $imageColumnName => $labelColumnName) {
// query whether or not, we've a base image
if ($image = $this->getValue($imageColumnName)) {
// initialize the label text
$labelText = $this->getDefaultImageLabel();
// query whether or not a custom label text has been passed
if ($this->hasValue($labelColumnName)) {
$labelText = $this->getValue($labelColumnName);
}
// prepare the new base image
$artefact = $this->newArtefact(
array(
ColumnKeys::STORE_VIEW_CODE => $storeViewCode,
ColumnKeys::ATTRIBUTE_SET_CODE => $attributeSetCode,
ColumnKeys::IMAGE_PARENT_SKU => $parentSku,
ColumnKeys::IMAGE_PATH => $image,
ColumnKeys::IMAGE_PATH_NEW => $image,
ColumnKeys::IMAGE_LABEL => $labelText
),
array(
ColumnKeys::STORE_VIEW_CODE => ColumnKeys::STORE_VIEW_CODE,
ColumnKeys::ATTRIBUTE_SET_CODE => ColumnKeys::ATTRIBUTE_SET_CODE,
ColumnKeys::IMAGE_PARENT_SKU => ColumnKeys::SKU,
ColumnKeys::IMAGE_PATH => $imageColumnName,
ColumnKeys::IMAGE_PATH_NEW => $imageColumnName,
ColumnKeys::IMAGE_LABEL => $labelColumnName
)
);
// append the base image to the artefacts
$this->artefacts[] = $artefact;
}
}
} | php | {
"resource": ""
} |
q9023 | ProductMediaObserver.processAdditionalImages | train | protected function processAdditionalImages()
{
// load the store view code
$storeViewCode = $this->getValue(ColumnKeys::STORE_VIEW_CODE);
$attributeSetCode = $this->getValue(ColumnKeys::ATTRIBUTE_SET_CODE);
// load the parent SKU from the row
$parentSku = $this->getValue(ColumnKeys::SKU);
// query whether or not, we've additional images
if ($additionalImages = $this->getValue(ColumnKeys::ADDITIONAL_IMAGES, null, array($this, 'explode'))) {
// expand the additional image labels, if available
$additionalImageLabels = $this->getValue(ColumnKeys::ADDITIONAL_IMAGE_LABELS, array(), array($this, 'explode'));
// initialize the images with the found values
foreach ($additionalImages as $key => $additionalImage) {
// prepare the additional image
$artefact = $this->newArtefact(
array(
ColumnKeys::STORE_VIEW_CODE => $storeViewCode,
ColumnKeys::ATTRIBUTE_SET_CODE => $attributeSetCode,
ColumnKeys::IMAGE_PARENT_SKU => $parentSku,
ColumnKeys::IMAGE_PATH => $additionalImage,
ColumnKeys::IMAGE_PATH_NEW => $additionalImage,
ColumnKeys::IMAGE_LABEL => isset($additionalImageLabels[$key]) ?
$additionalImageLabels[$key] :
$this->getDefaultImageLabel()
),
array(
ColumnKeys::STORE_VIEW_CODE => ColumnKeys::STORE_VIEW_CODE,
ColumnKeys::ATTRIBUTE_SET_CODE => ColumnKeys::ATTRIBUTE_SET_CODE,
ColumnKeys::IMAGE_PARENT_SKU => ColumnKeys::SKU,
ColumnKeys::IMAGE_PATH => ColumnKeys::ADDITIONAL_IMAGES,
ColumnKeys::IMAGE_PATH_NEW => ColumnKeys::ADDITIONAL_IMAGES,
ColumnKeys::IMAGE_LABEL => ColumnKeys::ADDITIONAL_IMAGE_LABELS
)
);
// append the additional image to the artefacts
$this->artefacts[] = $artefact;
}
}
} | php | {
"resource": ""
} |
q9024 | MelisFrontDragDropZonePlugin.back | train | public function back()
{
$viewModel = new ViewModel();
$viewModel->setTemplate('MelisFront/dragdropzone/meliscontainer');
$viewModel->pluginFrontConfig = $this->pluginFrontConfig;
$viewModel->dragdropzoneId = $this->pluginFrontConfig['id'];
$viewModel->configPluginKey = $this->configPluginKey;
$viewModel->pluginName = $this->pluginName;
$viewModel->pluginXmlDbKey = $this->pluginXmlDbKey;
$pageId = (!empty($this->pluginFrontConfig['pageId'])) ? $this->pluginFrontConfig['pageId'] : 0;
$siteModule = getenv('MELIS_MODULE');
$melisPage = $this->getServiceLocator()->get('MelisEnginePage');
$datasPage = $melisPage->getDatasPage($pageId, 'saved');
if($datasPage)
{
$datasTemplate = $datasPage->getMelisTemplate();
if(!empty($datasTemplate))
{
$siteModule = $datasTemplate->tpl_zf2_website_folder;
}
}
$viewModel->siteModule = $siteModule;
return $viewModel;
} | php | {
"resource": ""
} |
q9025 | FeedbackSubmitted.parseFeedback | train | public function parseFeedback($opts){
$parsedQuestions = [];
$scoreMax = 0;
$scoreRaw = 0;
foreach ($opts['questions'] as $item => $question) {
// Find the response to the current question
$currentResponse = null;
foreach ($opts['attempt']->responses as $responseId => $response) {
if (!empty($response->item) && $response->item == $item) {
$currentResponse = $response;
}
}
if (is_null($currentResponse)) {
// Perhaps a label or the learner did not answer this question - don't add to the array.
break;
}
// Parse the current question
$parsedQuestion = (object)[
'question' => $question,
'options' => $this->parseQuestionPresentation($question->presentation, $question->typ),
'score' => (object) [
'max' => 0,
'raw' => 0
],
'response' => null
];
$parsedQuestion->response = $currentResponse->id;
// Add scores and response
foreach ($parsedQuestion->options as $optionIndex => $option) {
if (isset($option->value) && $option->value > $parsedQuestion->score->max) {
$parsedQuestion->score->max = $option->value;
}
// Find the option the learner selected
if ($optionIndex == $currentResponse->id){
if (isset($option->value)) {
$parsedQuestion->score->raw = $option->value;
}
}
}
$scoreMax += $parsedQuestion->score->max;
$scoreRaw += $parsedQuestion->score->raw;
if ($parsedQuestion->score->max == 0) {
$parsedQuestion->score->max = null;
$parsedQuestion->score->raw = null;
}
else {
$parsedQuestion->score->min = 0;
$parsedQuestion->score->scaled = $parsedQuestion->score->raw / $parsedQuestion->score->max;
}
array_push(
$parsedQuestions,
$parsedQuestion
);
}
$scoreMin = null;
$scoreScaled = null;
if ($scoreMax == 0){
$scoreMax = null;
$scoreRaw = null;
}
else {
$scoreScaled = $scoreRaw / $scoreMax;
$scoreMin = 0;
}
return (object)[
'questions' => $parsedQuestions,
'score' => (object) [
'max' => $scoreMax,
'raw' => $scoreRaw,
'min' => $scoreMin,
'scaled' => $scoreScaled
]
];
} | php | {
"resource": ""
} |
q9026 | FeedbackSubmitted.parseQuestionPresentation | train | protected function parseQuestionPresentation ($presentation, $type){
// Text areas don't have options or scores
if ($type == 'textarea') {
return [];
}
// Strip out the junk.
$presentation = str_replace('r>>>>>', '', $presentation);
$presentation = trim(preg_replace('/\s+/', ' ', $presentation));
$presentation = strip_tags($presentation);
$options = explode('|', $presentation);
$return = [(object)[
'description' => 'Not selected'
]];
foreach ($options as $index => $option) {
switch ($type) {
case 'multichoice':
array_push($return, (object)[
'description' => $option
]);
break;
case 'multichoicerated':
$optionArr = explode('#### ', $option);
array_push($return, (object)[
'description' => $optionArr[1],
'value' => $optionArr[0]
]);
break;
default:
// Unsupported type.
return [];
break;
}
}
return $return;
} | php | {
"resource": ""
} |
q9027 | FieldDescriptorProto.setLabel | train | public function setLabel(\google\protobuf\FieldDescriptorProto\Label $value = null)
{
$this->label = $value;
} | php | {
"resource": ""
} |
q9028 | FieldDescriptorProto.setType | train | public function setType(\google\protobuf\FieldDescriptorProto\Type $value = null)
{
$this->type = $value;
} | php | {
"resource": ""
} |
q9029 | Application.get | train | public function get($name)
{
if (isset($this->container['CI']->{$name})) {
return $this->container['CI']->{$name};
}
return $this->container[$name];
} | php | {
"resource": ""
} |
q9030 | MediaGalleryValueUpdateObserver.initializeProductMediaGalleryValue | train | protected function initializeProductMediaGalleryValue(array $attr)
{
// load the value/store/parent ID
$valueId = $attr[MemberNames::VALUE_ID];
$storeId = $attr[MemberNames::STORE_ID];
$entityId = $attr[MemberNames::ENTITY_ID];
// query whether the product media gallery value already exists or not
if ($entity = $this->loadProductMediaGalleryValue($valueId, $storeId, $entityId)) {
return $this->mergeEntity($entity, $attr);
}
// simply return the attributes
return $attr;
} | php | {
"resource": ""
} |
q9031 | SystemResourceType.toArray | train | public function toArray()
{
return [
'name' => $this->name,
'label' => $this->label,
'description' => $this->description,
'class_name' => $this->className,
'singleton' => $this->singleton,
'read_only' => $this->readOnly,
'subscription_required' => $this->subscriptionRequired,
];
} | php | {
"resource": ""
} |
q9032 | Context.add | train | public function add(Route $route, array $params = [])
{
$callback = $route->getCallable();
if (empty($callback)) {
return;
}
$this->routes[] = $route->getRoute();
$paramNames = $route->getParamNames();
foreach ($paramNames as $name) {
if (isset($params[$name])) {
$this->setParam($name, $params[$name]);
}
}
if (is_array($callback)) {
$this->callable = array_merge($this->callable, $callback);
} elseif (!in_array($callback, $this->callable)) {
$this->callable[] = $callback;
}
} | php | {
"resource": ""
} |
q9033 | Context.transducer | train | public function transducer(RequestInterface $request)
{
$response = null;
if (count($this->middleware)) {
$md = array_pop($this->middleware);
$next = function (RequestInterface $request) {
return $this->transducer($request);
};
if (is_callable($md)) {
$response = $md($request, $next);
} elseif (is_array($md)) {
list($class, $action) = $md;
$instance = is_object($class) ? $class : new $class();
$response = $instance->$action($request, $next);
}
if ($response instanceof Generator) {
$response = Poroutine::resolve($response);
}
}
return $response ?? new Response();
} | php | {
"resource": ""
} |
q9034 | Extension.registerAllExtensions | train | public static function registerAllExtensions(\Protobuf\Extension\ExtensionRegistry $registry)
{
$registry->add(self::package());
$registry->add(self::genericServices());
} | php | {
"resource": ""
} |
q9035 | EntityMutationMetadataProvider.addToChangeSet | train | private function addToChangeSet(
EntityManagerInterface $em,
ClassMetadata $metadata,
$entity,
array &$change_set
) {
if (!isset($change_set[$metadata->rootEntityName])) {
$change_set[$metadata->rootEntityName] = [];
}
if (!in_array($entity, $change_set[$metadata->rootEntityName], true)) {
$change_set[$metadata->rootEntityName][] = $entity;
// recursively find all changes
$this->appendAssociations($em, $metadata, $entity, $change_set);
}
} | php | {
"resource": ""
} |
q9036 | PublicController.show | train | public function show($slug)
{
$model = $this->repository->bySlug($slug, ['translations', 'files', 'files.translations']);
return view('galleries::public.show')
->with(compact('model'));
} | php | {
"resource": ""
} |
q9037 | PropelDataCollector.getTime | train | public function getTime()
{
$time = 0;
foreach ($this->data['queries'] as $query) {
$time += (float) $query['time'];
}
return $time;
} | php | {
"resource": ""
} |
q9038 | PropelDataCollector.buildQueries | train | private function buildQueries()
{
$queries = array();
$outerGlue = $this->propelConfiguration->getParameter('debugpdo.logging.outerglue', ' | ');
$innerGlue = $this->propelConfiguration->getParameter('debugpdo.logging.innerglue', ': ');
foreach ($this->logger->getQueries() as $q) {
$parts = explode($outerGlue, $q, 4);
$times = explode($innerGlue, $parts[0]);
$con = explode($innerGlue, $parts[2]);
$memories = explode($innerGlue, $parts[1]);
$sql = trim($parts[3]);
$con = trim($con[1]);
$time = trim($times[1]);
$memory = trim($memories[1]);
$queries[] = array('connection' => $con, 'sql' => $sql, 'time' => $time, 'memory' => $memory);
}
return $queries;
} | php | {
"resource": ""
} |
q9039 | EnvironmentListener.onRestoreStarted | train | public function onRestoreStarted(RestoreEvent $event)
{
$database = $event->getDatabase();
if ($database->getWithDefault('state', BackupStatus::STATE_SUCCESS) === BackupStatus::STATE_FAILED) {
$this->output->writeln(' <info>Bypassed</info>');
$event->stopPropagation();
}
} | php | {
"resource": ""
} |
q9040 | ExtensionManager.bootGedmoExtensions | train | public function bootGedmoExtensions($namespaces = ['App'], $all = true)
{
if ($all) {
DoctrineExtensions::registerMappingIntoDriverChainORM(
$this->chain,
$this->reader
);
} else {
DoctrineExtensions::registerAbstractMappingIntoDriverChainORM(
$this->chain,
$this->reader
);
}
$driver = $this->metadata->getMetadataDriverImpl();
foreach ($namespaces as $namespace) {
$this->chain->addDriver($driver, $namespace);
}
$this->metadata->setMetadataDriverImpl($this->chain);
$this->dispatcher->fire('doctrine.driver-chain::booted', [
$driver,
$this->chain
]);
} | php | {
"resource": ""
} |
q9041 | FieldOptions.setCtype | train | public function setCtype(\google\protobuf\FieldOptions\CType $value = null)
{
$this->ctype = $value;
} | php | {
"resource": ""
} |
q9042 | FieldOptions.setJstype | train | public function setJstype(\google\protobuf\FieldOptions\JSType $value = null)
{
$this->jstype = $value;
} | php | {
"resource": ""
} |
q9043 | Grammar.whereNotIn | train | protected function whereNotIn(Builder $query, $where)
{
if (empty($where['values'])) {
return '1 = 1';
}
$values = $this->parameterize($where['values']);
return $this->wrap($where['column']).' not in ('.$values.')';
} | php | {
"resource": ""
} |
q9044 | Grammar.compileReplace | train | public function compileReplace(Builder $query, array $values)
{
// Essentially we will force every insert to be treated as a batch insert which
// simply makes creating the SQL easier for us since we can utilize the same
// basic routine regardless of an amount of records given to us to insert.
$table = $this->wrapTable($query->from);
if (! is_array(reset($values))) {
$values = [$values];
}
$columns = $this->columnize(array_keys(reset($values)));
// We need to build a list of parameter place-holders of values that are bound
// to the query. Each insert should have the exact same amount of parameter
// bindings so we will loop through the record and parameterize them all.
$parameters = [];
foreach ($values as $record) {
$parameters[] = '('.$this->parameterize($record).')';
}
$parameters = implode(', ', $parameters);
return "replace into $table ($columns) values $parameters";
} | php | {
"resource": ""
} |
q9045 | Variable.getVariableValue | train | protected function getVariableValue(array $matches)
{
$res = $matches[0];
$variable = substr($matches[0], 1, -1);
if (isset($this->frontmatter[$variable])) {
$res = $this->frontmatter[$variable];
}
return $res;
} | php | {
"resource": ""
} |
q9046 | ClusterClient.MemberAdd | train | public function MemberAdd(MemberAddRequest $argument,
$metadata = [], $options = [])
{
return $this->_simpleRequest('/etcdserverpb.Cluster/MemberAdd',
$argument,
['\Etcdserverpb\MemberAddResponse', 'decode'],
$metadata,
$options
);
} | php | {
"resource": ""
} |
q9047 | ClusterClient.MemberRemove | train | public function MemberRemove(MemberRemoveRequest $argument,
$metadata = [], $options = [])
{
return $this->_simpleRequest('/etcdserverpb.Cluster/MemberRemove',
$argument,
['\Etcdserverpb\MemberRemoveResponse', 'decode'],
$metadata,
$options
);
} | php | {
"resource": ""
} |
q9048 | ClusterClient.MemberUpdate | train | public function MemberUpdate(MemberUpdateRequest $argument,
$metadata = [], $options = [])
{
return $this->_simpleRequest('/etcdserverpb.Cluster/MemberUpdate',
$argument,
['\Etcdserverpb\MemberUpdateResponse', 'decode'],
$metadata,
$options
);
} | php | {
"resource": ""
} |
q9049 | ClusterClient.MemberList | train | public function MemberList(MemberListRequest $argument,
$metadata = [], $options = [])
{
return $this->_simpleRequest('/etcdserverpb.Cluster/MemberList',
$argument,
['\Etcdserverpb\MemberListResponse', 'decode'],
$metadata,
$options
);
} | php | {
"resource": ""
} |
q9050 | Util.checkReconnectError | train | public static function checkReconnectError($errorCode, $errorInfo, $exception) {
if ($exception) {
if (stripos($exception->getMessage(), self::MYSQL_GONE_AWAY) !== false || stripos($exception->getMessage(), self::MYSQL_REFUSED) !== false) {
return true;
}
} elseif ($errorInfo) {
if (stripos($errorInfo[2], self::MYSQL_GONE_AWAY) !== false || stripos($errorInfo[2], self::MYSQL_REFUSED) !== false) {
return true;
}
}
return false;
} | php | {
"resource": ""
} |
q9051 | TOTP.setTimeStep | train | public function setTimeStep($timeStep)
{
$timeStep = abs(intval($timeStep));
$this->timeStep = $timeStep;
return $this;
} | php | {
"resource": ""
} |
q9052 | TOTP.timestampToCounter | train | private static function timestampToCounter($timestamp, $timeStep)
{
$timestamp = abs(intval($timestamp));
$counter = intval(($timestamp * 1000) / ($timeStep * 1000));
return $counter;
} | php | {
"resource": ""
} |
q9053 | ModulePresenter.countFiles | train | public function countFiles()
{
$nbFiles = $this->entity->files->count();
$label = $nbFiles ? 'label-success' : 'label-default';
$html = [];
$html[] = '<span class="label '.$label.'">';
$html[] = $nbFiles;
$html[] = '</span>';
return implode("\r\n", $html);
} | php | {
"resource": ""
} |
q9054 | MainConfiguration.addResolversSection | train | protected function addResolversSection(ArrayNodeDefinition $node, array $factories)
{
$resolverNodeBuilder = $node
->fixXmlConfig('resolver')
->children()
->arrayNode('resolvers')
->useAttributeAsKey('name')
->prototype('array')
->performNoDeepMerging()
->children()
;
foreach ($factories as $name => $factory) {
$factoryNode = $resolverNodeBuilder->arrayNode($name)->canBeUnset();
$factory->addConfiguration($factoryNode);
}
} | php | {
"resource": ""
} |
q9055 | MainConfiguration.getValidators | train | protected function getValidators($key)
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root($key);
$rootNode
->defaultValue(array())
->prototype('variable')
->end()
->beforeNormalization()
->always()
->then(function ($values) {
// Normalize null as array
foreach ($values as $key => $value) {
if ($value === null) {
$values[$key] = array();
}
}
return $values;
})
->end();
$this->addValidatorValidation($rootNode);
return $rootNode;
} | php | {
"resource": ""
} |
q9056 | MainConfiguration.addValidatorValidation | train | protected function addValidatorValidation(ArrayNodeDefinition $node)
{
$node->validate()
->ifTrue(function ($value) {
if (!is_array($value)) {
return true;
}
// All key must be string. Used as alias for the validator service
if (count(array_filter(array_keys($value), 'is_string')) != count($value)) {
return true;
}
// All value must be array. Used as configuration for validator
if (count(array_filter(array_values($value), 'is_array')) != count($value)) {
return true;
}
return false;
})
->thenInvalid('Invalid validators configuration')
->end();
} | php | {
"resource": ""
} |
q9057 | AdvancedTextFilterType.applyDQL | train | protected function applyDQL(QueryBuilder $qb, string $column, $data): string
{
$input = $data['input'];
$uid = uniqid('text', false); // Generate random parameter names to prevent collisions
switch ($data['option']) {
case 'exact':
$qb->setParameter($uid, $input);
return "{$column} = :{$uid}";
case 'like_':
$qb->setParameter($uid, trim($input, '%').'%');
return "{$column} LIKE :{$uid}";
case '_like':
$qb->setParameter($uid, '%'.trim($input, '%'));
return "{$column} LIKE :{$uid}";
case '_like_':
$qb->setParameter($uid, '%'.trim($input, '%').'%');
return "{$column} LIKE :{$uid}";
case 'notlike_':
$qb->setParameter($uid, trim($input, '%').'%');
return "{$column} NOT LIKE :{$uid}";
case '_notlike':
$qb->setParameter($uid, '%'.trim($input, '%'));
return "{$column} NOT LIKE :{$uid}";
case '_notlike_':
$qb->setParameter($uid, '%'.trim($input, '%').'%');
return "{$column} NOT LIKE :{$uid}";
case 'empty':
return "{$column} = ''";
case 'notempty':
return "{$column} != ''";
case 'null':
return "{$column} IS NULL";
case 'notnull':
return "{$column} IS NOT NULL";
}
throw new \UnexpectedValueException("Unknown option '{$data['option']}'");
} | php | {
"resource": ""
} |
q9058 | Subrules.fixMessages | train | private function fixMessages($messages, $name, $realName, $subName)
{
$toRemove = null;
foreach ($messages as $messageRule => $message) {
if (strpos($messageRule, $name.'.') !== false) {
$toRemove = $messageRule;
$messageRule = substr($messageRule, strpos($messageRule, '.') + 1);
$messages[$realName.'_'.$subName.'.'.$messageRule] = $message;
}
}
if (isset($toRemove)) {
$this->messageKey = $toRemove;
}
return $messages;
} | php | {
"resource": ""
} |
q9059 | Subrules.removeMessage | train | private function removeMessage($messages)
{
if (! is_null($this->messageKey)) {
unset($messages[$this->messageKey]);
$this->messageKey = null;
}
return $messages;
} | php | {
"resource": ""
} |
q9060 | Subrules.fixRules | train | private function fixRules($rules, $rule, $name, $realName, $subName)
{
if (isset($rules[$name])) {
$key = array_search($name, array_keys($rules));
$rules = array_slice($rules, 0, $key, true) +
array($realName.'_'.$subName => $rule) +
array_slice($rules, $key, count($rules) - $key, true);
}
return $rules;
} | php | {
"resource": ""
} |
q9061 | KVClient.Range | train | public function Range(RangeRequest $argument,
$metadata = [], $options = [])
{
return $this->_simpleRequest('/etcdserverpb.KV/Range',
$argument,
['\Etcdserverpb\RangeResponse', 'decode'],
$metadata,
$options
);
} | php | {
"resource": ""
} |
q9062 | KVClient.Put | train | public function Put(PutRequest $argument,
$metadata = [], $options = [])
{
return $this->_simpleRequest('/etcdserverpb.KV/Put',
$argument,
['\Etcdserverpb\PutResponse', 'decode'],
$metadata,
$options
);
} | php | {
"resource": ""
} |
q9063 | KVClient.DeleteRange | train | public function DeleteRange(DeleteRangeRequest $argument,
$metadata = [], $options = [])
{
return $this->_simpleRequest('/etcdserverpb.KV/DeleteRange',
$argument,
['\Etcdserverpb\DeleteRangeResponse', 'decode'],
$metadata,
$options
);
} | php | {
"resource": ""
} |
q9064 | KVClient.Txn | train | public function Txn(TxnRequest $argument,
$metadata = [], $options = [])
{
return $this->_simpleRequest('/etcdserverpb.KV/Txn',
$argument,
['\Etcdserverpb\TxnResponse', 'decode'],
$metadata,
$options
);
} | php | {
"resource": ""
} |
q9065 | KVClient.Compact | train | public function Compact(CompactionRequest $argument,
$metadata = [], $options = [])
{
return $this->_simpleRequest('/etcdserverpb.KV/Compact',
$argument,
['\Etcdserverpb\CompactionResponse', 'decode'],
$metadata,
$options
);
} | php | {
"resource": ""
} |
q9066 | ValidationResult.add | train | public function add(ValidationResult $validation, $prefix = null)
{
$prefix = $this->translate($prefix);
foreach ($validation->getErrors() as $err) {
$this->errors[] = ($prefix ? trim($prefix) . ' ' : '') . $err;
}
} | php | {
"resource": ""
} |
q9067 | PresetStore.getPreset | train | public function getPreset($application, $version, array $options = null)
{
$presets = [];
foreach ($this->presets as $preset) {
if ($preset['application'] === $application
&& $this->matchVersion($version, $preset)
&& $this->matchOptions($options, $preset)
) {
$presets[] = $preset['backup'];
}
}
if (0 === count($presets)) {
return [];
}
if (1 === count($presets)) {
return $presets[0];
}
return call_user_func_array('array_merge', $presets);
} | php | {
"resource": ""
} |
q9068 | PresetStore.matchVersion | train | private function matchVersion($actual, array $preset)
{
if (!$actual || !array_key_exists('version', $preset)) {
return false;
}
return Semver::satisfies($actual, $preset['version']);
} | php | {
"resource": ""
} |
q9069 | PresetStore.matchOptions | train | private function matchOptions($actual, array $preset)
{
if (!$actual || !array_key_exists('options', $preset)) {
return true;
}
foreach ($actual as $key => $value) {
if (array_key_exists($key, $preset['options']) && $value !== $preset['options'][$key]) {
return false;
}
}
return true;
} | php | {
"resource": ""
} |
q9070 | FailedToInstantiateObject.fromFactory | train | public static function fromFactory( $factory, $interface, $exception = null ) {
$reason = $exception instanceof Exception
? " Reason: {$exception->getMessage()}"
: '';
if ( is_callable( $factory ) ) {
$message = sprintf(
'Could not instantiate object of type "%1$s" from factory of type: "%2$s".%3$s',
$interface,
gettype( $factory ),
$reason
);
} elseif ( is_string( $factory ) ) {
$message = sprintf(
'Could not instantiate object of type "%1$s" from class name: "%2$s".%3$s',
$interface,
$factory,
$reason
);
} else {
$message = sprintf(
'Could not instantiate object of type "%1$s" from invalid argument of type: "%2$s".%3$s',
$interface,
$factory,
$reason
);
}
return new static( $message, 0, $exception );
} | php | {
"resource": ""
} |
q9071 | RestoreListener.onRestore | train | public function onRestore(RestoreEvent $event)
{
$plugin = $this->pluginRegistry->getPlugin($event->getOption('plugin'));
$optionsResolver = new OptionsResolver();
$plugin->configureOptionsResolver($optionsResolver);
$parameter = $optionsResolver->resolve($event->getOption('parameter'));
try {
$plugin->restore($event->getSource(), $event->getDestination(), $event->getDatabase(), $parameter);
$event->setStatus(BackupStatus::STATE_SUCCESS);
} catch (\Exception $exception) {
$event->setStatus(BackupStatus::STATE_FAILED);
$event->setException($exception);
}
} | php | {
"resource": ""
} |
q9072 | AbstractValidator.applyValidator | train | public function applyValidator($value, array $configuration)
{
// Validate configuration
$resolver = new OptionsResolver();
$this->configureOptions($resolver);
$configuration = $resolver->resolve($configuration);
$this->validate($value, $configuration);
} | php | {
"resource": ""
} |
q9073 | TrumbowygHTMLEditorField.getButtons | train | public function getButtons()
{
if ($this->buttons && is_array($this->buttons)) {
return $this->buttons;
} else {
return $this->config()->default_buttons;
}
} | php | {
"resource": ""
} |
q9074 | TrumbowygHTMLEditorField.addButton | train | public function addButton($button)
{
$buttons = $this->buttons;
// If buttons isn't an array, set it
if (!is_array($buttons)) {
$buttons = array();
}
$buttons[] = $button;
$this->buttons = $buttons;
return $this;
} | php | {
"resource": ""
} |
q9075 | TrumbowygHTMLEditorField.getButtonsJS | train | public function getButtonsJS()
{
$buttons = $this->getButtons();
$str = "";
for ($x = 0; $x < count($buttons); $x++) {
$str .= "'" . $buttons[$x] . "'";
if ($x < (count($buttons) - 1)) {
$str .= ",";
}
}
return $str;
} | php | {
"resource": ""
} |
q9076 | TerminalDimensions.refreshDimensions | train | public function refreshDimensions()
{
if ('\\' === DIRECTORY_SEPARATOR) {
if (preg_match('/^(\d+)x(\d+)(?: \((\d+)x(\d+)\))?$/', trim(getenv('ANSICON')), $matches)) {
// extract [w, H] from "wxh (WxH)"
// or [w, h] from "wxh"
$this->width = (int) $matches[1];
$this->height = isset($matches[4]) ? (int) $matches[4] : (int) $matches[2];
} elseif (null !== $dimensions = $this->getConsoleMode()) {
// extract [w, h] from "wxh"
$this->width = (int) $dimensions[0];
$this->height = (int) $dimensions[1];
}
} elseif ($sttyString = $this->getSttyColumns()) {
if (preg_match('/rows.(\d+);.columns.(\d+);/i', $sttyString, $matches)) {
// extract [w, h] from "rows h; columns w;"
$this->width = (int) $matches[2];
$this->height = (int) $matches[1];
} elseif (preg_match('/;.(\d+).rows;.(\d+).columns/i', $sttyString, $matches)) {
// extract [w, h] from "; h rows; w columns"
$this->width = (int) $matches[2];
$this->height = (int) $matches[1];
}
}
$this->initialised = true;
} | php | {
"resource": ""
} |
q9077 | TerminalDimensions.getConsoleMode | train | private function getConsoleMode()
{
if (!function_exists('proc_open')) {
return null;
}
$spec = [
1 => ['pipe', 'w'],
2 => ['pipe', 'w'],
];
$process = proc_open('mode CON', $spec, $pipes, null, null, ['suppress_errors' => true]);
if (is_resource($process)) {
$info = stream_get_contents($pipes[1]);
fclose($pipes[1]);
fclose($pipes[2]);
proc_close($process);
if (preg_match('/--------+\r?\n.+?(\d+)\r?\n.+?(\d+)\r?\n/', $info, $matches)) {
return [(int) $matches[2], (int) $matches[1]];
}
}
return null;
} | php | {
"resource": ""
} |
q9078 | TerminalDimensions.getSttyColumns | train | private function getSttyColumns()
{
if (!function_exists('proc_open')) {
return null;
}
$spec = [
1 => ['pipe', 'w'],
2 => ['pipe', 'w'],
];
$process = proc_open('stty -a | grep columns', $spec, $pipes, null, null, ['suppress_errors' => true]);
if (is_resource($process)) {
$info = stream_get_contents($pipes[1]);
fclose($pipes[1]);
fclose($pipes[2]);
proc_close($process);
return $info;
}
return null;
} | php | {
"resource": ""
} |
q9079 | SelfUpdateCommand.stable | train | private function stable(Updater $updater)
{
$updater->setStrategy(Updater::STRATEGY_GITHUB);
$updater->getStrategy()->setPackageName('nanbando/core');
$updater->getStrategy()->setPharName('nanbando.phar');
$updater->getStrategy()->setCurrentLocalVersion('@git_version@');
$updater->getStrategy()->setStability(GithubStrategy::STABLE);
} | php | {
"resource": ""
} |
q9080 | CheckNeedTrait.is_needed | train | protected function is_needed( $context = null ) {
$is_needed = $this->hasConfigKey( 'is_needed' )
? $this->getConfigKey( 'is_needed' )
: true;
if ( is_callable( $is_needed ) ) {
return $is_needed( $context );
}
return (bool) $is_needed;
} | php | {
"resource": ""
} |
q9081 | OcflHelper.resolvetoFIDtoURI | train | public static function resolvetoFIDtoURI(int $fid) {
if (!is_integer($fid)) {
return null;
}
/* @var \Drupal\file\FileInterface $file */
$file = \Drupal::entityTypeManager()->getStorage('file')->load($fid);
return $file;
} | php | {
"resource": ""
} |
q9082 | CropFileManager.transformFile | train | public function transformFile(array $data)
{
return $this->filterManager->apply(
$this->dataManager->find('original', $data['filename']),
array(
'filters' => array(
'crop'=> array(
'start' => array($data['x'], $data['y']),
'size' => array($data['width'], $data['height'])
)
)
)
);
} | php | {
"resource": ""
} |
q9083 | CropFileManager.saveTransformedFile | train | public function saveTransformedFile($endpoint, BinaryInterface $cropedFile, array $data)
{
$this
->filesystemMap
->get(
$this->configuration->getValue($endpoint, 'croped_fs')
)
->write(
$data['filename'],
$cropedFile->getContent()
);
} | php | {
"resource": ""
} |
q9084 | EntityAnnotationMetadataProvider.isTracked | train | public function isTracked(EntityManagerInterface $em, $entity)
{
$class = get_class($entity);
$annotations = $this->reader->getClassAnnotations($em->getClassMetadata($class)->getReflectionClass());
foreach ($annotations as $annotation) {
if ($annotation instanceof Tracked) {
return true;
}
}
return false;
} | php | {
"resource": ""
} |
q9085 | Cell.render | train | protected function render($template, $data = [])
{
$view = new View();
$view->type(View::VIEW_TYPE_CELL);
$view->set($data);
$className = get_class($this);
$namePrefix = '\View\Cell\\';
$name = substr($className, strpos($className, $namePrefix) + strlen($namePrefix));
$view->context(str_replace('\\', DIRECTORY_SEPARATOR, $name));
return $view->render($template);
} | php | {
"resource": ""
} |
q9086 | Starter.routeMatched | train | public function routeMatched(ApiRoute $route, Request $request): void
{
if (($format = $request->getParameter(self::API_DOCU_STARTER_QUERY_KEY_GENERATE)) !== null) {
$this->generator->generateAll($this->router);
exit(0);
}
if (($format = $request->getParameter(self::API_DOCU_STARTER_QUERY_KEY_TARGET)) !== null) {
$this->generator->generateTarget($route, $request);
exit(0);
}
} | php | {
"resource": ""
} |
q9087 | ReadonlyDatabase.get | train | public function get($name)
{
if (!$this->exists($name)) {
throw new PropertyNotExistsException($name);
}
return $this->data[$name];
} | php | {
"resource": ""
} |
q9088 | Assert.assertAttributeContains | train | public function assertAttributeContains($needle, $haystackAttributeName, $haystackClassOrObject, $message = '', $ignoreCase = false, $checkForObjectIdentity = true, $checkForNonObjectIdentity = false) {
$this->callAssertMethod(__FUNCTION__, [
'expected' => $key,
]);
} | php | {
"resource": ""
} |
q9089 | Assert.assertAttributeContainsOnly | train | public function assertAttributeContainsOnly($type, $haystackAttributeName, $haystackClassOrObject, $isNativeType = null) {
$this->callAssertMethod(__FUNCTION__, [
'expected' => $key,
]);
} | php | {
"resource": ""
} |
q9090 | Assert.assertAttributeEquals | train | public function assertAttributeEquals($expected, $actualAttributeName, $actualClassOrObject, $message = '', $delta = 0.0, $maxDepth = 10, $canonicalize = false, $ignoreCase = false) {
$this->callAssertMethod(__FUNCTION__, [
'expected' => $key,
]);
} | php | {
"resource": ""
} |
q9091 | Assert.assertFileEquals | train | public function assertFileEquals($expected, $canonicalize = false, $ignoreCase = false) {
$this->callAssertMethod(__FUNCTION__, [
'expected' => $expected,
'additionalParams' => [
$canonicalize,
$ignoreCase,
],
]);
} | php | {
"resource": ""
} |
q9092 | Assert.assertFileNotEquals | train | public function assertFileNotEquals($expected, $canonicalize = false, $ignoreCase = false) {
$this->callAssertMethod(__FUNCTION__, [
'expected' => $expected,
'additionalParams' => [
$canonicalize,
$ignoreCase,
],
]);
} | php | {
"resource": ""
} |
q9093 | Assert.assertStringEqualsFile | train | public function assertStringEqualsFile($expectedFile, $canonicalize = false, $ignoreCase = false) {
$this->callAssertMethod(__FUNCTION__, [
'expected' => $expectedFile,
'additionalParams' => [
$canonicalize,
$ignoreCase,
],
]);
} | php | {
"resource": ""
} |
q9094 | Assert.assertStringNotEqualsFile | train | public function assertStringNotEqualsFile($expectedFile, $canonicalize = false, $ignoreCase = false) {
$this->callAssertMethod(__FUNCTION__, [
'expected' => $expectedFile,
'additionalParams' => [
$canonicalize,
$ignoreCase,
],
]);
} | php | {
"resource": ""
} |
q9095 | Assert.assertEqualXMLStructure | train | public function assertEqualXMLStructure(\DOMElement $expectedElement, $checkAttributes = false) {
$this->callAssertMethod(__FUNCTION__, [
'expected' => $expectedElement,
'options' => [
$checkAttributes,
],
]);
} | php | {
"resource": ""
} |
q9096 | Form.runCallback | train | protected static function runCallback($method, $args)
{
$instance = static::resolveFacadeInstance();
if(empty($args))
{
throw new InvalidArgumentException("Please provide an argument to this method");
}
switch (count($args))
{
case 0:
return $instance->$method();
case 1:
return $instance->$method($args[0]);
case 2:
return $instance->$method($args[0], $args[1]);
case 3:
return $instance->$method($args[0], $args[1], $args[2]);
case 4:
return $instance->$method($args[0], $args[1], $args[2], $args[3]);
default:
return call_user_func_array(array($instance, $method), $args);
}
} | php | {
"resource": ""
} |
q9097 | FormValidation.set_value | train | public function set_value($field = '', $default = '')
{
if (!isset($this->_field_data[$field], $this->_field_data[$field]['postdata'])) {
return $default;
}
return $this->_field_data[$field]['postdata'];
} | php | {
"resource": ""
} |
q9098 | FormValidation.run | train | public function run($group = '')
{
if (!empty($this->validation_data) || $this->CI->input->method() === 'post') {
$this->ran = true;
return parent::run($group);
}
return false;
} | php | {
"resource": ""
} |
q9099 | MelisFrontSEODispatchRouterAbstractListener.redirect404 | train | public function redirect404(MvcEvent $e, $idpage = null)
{
$sm = $e->getApplication()->getServiceManager();
$eventManager = $e->getApplication()->getEventManager();
$melisTree = $sm->get('MelisEngineTree');
$melisSiteDomain = $sm->get('MelisEngineTableSiteDomain');
$melisSite404 = $sm->get('MelisEngineTableSite404');
if ($idpage == null)
{
// idPage is not working, we get the site through the domain
// used to redirect to the right 404
$router = $e->getRouter();
$uri = $router->getRequestUri();
$domainTxt = $uri->getHost();
}
else
{
// We get the site using the idPage and redirect to the site's 404
$domainTxt = $melisTree->getDomainByPageId($idpage, true);
if (empty($domainTxt))
{
$router = $e->getRouter();
$uri = $router->getRequestUri();
$domainTxt = $uri->getHost();
}
$domainTxt = str_replace('http://', '', $domainTxt);
$domainTxt = str_replace('https://', '', $domainTxt);
}
// Get the siteId from the domain
if ($domainTxt)
{
$domain = $melisSiteDomain->getEntryByField('sdom_domain', $domainTxt);
$domain = $domain->current();
if ($domain)
$siteId = $domain->sdom_site_id;
else
return '';
}
else
return '';
// Get the 404 of the siteId
$site404 = $melisSite404->getEntryByField('s404_site_id', $siteId);
if ($site404)
{
$site404 = $site404->current();
if (empty($site404))
{
// No entry in DB for this siteId, let's get the general one (siteId -1)
$site404 = $melisSite404->getEntryByField('s404_site_id', -1);
$site404 = $site404->current();
}
}
if (empty($site404))
{
// No 404 found
return '';
}
else
{
// Check if the 404 defined exist also!
$melisPage = $sm->get('MelisEnginePage');
$datasPage = $melisPage->getDatasPage($site404->s404_page_id, 'published');
$pageTree = $datasPage->getMelisPageTree();
if (empty($pageTree))
return ''; // The 404 page defined doesn't exist or is not published
// Redirect to the 404 of the site
$link = $melisTree->getPageLink($site404->s404_page_id, true);
return $link;
}
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.