_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q11700
CryptBehavior.beforeSave
train
public function beforeSave(Event $event, EntityInterface $entity) { $driver = $this->_table->connection()->driver(); foreach ($this->config('fields') as $field => $type) { if (!$entity->has($field)) { continue; } $raw = $entity->get($field); $plain = Type::build($type)->toDatabase($raw, $driver); $entity->set($field, $this->encrypt($plain)); } }
php
{ "resource": "" }
q11701
CryptBehavior.findDecrypted
train
public function findDecrypted(Query $query, array $options) { $options += ['fields' => []]; $mapper = function ($row) use ($options) { $driver = $this->_table->connection()->driver(); foreach ($this->config('fields') as $field => $type) { if (($options['fields'] && !in_array($field, (array)$options['fields'])) || !($row instanceof EntityInterface) || !$row->has($field) ) { continue; } $cipher = $row->get($field); $plain = $this->decrypt($cipher); $row->set($field, Type::build($type)->toPHP($plain, $driver)); } return $row; }; $formatter = function ($results) use ($mapper) { return $results->map($mapper); }; return $query->formatResults($formatter); }
php
{ "resource": "" }
q11702
CryptBehavior.beforeFind
train
public function beforeFind(Event $event, Query $query, ArrayObject $options, $primary) { $query->find('decrypted'); }
php
{ "resource": "" }
q11703
CryptBehavior.decrypt
train
public function decrypt($cipher) { if (is_resource($cipher)) { $cipher = stream_get_contents($cipher); } return $this->config('strategy')->decrypt($cipher); }
php
{ "resource": "" }
q11704
CryptBehavior._resolveStrategy
train
protected function _resolveStrategy($strategy) { $key = Security::salt(); if (!$strategy) { $class = self::DEFAULT_STRATEGY; $strategy = new $class($key); } if (is_string($strategy) && class_exists($strategy)) { $strategy = new $strategy($key); } if (!($strategy instanceof StrategyInterface)) { throw new Exception('Invalid "strategy" configuration.'); } return $strategy; }
php
{ "resource": "" }
q11705
CryptBehavior._resolveFields
train
protected function _resolveFields($fields) { if (is_string($fields)) { $fields = [$fields]; } if (!is_array($fields)) { throw new Exception('Invalid "fields" configuration.'); } $types = array_keys(Type::map()); foreach ($fields as $field => $type) { if (is_numeric($field) && is_string($type)) { unset($fields[$field]); $field = $type; $type = self::DEFAULT_TYPE; $fields[$field] = $type; } if (!in_array($type, $types)) { throw new Exception(sprintf('The field "%s" mapped type "%s" was not found.', $field, $type)); } } return $fields; }
php
{ "resource": "" }
q11706
Parser._get_title
train
protected function _get_title( $content ) { preg_match( '/<meta +?property=["\']og:title["\'][^\/>]*? content=["\']([^"\']+?)["\'].*?\/?>/si', $content, $reg ); if ( ! empty( $reg[1] ) ) { return $reg[1]; } preg_match( '/<title>([^"\']+?)<\/title>/si', $content, $reg ); if ( ! empty( $reg[1] ) ) { return $reg[1]; } }
php
{ "resource": "" }
q11707
Parser._get_permalink
train
protected function _get_permalink( $content ) { preg_match( '/<meta +?property=["\']og:url["\'][^\/>]*? content=["\']([^"\']+?)["\'].*?\/?>/si', $content, $reg ); if ( ! empty( $reg[1] ) ) { return $reg[1]; } return $this->url; }
php
{ "resource": "" }
q11708
Parser._get_description
train
protected function _get_description( $content ) { preg_match( '/<meta +?property=["\']og:description["\'][^\/>]*? content=["\']([^"\']+?)["\'].*?\/?>/si', $content, $reg ); if ( ! empty( $reg[1] ) ) { return $reg[1]; } preg_match( '/<meta +?name=["\']description["\'][^\/>]*? content=["\']([^"\']+?)["\'].*?\/?>/si', $content, $reg ); if ( ! empty( $reg[1] ) ) { return $reg[1]; } }
php
{ "resource": "" }
q11709
Parser._get_domain
train
protected function _get_domain( $content ) { $permalink = $this->get_permalink(); if ( ! $permalink ) { $permalink = $this->_get_permalink( $content ); } preg_match( '/https?:\/\/([^\/]+)/', $permalink, $reg ); if ( ! empty( $reg[1] ) ) { return $reg[1]; } }
php
{ "resource": "" }
q11710
Parser._get_favicon
train
protected function _get_favicon( $content ) { preg_match( '/<link +?rel=["\']shortcut icon["\'][^\/>]*? href=["\']([^"\']+?)["\'][^\/>]*?\/?>/si', $content, $reg ); if ( empty( $reg[1] ) ) { preg_match( '/<link +?rel=["\']icon["\'][^\/>]*? href=["\']([^"\']+?)["\'][^\/>]*?\/?>/si', $content, $reg ); } if ( empty( $reg[1] ) ) { return; } $favicon = $reg[1]; $favicon = $this->_relative_path_to_url( $favicon, $content ); if ( is_ssl() ) { $favicon = preg_replace( '|^http:|', 'https:', $favicon ); } $requester = new Requester( $favicon ); $response = $requester->request( $favicon ); if ( is_wp_error( $response ) ) { return; } $status_code = $requester->get_status_code(); if ( 200 != $status_code && 304 != $status_code ) { return; } return $favicon; }
php
{ "resource": "" }
q11711
Parser._get_thumbnail
train
protected function _get_thumbnail( $content ) { preg_match( '/<meta +?property=["\']og:image["\'][^\/>]*? content=["\']([^"\']+?)["\'].*?\/?>/si', $content, $reg ); if ( empty( $reg[1] ) ) { return; } $thumbnail = $reg[1]; $thumbnail = $this->_relative_path_to_url( $thumbnail, $content ); if ( is_ssl() ) { $thumbnail = preg_replace( '|^http:|', 'https:', $thumbnail ); } $requester = new Requester( $thumbnail ); $response = $requester->request( $thumbnail ); if ( is_wp_error( $response ) ) { return; } $status_code = $requester->get_status_code(); if ( 200 != $status_code && 304 != $status_code ) { return; } return $thumbnail; }
php
{ "resource": "" }
q11712
Parser._relative_path_to_url
train
protected function _relative_path_to_url( $path, $content ) { if ( wp_http_validate_url( $path ) ) { return $path; } $permalink = $this->get_permalink(); if ( ! $permalink ) { $permalink = $this->_get_permalink( $content ); } preg_match( '/(https?:\/\/[^\/]+)/', $permalink, $reg ); if ( empty( $reg[0] ) ) { return false; } return trailingslashit( $reg[0] ) . $path; }
php
{ "resource": "" }
q11713
GameRepository.findWithLetter
train
public function findWithLetter($letter, $locale) { $query = $this->createQueryBuilder('g') ->addSelect('translation'); if ($letter === '0') { $query ->innerJoin('g.translations', 'translation') ->where('SUBSTRING(translation.name , 1, 1) NOT IN (:list)') ->setParameter('list', range('a', 'z')); } else { $query ->innerJoin('g.translations', 'translation') ->where('SUBSTRING(translation.name , 1, 1) = :letter') ->setParameter('letter', $letter); } $query ->andWhere('translation.locale = :locale') ->setParameter('locale', $locale) ->orderBy('translation.name', 'ASC'); $this->onlyActive($query); $this->withPlatforms($query); return $query->getQuery(); }
php
{ "resource": "" }
q11714
GameRepository.findSerieGames
train
public function findSerieGames($idSerie) { $query = $this->createQueryBuilder('g'); $query ->where('g.idSerie = :idSerie') ->setParameter('idSerie', $idSerie); $this->onlyActive($query); $this->withPlatforms($query); return $query->getQuery()->getResult(); }
php
{ "resource": "" }
q11715
SyliusRuntime.getProductName
train
public function getProductName($productId): ?string { $product = $this->productRepository->find($productId); if (!$product instanceof ProductInterface) { return null; } return $product->getName(); }
php
{ "resource": "" }
q11716
SyliusRuntime.getTaxonPath
train
public function getTaxonPath($taxonId): ?array { $taxon = $this->taxonRepository->find($taxonId); if (!$taxon instanceof TaxonInterface) { return null; } $parts = [$taxon->getName()]; while ($taxon->getParent() instanceof TaxonInterface) { $taxon = $taxon->getParent(); $parts[] = $taxon->getName(); } return array_reverse($parts); }
php
{ "resource": "" }
q11717
Debug.separator
train
public static function separator($char = '=', $repeat = 50) { if (self::isCli()) { echo str_repeat($char, $repeat) . "\n"; } else { echo "<div class=\"debug-separator\">" . str_repeat($char, $repeat) . "</div>\n"; } }
php
{ "resource": "" }
q11718
ExportComponent.export
train
public function export($id = null, $type = 'docx') { $type = mb_strtolower($type); if (!empty($type) && !$this->_controller->RequestHandler->prefers($type)) { throw new BadRequestException(__d('view_extension', 'Invalid request')); } if (!method_exists($this->_model, 'generateExportFile') || !method_exists($this->_model, 'getExportFilename')) { throw new InternalErrorException(__d('view_extension', 'Export method not found')); } $tempFile = $this->_model->generateExportFile($id); if (empty($tempFile)) { throw new InternalErrorException(__d('view_extension', 'Invalid generated file')); } $exportFile = pathinfo($tempFile, PATHINFO_FILENAME); return $this->download($id, $exportFile); }
php
{ "resource": "" }
q11719
ExportComponent.preview
train
public function preview($id = null) { if (!method_exists($this->_model, 'generateExportFile')) { throw new InternalErrorException(__d( 'view_extension', 'Method "%s" is not exists in model "%s"', 'generateExportFile()', $this->_model->name )); } if (!method_exists($this->_model, 'getExportFilename')) { throw new InternalErrorException(__d( 'view_extension', 'Method "%s" is not exists in model "%s"', 'getExportFilename()', $this->_model->name )); } $tempFile = $this->_model->generateExportFile($id); if (empty($tempFile)) { throw new InternalErrorException(__d('view_extension', 'Invalid generated file')); } $previewFile = $tempFile; $exportPath = $this->_getExportDir(); $pdfTempFile = $exportPath . uniqid() . '.pdf'; if ($this->_convertFileToPdf($tempFile, $pdfTempFile)) { $previewFile = $pdfTempFile; } $exportFileName = $this->_model->getExportFilename($id, false); $preview = $this->_createImgPreview($previewFile); $orig = pathinfo($tempFile, PATHINFO_FILENAME); $pdf = null; if (!empty($pdfTempFile)) { $pdf = pathinfo($pdfTempFile, PATHINFO_FILENAME); } $download = compact('orig', 'pdf'); $result = compact('exportFileName', 'preview', 'download'); return $result; }
php
{ "resource": "" }
q11720
ExportComponent._convertFileToPdf
train
protected function _convertFileToPdf($inputFile = null, $outputFile = null) { $cfgUnoconv = $this->_getUnoconvConfig(); if ($cfgUnoconv === false) { throw new InternalErrorException(__d('view_extension', 'Unoconv is not configured')); } if (!file_exists($inputFile)) { throw new InternalErrorException(__d('view_extension', 'Invalid input file for converting to PDF')); } if (empty($outputFile)) { throw new InternalErrorException(__d('view_extension', 'Invalid output file for converting to PDF')); } if (mime_content_type($inputFile) === 'application/pdf') { return false; } extract($cfgUnoconv); if ($timeout <= 0) { $timeout = 60; } $unoconvOpt = [ 'timeout' => $timeout, 'unoconv.binaries' => $binaries, ]; $unoconv = Unoconv\Unoconv::create($unoconvOpt); $unoconv->transcode($inputFile, 'pdf', $outputFile); if (!file_exists($outputFile)) { throw new InternalErrorException(__d('view_extension', 'Error on creation PDF file')); } return true; }
php
{ "resource": "" }
q11721
ExportComponent._createImgPreview
train
protected function _createImgPreview($inputFile = null) { $result = []; if (empty($inputFile) || !file_exists($inputFile)) { return $result; } $previewFullPath = $this->_getPreviewDir(); $wwwRoot = Configure::read('App.www_root'); if (empty($wwwRoot)) { throw new InternalErrorException(__d('view_extension', 'Invalid path to "www_root" directory')); } $wwwRootPos = mb_stripos($previewFullPath, $wwwRoot); if ($wwwRootPos !== 0) { throw new InternalErrorException(__d('view_extension', 'Path to preview directory is not contain path to "www_root" directory')); } $previewWebRootPath = mb_substr($previewFullPath, mb_strlen($wwwRoot) - 1); if (empty($previewWebRootPath)) { throw new InternalErrorException(__d('view_extension', 'Invalid path to preview directory')); } $jpgTempFile = uniqid(); $im = new Imagick(); $im->setResolution(150, 150); if (!$im->readimage($inputFile)) { $im->clear(); $im->destroy(); return $result; } $numPages = $im->getNumberImages(); for ($page = 0; $page < $numPages; $page++) { $postfix = '[' . $page . ']'; $previewFile = $jpgTempFile . $postfix . '.jpg'; if (!$im->readimage($inputFile . $postfix)) { continue; } $im->setImageFormat('jpeg'); $im->setImageCompressionQuality(90); if ($im->writeImage($previewFullPath . $previewFile)) { $result[] = $previewWebRootPath . $previewFile; } } $im->clear(); $im->destroy(); if (!empty($result) && (DIRECTORY_SEPARATOR === '\\')) { foreach ($result as &$resultItem) { $resultItem = mb_ereg_replace('\\\\', '/', $resultItem); } } return $result; }
php
{ "resource": "" }
q11722
ExportComponent._setExportDir
train
protected function _setExportDir($path = null) { $path = (string)$path; if (file_exists($path)) { $this->_pathExportDir = $path; } }
php
{ "resource": "" }
q11723
ExportComponent._setPreviewDir
train
protected function _setPreviewDir($path = null) { $path = (string)$path; if (file_exists($path)) { $this->_pathPreviewDir = $path; } }
php
{ "resource": "" }
q11724
ExportComponent._setStorageTimeExport
train
protected function _setStorageTimeExport($time = null) { $time = (int)$time; if ($time > 0) { $this->_storageTimeExport = $time; } }
php
{ "resource": "" }
q11725
ExportComponent._setStorageTimePreview
train
protected function _setStorageTimePreview($time = null) { $time = (int)$time; if ($time > 0) { $this->_storageTimePreview = $time; } }
php
{ "resource": "" }
q11726
ExportComponent.download
train
public function download($id = null, $file = null) { $type = $this->_controller->RequestHandler->prefers(); $exportFileName = null; if (method_exists($this->_model, 'getExportFilename')) { $exportFileName = $this->_model->getExportFilename($id, true); } $exportPath = $this->_getExportDir(); $downloadFile = $exportPath . $file; if (!empty($type)) { $downloadFile .= '.' . $type; } if (!file_exists($downloadFile)) { throw new InternalErrorException(__d('view_extension', 'Invalid file for downloading')); } if (!empty($type) && !empty($exportFileName)) { $this->_controller->response->type($type); $exportFileName .= '.' . $type; } $responseOpt = [ 'download' => true, ]; if (!empty($exportFileName)) { if ($this->_controller->request->is('msie')) { $exportFileName = rawurlencode($exportFileName); } $responseOpt['name'] = $exportFileName; } $this->_controller->response->file($downloadFile, $responseOpt); return $this->_controller->response; }
php
{ "resource": "" }
q11727
ExportComponent._clearDir
train
protected function _clearDir($type = null, $timeNow = null) { switch (mb_strtolower($type)) { case 'export': $clearPath = $this->_getExportDir(); $storageTime = $this->_getStorageTimeExport(); break; case 'preview': $clearPath = $this->_getPreviewDir(); $storageTime = $this->_getStorageTimePreview(); break; default: return false; } $result = true; $oFolder = new Folder($clearPath, true); $exportFiles = $oFolder->find('.*', false); if (empty($exportFiles)) { return $result; } if (!empty($timeNow)) { $timeNow = (int)$timeNow; } else { $timeNow = time(); } $exportFilesPath = $oFolder->pwd(); foreach ($exportFiles as $exportFile) { $oFile = new File($exportFilesPath . DS . $exportFile); $lastChangeTime = $oFile->lastChange(); if ($lastChangeTime === false) { continue; } if (($timeNow - $lastChangeTime) > $storageTime) { if (!$oFile->delete()) { $result = false; } } } return true; }
php
{ "resource": "" }
q11728
ExportComponent._getUnoconvConfig
train
protected function _getUnoconvConfig() { $cfgUnoconv = $this->_modelConfigTheme->getUnoconvConfig(); if (empty($cfgUnoconv)) { return false; } $timeout = (int)Hash::get($cfgUnoconv, 'timeout'); $binaries = (string)Hash::get($cfgUnoconv, 'binaries'); $result = compact('timeout', 'binaries'); return $result; }
php
{ "resource": "" }
q11729
ExportComponent.isUnoconvReady
train
public function isUnoconvReady() { $cfgUnoconv = $this->_getUnoconvConfig(); if ($cfgUnoconv === false) { return false; } if (!file_exists($cfgUnoconv['binaries'])) { return false; } return true; }
php
{ "resource": "" }
q11730
TwigHandlerTrait.fetchTemplate
train
public function fetchTemplate(Request $request, $template) { if (!$this->view instanceof Twig) { throw new Exception("Twig provider not registered."); } foreach ($this->settings['view']['global'] as $key => $map) { $key = is_numeric($key) ? $map : $key; switch ($key) { case 'request': $value = $request; break; default: $value = isset($this->container[$key]) ? $this->container[$key] : null; break; } $this->view->getEnvironment()->addGlobal($map, $value); } $result = $this->view->fetch( $template . $this->settings['view']['extension'], $this->data->all() ); return $result; }
php
{ "resource": "" }
q11731
TwigHandlerTrait.renderTemplate
train
public function renderTemplate(Request $request, Response $response, $template, $status = null) { $response->getBody()->write($this->fetchTemplate($request, $template)); if ($status) { $response = $response->withStatus($status); } return $response; }
php
{ "resource": "" }
q11732
GateKeeper.isAccessibleBy
train
public static function isAccessibleBy($document, $user) { $result = null; switch (Convertor::baseClassName($user)) { case 'User': //Admin $result = true; break; case 'Customer': //Customer $result = (self::getDocumentCompany($document) == self::getCustomerCompany($user)); break; case 'Anonym': //Anonymous $result = false; break; } return $result; }
php
{ "resource": "" }
q11733
GateKeeper.getDocumentCompany
train
public static function getDocumentCompany($document) { return $document->getDataValue('firma') ? \FlexiPeeHP\FlexiBeeRO::uncode( $document->getDataValue('firma')) : null; }
php
{ "resource": "" }
q11734
GateKeeper.getCustomerCompany
train
public static function getCustomerCompany($customer) { return $customer->adresar->getDataValue('kod') ? \FlexiPeeHP\FlexiBeeRO::uncode($customer->adresar->getDataValue('kod')) : null; }
php
{ "resource": "" }
q11735
Controller.redirect
train
protected function redirect(string $ref, array $params = [], string $schema = null) { $url = $this->link($ref, $params, $schema); $response = new Response(); $response->setCode(Response::CODE_REDIRECT_SEE_OTHER); $response->addHeader('Location', $url); return $response; }
php
{ "resource": "" }
q11736
Attribute.getDefaultValue
train
public function getDefaultValue() { if ($this->hasOption(self::OPTION_DEFAULT_VALUE)) { return $this->getSanitizedValue( $this->getOption(self::OPTION_DEFAULT_VALUE, $this->getNullValue()) ); } return $this->getNullValue(); }
php
{ "resource": "" }
q11737
Attribute.getValidator
train
public function getValidator() { if (!$this->validator) { $default_validator_class = Validator::CLASS; $validator_implementor = $this->getOption(self::OPTION_VALIDATOR, $default_validator_class); if (!class_exists($validator_implementor, true)) { throw new InvalidConfigException( sprintf( "Unable to resolve validator implementor '%s' given for attribute '%s' on entity type '%s'.", $validator_implementor, $this->getName(), $this->getType()->getName() ) ); } $validator = new $validator_implementor($this->getName(), $this->buildValidationRules()); if (!$validator instanceof ValidatorInterface) { throw new InvalidTypeException( sprintf( "Invalid validator implementor '%s' given for attribute '%s' on entity type '%s'. " . "Make sure to implement '%s'.", $validator_implementor, $this->getName(), $this->getType() ? $this->getType()->getName() : 'undefined', ValidatorInterface::CLASS ) ); } $this->validator = $validator; } return $this->validator; }
php
{ "resource": "" }
q11738
Attribute.createValueHolder
train
public function createValueHolder($apply_default_values = false) { if (!$this->value_holder_implementor) { $implementor = $this->hasOption(self::OPTION_VALUE_HOLDER) ? $this->getOption(self::OPTION_VALUE_HOLDER) : $this->buildDefaultValueHolderClassName(); if (!class_exists($implementor)) { throw new InvalidConfigException( sprintf( "Invalid valueholder implementor '%s' configured for attribute '%s' on entity '%s'.", $implementor, $this->getName(), $this->getType() ? $this->getType()->getName() : 'undefined' ) ); } $test_value_holder = new $implementor($this); if (!$test_value_holder instanceof ValueHolderInterface) { throw new InvalidTypeException( sprintf( "Invalid valueholder implementation '%s' given for attribute '%s' on entity type '%s'. " . "Make sure to implement '%s'.", $implementor, $this->getName(), $this->getType() ? $this->getType()->getName() : 'undefined', ValueHolderInterface::CLASS ) ); } $this->value_holder_implementor = $implementor; } $value_holder = new $this->value_holder_implementor($this); if ($apply_default_values === true) { $value_holder->setValue($this->getDefaultValue()); } elseif ($apply_default_values === false) { $value_holder->setValue($this->getNullValue()); } else { throw new InvalidTypeException( sprintf( "Only boolean arguments are acceptable for attribute '%s' on entity type '%s'. ", $this->getName(), $this->getType() ? $this->getType()->getName() : 'undefined' ) ); } return $value_holder; }
php
{ "resource": "" }
q11739
Console.init
train
public function init(OutputInterface $consoleOutput, $dispatcher) { $this->consoleOutput = $consoleOutput; $this->dispatcher = $dispatcher; $this->sfStyleOutput = new SymfonyStyle(new StringInput(''), $consoleOutput); }
php
{ "resource": "" }
q11740
Console.getSfStyleOutput
train
public function getSfStyleOutput(): SymfonyStyle { if (is_null($this->sfStyleOutput)) { $this->sfStyleOutput = new SymfonyStyle(new StringInput(''), new NullOutput()); } return $this->sfStyleOutput; }
php
{ "resource": "" }
q11741
BaseOAuth.getRequestToken
train
function getRequestToken($args = array()) {/*{{{*/ $r = $this->oAuthRequest($this->requestTokenURL(), $args); $token = $this->oAuthParseResponse($r); $this->token = new OAuthConsumer($token['oauth_token'], $token['oauth_token_secret']); return $token; }
php
{ "resource": "" }
q11742
BaseOAuth.oAuthParseResponse
train
function oAuthParseResponse($responseString) { $r = array(); foreach (explode('&', $responseString) as $param) { $pair = explode('=', $param, 2); if (count($pair) != 2) continue; $r[urldecode($pair[0])] = urldecode($pair[1]); } return $r; }
php
{ "resource": "" }
q11743
BaseOAuth.getAccessToken
train
function getAccessToken($args = array()) {/*{{{*/ $r = $this->oAuthRequest($this->accessTokenURL(), $args); //var_dump($r); $token = $this->oAuthParseResponse($r); $this->token = new OAuthConsumer($token['oauth_token'], $token['oauth_token_secret']); return $token; }
php
{ "resource": "" }
q11744
SqLite.getDsn
train
public function getDsn(): string { /* # File connection $connection = new PDO('sqlite:<filename>', null, null array(PDO::ATTR_PERSISTENT => true) ); # Memory connection $connection = new PDO('sqlite::memory:', null, null array(PDO::ATTR_PERSISTENT => true) ); */ # Build the DSN $_dsn = $this->getDriver().':'.$this->getFilename(); # Set it $this->setDsn($_dsn); return $_dsn; }
php
{ "resource": "" }
q11745
RestartExpansion.execute
train
public function execute($login, InputInterface $input) { $scriptToExecute = 'run.sh'; if ($this->gameData->getServerOs() == GameDataStorage::OS_WINDOWS) { $scriptToExecute = 'run.bat'; } $player = $this->playerStorage->getPlayerInfo($login); $this->chatNotification->sendMessage( 'expansion_core.chat_commands.restart.message', null, ['%nickname%' => $player->getNickName()] ); $this->application->stopApplication(); $process = new Process("bin/" . $scriptToExecute . " &"); $process->start(); }
php
{ "resource": "" }
q11746
CsvReader.getHeader
train
public function getHeader() { if (null == $this->header) { $header = $this->getNextDataSet(); if (null === $header) { throw new Exception("Cannot retrieve header"); } $this->setHeader($header); } return $this->header; }
php
{ "resource": "" }
q11747
CsvReader.reset
train
public function reset() { $this->header = null; $this->line = 0; $this->file->rewind(); return $this; }
php
{ "resource": "" }
q11748
SimpleEmailService.listVerifiedEmailAddresses
train
public function listVerifiedEmailAddresses() { $rest = new SimpleEmailServiceRequest($this, 'GET'); $rest->setParameter('Action', 'ListVerifiedEmailAddresses'); $rest = $rest->getResponse(); if($rest->error === false && $rest->code !== 200) { $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status'); } if($rest->error !== false) { $this->__triggerError('listVerifiedEmailAddresses', $rest->error); return false; } $response = array(); if(!isset($rest->body)) { return $response; } $addresses = array(); foreach($rest->body->ListVerifiedEmailAddressesResult->VerifiedEmailAddresses->member as $address) { $addresses[] = (string)$address; } $response['Addresses'] = $addresses; $response['RequestId'] = (string)$rest->body->ResponseMetadata->RequestId; return $response; }
php
{ "resource": "" }
q11749
SimpleEmailService.deleteVerifiedEmailAddress
train
public function deleteVerifiedEmailAddress($email) { $rest = new SimpleEmailServiceRequest($this, 'DELETE'); $rest->setParameter('Action', 'DeleteVerifiedEmailAddress'); $rest->setParameter('EmailAddress', $email); $rest = $rest->getResponse(); if($rest->error === false && $rest->code !== 200) { $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status'); } if($rest->error !== false) { $this->__triggerError('deleteVerifiedEmailAddress', $rest->error); return false; } $response['RequestId'] = (string)$rest->body->ResponseMetadata->RequestId; return $response; }
php
{ "resource": "" }
q11750
SimpleEmailService.__triggerError
train
public function __triggerError($functionname, $error) { if($error == false) { trigger_error(sprintf("SimpleEmailService::%s(): Encountered an error, but no description given", $functionname), E_USER_WARNING); } else if(isset($error['curl']) && $error['curl']) { trigger_error(sprintf("SimpleEmailService::%s(): %s %s", $functionname, $error['code'], $error['message']), E_USER_WARNING); } else if(isset($error['Error'])) { $e = $error['Error']; $message = sprintf("SimpleEmailService::%s(): %s - %s: %s\nRequest Id: %s\n", $functionname, $e['Type'], $e['Code'], $e['Message'], $error['RequestId']); trigger_error($message, E_USER_WARNING); } else { trigger_error(sprintf("SimpleEmailService::%s(): Encountered an error: %s", $functionname, $error), E_USER_WARNING); } }
php
{ "resource": "" }
q11751
SimpleEmailServiceRequest.setParameter
train
public function setParameter($key, $value, $replace = true) { if(!$replace && isset($this->parameters[$key])) { $temp = (array)($this->parameters[$key]); $temp[] = $value; $this->parameters[$key] = $temp; } else { $this->parameters[$key] = $value; } }
php
{ "resource": "" }
q11752
SimpleEmailServiceMessage.validate
train
public function validate() { if(count($this->to) == 0) return false; if($this->from == null || strlen($this->from) == 0) return false; // messages require at least one of: subject, messagetext, messagehtml. if(($this->subject == null || strlen($this->subject) == 0) && ($this->messagetext == null || strlen($this->messagetext) == 0) && ($this->messagehtml == null || strlen($this->messagehtml) == 0)) { return false; } return true; }
php
{ "resource": "" }
q11753
GamecurrencyQuery.filterBySenderlogin
train
public function filterBySenderlogin($senderlogin = null, $comparison = null) { if (null === $comparison) { if (is_array($senderlogin)) { $comparison = Criteria::IN; } } return $this->addUsingAlias(GamecurrencyTableMap::COL_SENDERLOGIN, $senderlogin, $comparison); }
php
{ "resource": "" }
q11754
GamecurrencyQuery.filterByReceiverlogin
train
public function filterByReceiverlogin($receiverlogin = null, $comparison = null) { if (null === $comparison) { if (is_array($receiverlogin)) { $comparison = Criteria::IN; } } return $this->addUsingAlias(GamecurrencyTableMap::COL_RECEIVERLOGIN, $receiverlogin, $comparison); }
php
{ "resource": "" }
q11755
GamecurrencyQuery.filterByTransactionid
train
public function filterByTransactionid($transactionid = null, $comparison = null) { if (is_array($transactionid)) { $useMinMax = false; if (isset($transactionid['min'])) { $this->addUsingAlias(GamecurrencyTableMap::COL_TRANSACTIONID, $transactionid['min'], Criteria::GREATER_EQUAL); $useMinMax = true; } if (isset($transactionid['max'])) { $this->addUsingAlias(GamecurrencyTableMap::COL_TRANSACTIONID, $transactionid['max'], Criteria::LESS_EQUAL); $useMinMax = true; } if ($useMinMax) { return $this; } if (null === $comparison) { $comparison = Criteria::IN; } } return $this->addUsingAlias(GamecurrencyTableMap::COL_TRANSACTIONID, $transactionid, $comparison); }
php
{ "resource": "" }
q11756
GamecurrencyQuery.filterByBillid
train
public function filterByBillid($billid = null, $comparison = null) { if (is_array($billid)) { $useMinMax = false; if (isset($billid['min'])) { $this->addUsingAlias(GamecurrencyTableMap::COL_BILLID, $billid['min'], Criteria::GREATER_EQUAL); $useMinMax = true; } if (isset($billid['max'])) { $this->addUsingAlias(GamecurrencyTableMap::COL_BILLID, $billid['max'], Criteria::LESS_EQUAL); $useMinMax = true; } if ($useMinMax) { return $this; } if (null === $comparison) { $comparison = Criteria::IN; } } return $this->addUsingAlias(GamecurrencyTableMap::COL_BILLID, $billid, $comparison); }
php
{ "resource": "" }
q11757
GamecurrencyQuery.filterByAmount
train
public function filterByAmount($amount = null, $comparison = null) { if (is_array($amount)) { $useMinMax = false; if (isset($amount['min'])) { $this->addUsingAlias(GamecurrencyTableMap::COL_AMOUNT, $amount['min'], Criteria::GREATER_EQUAL); $useMinMax = true; } if (isset($amount['max'])) { $this->addUsingAlias(GamecurrencyTableMap::COL_AMOUNT, $amount['max'], Criteria::LESS_EQUAL); $useMinMax = true; } if ($useMinMax) { return $this; } if (null === $comparison) { $comparison = Criteria::IN; } } return $this->addUsingAlias(GamecurrencyTableMap::COL_AMOUNT, $amount, $comparison); }
php
{ "resource": "" }
q11758
GamecurrencyQuery.filterByMessage
train
public function filterByMessage($message = null, $comparison = null) { if (null === $comparison) { if (is_array($message)) { $comparison = Criteria::IN; } } return $this->addUsingAlias(GamecurrencyTableMap::COL_MESSAGE, $message, $comparison); }
php
{ "resource": "" }
q11759
GamecurrencyQuery.filterByDatetime
train
public function filterByDatetime($datetime = null, $comparison = null) { if (is_array($datetime)) { $useMinMax = false; if (isset($datetime['min'])) { $this->addUsingAlias(GamecurrencyTableMap::COL_DATETIME, $datetime['min'], Criteria::GREATER_EQUAL); $useMinMax = true; } if (isset($datetime['max'])) { $this->addUsingAlias(GamecurrencyTableMap::COL_DATETIME, $datetime['max'], Criteria::LESS_EQUAL); $useMinMax = true; } if ($useMinMax) { return $this; } if (null === $comparison) { $comparison = Criteria::IN; } } return $this->addUsingAlias(GamecurrencyTableMap::COL_DATETIME, $datetime, $comparison); }
php
{ "resource": "" }
q11760
PriceModifier.setPriceModification
train
public function setPriceModification($value) { if ($this->exists()) { $join = $this->manyMany('Reservations'); $table = end($join); $where = $this->getSourceQueryParam('Foreign.Filter'); $where["`{$this->baseTable()}ID`"] = $this->ID; SQLUpdate::create( "`{$table}`", array('`PriceModification`' => $value), $where )->execute(); } }
php
{ "resource": "" }
q11761
Reader.setOptions
train
public function setOptions(array $options) { foreach ($options as $opt => $val) { $this->setOption($opt, $val); } return $this; }
php
{ "resource": "" }
q11762
Reader.setOption
train
public function setOption($name, $value) { if (! in_array($name, $this->validOptions)) { throw new Error('Invalid option ' . $name . '. Valid options are : ' . join(', ', $this->validOptions)); } // Check duplicate fields in header if ('header' == $name) { $cnt = array_count_values($value); $duplicates = array(); foreach ($cnt as $f => $c) { if ($c > 1) { $duplicates[$f] = $c; } } if (sizeof($duplicates) > 0) { $msg = 'Duplicate fields found in header : ' . join(', ', array_keys($duplicates)); throw new Error($msg); } } $this->$name = $value; return $this; }
php
{ "resource": "" }
q11763
Reader.openFile
train
protected function openFile() { if (is_null($this->fp)) { $this->fp = @fopen($this->file, $this->mode); if (! $this->fp) { throw new Error('Unable to open ' . $this->file); } } return $this; }
php
{ "resource": "" }
q11764
Reader.readLine
train
protected function readLine() { if (! $this->valid()) { throw new Error('End of stream reached, no data to read'); } $this->currentData = fgetcsv($this->fp, null, $this->delimiter, $this->enclosure); // Check if EOF is reached if (false === $this->currentData) { return false; } elseif (array(null) == $this->currentData) { /* * An empty line in the csv file * is returned as an array containing a NULL value. */ if (! $this->ignoreEmptyLines) { throw new Error('Empty line found in file'); } return $this->readLine(); } $this->curLine++; if ($this->inputEncoding != $this->outputEncoding) { $inEnc = $this->inputEncoding; $outEnc = $this->outputEncoding; array_walk($this->currentData, function (&$str) use ($inEnc, $outEnc) { $str = mb_convert_encoding($str, $outEnc, $inEnc); }); } return $this->currentData; }
php
{ "resource": "" }
q11765
Reader.fetch
train
public function fetch() { if (! $this->valid()) { return false; } $line = $this->current(); $this->readLine(); return $line; }
php
{ "resource": "" }
q11766
Reader.getHtmlPreview
train
public function getHtmlPreview($numLines = 5) { $html = '<table>'; if ($this->header) { $html .= '<thead><tr>'; foreach ($this->header as $h) { $html .= '<th>' . htmlentities($h, ENT_QUOTES, 'UTF-8') . '</th>'; } $html .= '</tr></thead>'; } $html .= '<tbody>'; $i = 0; foreach ($this as $line) { if ($i >= $numLines) { break; } $html .= '<tr>'; foreach ($line as $v) { $html .= '<td>' . htmlentities($v, ENT_QUOTES, 'UTF-8') . '</td>'; } $html .= '</tr>'; $i++; } $html .= '</tbody></table>'; return $html; }
php
{ "resource": "" }
q11767
FiscalYearManager.getNextFiscalYear
train
public function getNextFiscalYear() { $fiscalYearId = $this->FiscalYear->lastFiscalYearByOrganization($this->AuthenticationManager->getCurrentUserOrganizationId()); $FiscalYear = $this->FiscalYear->byId($fiscalYearId); return json_encode(array('fiscalYear' => $FiscalYear->year + 1)); }
php
{ "resource": "" }
q11768
FmlManialink.addDictionaryInformation
train
protected function addDictionaryInformation() { $translations = []; $this->dictionary->removeAllEntries(); $this->getDictionaryInformation($this->manialink, $translations); foreach ($translations as $msgId => $messages) { foreach ($messages as $message) { $this->dictionary->setEntry($message['Lang'], $msgId, htmlspecialchars($message['Text'])); } } }
php
{ "resource": "" }
q11769
FmlManialink.getDictionaryInformation
train
protected function getDictionaryInformation($control, &$translations) { foreach ($control->getChildren() as $child) { if (($child instanceof Label || $child instanceof FmlLabel) && $child->getTranslate()) { $id = $child->getTextId(); if (!isset($this->cachedMessages[$id])) { $textId = 'exp_'.md5($id); $messages = $this->translationHelper->getTranslations($child->getTextId(), []); $translations[$textId] = $messages; $this->cachedMessages[$textId] = $messages; // Replaces with text id that can be used in the xml. $child->setTextId($textId); } else { $translations[$id] = $this->cachedMessages[$id]; } } else { if ($child instanceof Container) { $this->getDictionaryInformation($child, $translations); } } } }
php
{ "resource": "" }
q11770
TypeAbstract.configure
train
protected function configure( \Altamira\JsWriter\JsWriterAbstract $jsWriter ) { $confInstance = \Altamira\Config::getInstance(); $file = $confInstance['altamira.root'] . $confInstance['altamira.typeconfigpath']; $config = \parse_ini_file( $file, true ); $libConfig = $config[strtolower( $jsWriter->getLibrary() )]; $type = static::TYPE; $typeAttributes = preg_grep( "/$type\./i", array_keys( $libConfig ) ); foreach ( $typeAttributes as $key ) { $attribute = preg_replace( "/{$type}\./i", '', $key ); $this->{$attribute} = $libConfig[$key]; } }
php
{ "resource": "" }
q11771
TypeAbstract.getRendererOptions
train
public function getRendererOptions() { $opts = array(); foreach( $this->allowedRendererOptions as $opt ) { if( isset( $this->options[$opt] ) ) $opts[$opt] = $this->options[$opt]; } return $opts; }
php
{ "resource": "" }
q11772
NewBaseAdminModule.isUserAdmin
train
public function isUserAdmin() { $user = $this->getUsersDatabase(); $sr = $user->getById($this->_context->authenticatedUserId()); return ($sr->getField($user->getUserTable()->admin) == "yes"); }
php
{ "resource": "" }
q11773
JournalManager.getVoucherTypes
train
public function getVoucherTypes() { $voucherTypes = array(); $this->VoucherType->byOrganization($this->AuthenticationManager->getCurrentUserOrganizationId())->each(function($VoucherType) use (&$voucherTypes) { array_push($voucherTypes, array('label'=> $this->Lang->has($VoucherType->lang_key) ? $this->Lang->get($VoucherType->lang_key) : $VoucherType->name, 'value'=>$VoucherType->id)); }); return $voucherTypes; }
php
{ "resource": "" }
q11774
JournalManager.getFiscalYears
train
public function getFiscalYears() { $fiscalYears = array(); $this->FiscalYear->byOrganization($this->AuthenticationManager->getCurrentUserOrganizationId())->each(function($FiscalYear) use (&$fiscalYears) { array_push($fiscalYears, $FiscalYear->year); }); return $fiscalYears; }
php
{ "resource": "" }
q11775
JournalManager.getFirstAndLastDayOfCurrentMonth
train
public function getFirstAndLastDayOfCurrentMonth() { $Date = new Carbon('first day of this month'); $Date2 = new Carbon('last day of this month'); return array('userFormattedFrom' => $Date->format($this->Lang->get('form.phpShortDateFormat')), 'userFormattedTo' => $Date2->format($this->Lang->get('form.phpShortDateFormat')), 'databaseFormattedFrom' => $Date->format('Y-m-d'), 'databaseFormattedTo' => $Date2->format('Y-m-d')); }
php
{ "resource": "" }
q11776
JournalManager.updateJournalVoucherStatus
train
public function updateJournalVoucherStatus($id, $Journal = null, $JournalVoucher = null, $newStatus = null, $databaseConnectionName = null) { if(empty($newStatus)) { $debitSum = $this->JournalEntry->getJournalVoucherDebitSum($id, $databaseConnectionName); $creditSum = $this->JournalEntry->getJournalVoucherCreditSum($id, $databaseConnectionName); // var_dump((string) $debitSum, (string) $creditSum, $debitSum == $creditSum, round($debitSum) == round($creditSum), (string) $debitSum == (string) $creditSum ); // var_dump(round($debitSum, 2), round($creditSum, 2), round($debitSum, 2) == round($creditSum, 2)); if(round($debitSum, 2) == round($creditSum, 2)) { $status = 'B'; } else { $status = 'A'; } } else { $status = $newStatus; } if(empty($JournalVoucher)) { $JournalVoucher = $this->JournalVoucher->byId($id, $databaseConnectionName); } $currentStatus = $JournalVoucher->status; if($currentStatus != $status) { $this->JournalVoucher->update(array('status' => $status), $JournalVoucher, $databaseConnectionName); if(!empty($Journal)) { $this->Journal->attachDetail($Journal->id, array('field' => $this->Lang->get('decima-accounting::journal-management.status'), 'field_lang_key' => 'decima-accounting::journal-management.status', 'old_value' => $this->Lang->get('decima-accounting::journal-management.' . $currentStatus), 'new_value' => $this->Lang->get('decima-accounting::journal-management.' . $status)), $Journal); } } return $status; }
php
{ "resource": "" }
q11777
ClearTransientCache.clearTransients
train
protected function clearTransients() { // https://coderwall.com/p/yrqrkw/delete-all-existing-wordpress-transients-in-mysql-database // DELETE FROM `wp_options` WHERE `option_name` LIKE ('_transient_%'); // DELETE FROM `wp_options` WHERE `option_name` LIKE ('_site_transient_%'); Option::where('option_name', 'like', '_transient_%')->delete(); Option::where('option_name', 'like', '_site_transient_%')->delete(); return Option::where('option_name', 'like', '%_transient_%')->count(); }
php
{ "resource": "" }
q11778
Factory.createConnection
train
public function createConnection($maxAttempts = 3) { if (is_null($this->connection)) { $lastExcelption = $this->attemptConnection($maxAttempts); if (!is_null($lastExcelption)) { $this->console->getSfStyleOutput()->error( [ "Looks like your Dedicated server is either offline or has wrong config settings", "Error message: " . $lastExcelption->getMessage() ] ); $this->logger->error("Unable to open connection for Dedicated server", ["exception" => $lastExcelption]); throw $lastExcelption; } // Dispatch connected event. $event = new GenericEvent($this->connection); $this->eventDispatcher->dispatch(self::EVENT_CONNECTED, $event); } return $this->connection; }
php
{ "resource": "" }
q11779
Linker.isLinked
train
public function isLinked(string $host = null): bool { // link exists? // e.g: isLinked('localhost') if ($host && isset($this->links[$host])) { return ($this->links[$host]->status() === Link::STATUS_CONNECTED); } // without master/slave directives // e.g: isLinked() if (true !== $this->config->get('sharding')) { foreach ($this->links as $link) { return ($link->status() === Link::STATUS_CONNECTED); } } // with master/slave directives, check by host switch (trim((string) $host)) { // e.g: isLinked(), isLinked('master') case '': case Link::TYPE_MASTER: foreach ($this->links as $link) { if ($link->getType() == Link::TYPE_MASTER) { return ($link->status() === Link::STATUS_CONNECTED); } } break; // e.g: isLinked('slave1.mysql.local'), isLinked('slave') case Link::TYPE_SLAVE: foreach ($this->links as $link) { if ($link->getType() == Link::TYPE_SLAVE) { return ($link->status() === Link::STATUS_CONNECTED); } } break; } return false; }
php
{ "resource": "" }
q11780
Linker.getLink
train
public function getLink(string $host = null): ?Link { // link exists? // e.g: getLink('localhost') if ($host && isset($this->links[$host])) { return $this->links[$host]; } $host = trim((string) $host); // with master/slave directives if (true === $this->config->get('sharding')) { // e.g: getLink(), getLink('master'), getLink('master.mysql.local') if ($host == '' || $host == Link::TYPE_MASTER) { return Util::arrayRand( array_filter($this->links, function($link) { return $link->getType() == Link::TYPE_MASTER; })); } // e.g: getLink(), getLink('slave'), getLink('slave1.mysql.local') elseif ($host == Link::TYPE_SLAVE) { return Util::arrayRand( array_filter($this->links, function($link) { return $link->getType() == Link::TYPE_SLAVE; })); } } else { // e.g: getLink() if ($host == '') { return Util::arrayRand( array_filter($this->links, function($link) { return $link->getType() == Link::TYPE_SINGLE; })); } } }
php
{ "resource": "" }
q11781
Generator.getStub
train
protected function getStub($name) { if (is_file($path = base_path("resources/stubs/vendor/crud-generator/{$this->stubsGroup}/$name.stub"))) { return file_get_contents($path); } if (is_file($path = __DIR__."/../resources/stubs/{$this->stubsGroup}/$name.stub")) { return file_get_contents($path); } return ''; }
php
{ "resource": "" }
q11782
Generator.getLangPath
train
protected function getLangPath() { $sectionSegments = $this->sectionSegments; if ($this->langDir) { array_unshift($sectionSegments, $this->langDir); } return base_path('resources/lang/fr/'.implode('/', $sectionSegments).'.php'); }
php
{ "resource": "" }
q11783
Search.loadData
train
public static function loadData(): void { if (Search::$loaded === false) { $filePath = Search::$DATA_DIR."merged-ultraslim.json"; $contents = @file_get_contents($filePath); if ($contents === false) { throw new KBException("$filePath does not exist !"); } Search::$data = json_decode($contents); Search::$loaded = true; } }
php
{ "resource": "" }
q11784
Search.getByName
train
public static function getByName(string $name, int $type = Search::ANY): string { self::loadData(); $kbEntrys = self::getVariable($name); if (isset($kbEntrys->a)) { foreach ($kbEntrys->a as $kbEntry) { if ($type === Search::ANY) { return Search::$data->urls[$kbEntry->u]."#".$kbEntry->a; } elseif ($type === Search::MYSQL) { if ($kbEntry->t === Search::MYSQL) { return Search::$data->urls[$kbEntry->u]."#".$kbEntry->a; } } elseif ($type === Search::MARIADB) { if ($kbEntry->t === Search::MARIADB) { return Search::$data->urls[$kbEntry->u]."#".$kbEntry->a; } } } } throw new KBException("$name does not exist for this type of documentation !"); }
php
{ "resource": "" }
q11785
Search.getVariable
train
public static function getVariable(string $name): stdClass { self::loadData(); if (isset(Search::$data->vars->{$name})) { return Search::$data->vars->{$name}; } else { throw new KBException("$name does not exist !"); } }
php
{ "resource": "" }
q11786
Search.getVariableType
train
public static function getVariableType(string $name): string { self::loadData(); $kbEntry = self::getVariable($name); if (isset($kbEntry->t)) { return Search::$data->varTypes->{$kbEntry->t}; } else { throw new KBException("$name does have a known type !"); } }
php
{ "resource": "" }
q11787
AbstractController.notFound
train
public function notFound(Request $request, Response $response) { $handler = $this->container->get('notFoundHandler'); return $handler($request, $response); }
php
{ "resource": "" }
q11788
UpdaterWidgetFactory.setLocalRecord
train
public function setLocalRecord($nick, $checkpoints) { if (count($checkpoints) > 0) { $this->updateValue($this->playerGroup, 'LocalRecordCheckpoints', Builder::getArray($checkpoints, true)); $this->updateValue($this->playerGroup, 'LocalRecordHolder', Builder::escapeText($nick)); } else { $this->updateValue($this->playerGroup, 'LocalRecordCheckpoints', "Integer[Integer]"); $this->updateValue($this->playerGroup, 'LocalRecordHolder', Builder::escapeText("-")); } }
php
{ "resource": "" }
q11789
Strs.cutstr
train
public static function cutstr($string, $length, $suffix = true, $charset = "utf-8", $start = 0, $dot = ' ...') { $str = str_replace(['&amp;', '&quot;', '&lt;', '&gt;'], ['&', '"', '<', '>'], $string); if (function_exists("mb_substr")) { $strcut = mb_substr($str, $start, $length, $charset); if (mb_strlen($str, $charset) > $length) { return $suffix ? $strcut . $dot : $strcut; } return $strcut; } $re = []; $match = ['']; $re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/"; $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/"; $re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/"; $re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/"; preg_match_all($re[$charset], $str, $match); $slice = join("", array_slice($match[0], $start, $length)); $strcut = str_replace(['&', '"', '<', '>'], ['&amp;', '&quot;', '&lt;', '&gt;'], $slice); return $suffix ? $strcut . $dot : $strcut; }
php
{ "resource": "" }
q11790
Command.updateRoles
train
protected function updateRoles() { foreach ($this->roles() as $Role) { $this->authManager->add($Role); echo sprintf(' > role `%s` added.', $Role->name) . PHP_EOL; } }
php
{ "resource": "" }
q11791
Command.updateRules
train
protected function updateRules() { foreach ($this->rules() as $Rule) { $this->authManager->add($Rule); echo sprintf(' > rule `%s` added.', $Rule->name) . PHP_EOL; } }
php
{ "resource": "" }
q11792
Command.updatePermission
train
protected function updatePermission() { foreach ($this->permissions() as $Permission) { $this->authManager->add($Permission); echo sprintf(' > permission `%s` added.', $Permission->name) . PHP_EOL; } }
php
{ "resource": "" }
q11793
Command.updateInheritanceRoles
train
protected function updateInheritanceRoles() { foreach ($this->inheritanceRoles() as $role => $items) { foreach ($items as $item) { $this->authManager ->addChild(RbacFactory::Role($role), RbacFactory::Role($item)); echo sprintf(' > role `%s` inherited role `%s`.', $role, $item) . PHP_EOL; } } }
php
{ "resource": "" }
q11794
Command.updateInheritancePermissions
train
protected function updateInheritancePermissions() { foreach ($this->inheritancePermissions() as $role => $items) { foreach ($items as $item) { $this->authManager ->addChild(RbacFactory::Role($role), RbacFactory::Permission($item)); echo sprintf(' > role `%s` inherited permission `%s`.', $role, $item) . PHP_EOL; } } }
php
{ "resource": "" }
q11795
MelisInstallerModulesService.getModulePlugins
train
public function getModulePlugins($excludeModulesOnReturn = array()) { $modules = array(); $excludeModules = array_values($this->getCoreModules()); foreach($this->getAllModules() as $module) { if(!in_array($module, array_merge($excludeModules,$excludeModulesOnReturn))) { $modules[] = $module; } } return $modules; }
php
{ "resource": "" }
q11796
MelisInstallerModulesService.getMelisModules
train
public function getMelisModules() { $modules = array(); foreach($this->getAllModules() as $module) { if(strpos($module, 'Melis') !== false || strpos($module, 'melis') !== false) { $modules[] = $module; } } return $modules; }
php
{ "resource": "" }
q11797
TreeComponent.tree
train
public function tree($id = null) { Configure::write('debug', 0); if (!method_exists($this->_model, 'getTreeData')) { throw new InternalErrorException(__d( 'view_extension', 'Method "%s" is not exists in model "%s"', 'getTreeData()', $this->_model->name )); } if (!$this->_controller->request->is('ajax') || !$this->_controller->request->is('post') || !$this->_controller->RequestHandler->prefers('json')) { throw new BadRequestException(); } $data = [ [ 'text' => __d('view_extension', '&lt;None&gt;'), ] ]; $treeData = $this->_model->getTreeData($id); if (!empty($treeData)) { $data = $treeData; } $this->_controller->set(compact('data')); $this->_controller->set('_serialize', 'data'); }
php
{ "resource": "" }
q11798
InjectorBuilder.build
train
public function build(Injector $injector = null): Injector { if ($injector === null) { $injector = new Injector(); } foreach ($this->configs as $config) { $config->apply($injector); } return $injector; }
php
{ "resource": "" }
q11799
Where.where
train
public function where(...$arguments): self { switch (count($arguments)) { case 1: if (! is_array($arguments[0])) { throw new InvalidArgumentException; } foreach ($arguments[0] as $column => $data) { if (is_array($data)) { $this->where($column, ...$data); } else { $this->where($column, $data); } } return $this; break; case 2: $arguments = [$arguments[0], '=', $arguments[1], 'AND']; break; case 3: array_push($arguments, 'AND'); break; } return $this->setWhere([ 'column' => $arguments[0], 'value' => $arguments[2], 'operator' => $arguments[3], 'comparison' => $arguments[1] ]); }
php
{ "resource": "" }