_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q4600
Db.query
train
protected function query(string $sql, array $params = [], array $options = []): \PDOStatement { $options += [ Db::OPTION_FETCH_MODE => $this->getFetchArgs() ]; $stm = $this->getPDO()->prepare($sql); if ($options[Db::OPTION_FETCH_MODE]) { $stm->setFetchMode(...(...
php
{ "resource": "" }
q4601
Db.queryModify
train
protected function queryModify(string $sql, array $params = [], array $options = []): int { $options += [Db::OPTION_FETCH_MODE => 0]; $stm = $this->query($sql, $params, $options); return $stm->rowCount(); }
php
{ "resource": "" }
q4602
Db.queryID
train
protected function queryID(string $sql, array $params = [], array $options = []) { $options += [Db::OPTION_FETCH_MODE => 0]; $this->query($sql, $params, $options); $r = $this->getPDO()->lastInsertId(); return is_numeric($r) ? (int)$r : $r; }
php
{ "resource": "" }
q4603
Db.queryDefine
train
protected function queryDefine(string $sql, array $options = []) { $options += [Db::OPTION_FETCH_MODE => 0]; $this->query($sql, [], $options); }
php
{ "resource": "" }
q4604
Db.escape
train
public function escape($identifier): string { if ($identifier instanceof Literal) { return $identifier->getValue($this); } return '`'.str_replace('`', '``', $identifier).'`'; }
php
{ "resource": "" }
q4605
Db.prefixTable
train
protected function prefixTable($table, bool $escape = true): string { if ($table instanceof Identifier) { return $escape ? $table->escape($this) : (string)$table; } else { $table = $this->px.$table; return $escape ? $this->escape($table) : $table; } }
php
{ "resource": "" }
q4606
Db.stripPrefix
train
protected function stripPrefix(string $table): string { $len = strlen($this->px); if (strcasecmp(substr($table, 0, $len), $this->px) === 0) { $table = substr($table, $len); } return $table; }
php
{ "resource": "" }
q4607
ThemeHandle.getThemesFromDir
train
public function getThemesFromDir() { $themeList = array(); $themePath = Yii::getPathOfAlias('webroot.themes'); $themes = scandir($themePath); foreach($themes as $theme) { $themeName = $this->urlTitle($theme); $themeFile = $themePath.'/'.$theme.'/'.$themeName.'.yaml'; if(file_exists($themeFi...
php
{ "resource": "" }
q4608
ThemeHandle.cacheThemeConfig
train
public function cacheThemeConfig($return=false) { $themes = $this->getThemesFromDb(); $arrayTheme = array(); foreach($themes as $theme) { if(!in_array($theme->folder, $arrayTheme)) $arrayTheme[] = $theme->folder; } if($return == false) { $filePath = Yii::getPathOfAlias('application.c...
php
{ "resource": "" }
q4609
ThemeHandle.getThemeConfig
train
public function getThemeConfig($theme) { Yii::import('mustangostang.spyc.Spyc'); define('DS', DIRECTORY_SEPARATOR); $themeName = $this->urlTitle($theme); $configPath = Yii::getPathOfAlias('webroot.themes.'.$theme).DS.$themeName.'.yaml'; if(file_exists($configPath)) return Spyc::YAMLLoad($config...
php
{ "resource": "" }
q4610
ThemeHandle.deleteThemeDb
train
public function deleteThemeDb($theme) { if($theme != null) { $model = OmmuThemes::model()->findByAttributes(array('folder'=>$theme)); if($model != null) $model->delete(); else return false; } else return false; }
php
{ "resource": "" }
q4611
ThemeHandle.setThemes
train
public function setThemes() { $installedTheme = $this->getThemesFromDir(); $cacheTheme = file(Yii::getPathOfAlias('application.config').'/cache_theme.php'); $toBeInstalled = array(); $caches = array(); foreach($cacheTheme as $val) { $caches[] = $val; } if(!$installedTheme) $install...
php
{ "resource": "" }
q4612
PhotosAlbumsTable.afterSave
train
public function afterSave(Event $event, Entity $entity, ArrayObject $options) { //Creates the folder (new Folder($entity->path, true, 0777)); parent::afterSave($event, $entity, $options); }
php
{ "resource": "" }
q4613
CreateAdminCommand.execute
train
public function execute(Arguments $args, ConsoleIo $io) { $command = new AddUserCommand; return $command->run(['--group', 1] + $args->getOptions(), $io); }
php
{ "resource": "" }
q4614
ReqAttr.getReferrer
train
public static function getReferrer(ServerRequestInterface $request) { if ($referrer = $request->getAttribute(self::REFERRER)) { return $referrer; } if ($referrer = Respond::session()->get(self::REFERRER)) { return $referrer; } $info = $request->getServ...
php
{ "resource": "" }
q4615
ReqAttr.withBasePath
train
public static function withBasePath(ServerRequestInterface $request, $basePath, $pathInfo = null) { $path = $request->getUri()->getPath(); if (strpos($path, $basePath) !== 0) { throw new \InvalidArgumentException; } $pathInfo = is_null($pathInfo) ? substr($path, strlen($b...
php
{ "resource": "" }
q4616
ReqAttr.getPathInfo
train
public static function getPathInfo(ServerRequestInterface $request) { return $request->getAttribute(self::PATH_INFO, null) ?: $request->getUri()->getPath(); }
php
{ "resource": "" }
q4617
QueueManager.run
train
public function run($eventname, $count) { $queueEvents = $this->loadQueue($eventname, $count); if ($queueEvents->numRows) { while ($queueEvents->next()) { if ($this->checkInterval($queueEvents)) { $this->setStartTime($queueEvents->id); ...
php
{ "resource": "" }
q4618
QueueManager.setError
train
protected function setError($id) { $queueEvent = new QueueSetErrorEvent(); $queueEvent->setId($id); $this->dispatcher->dispatch($queueEvent::NAME, $queueEvent); }
php
{ "resource": "" }
q4619
QueueManager.saveJobResult
train
protected function saveJobResult($id, $jobEvent) { if ($jobEvent) { $queueEvent = new QueueSaveJobResultEvent(); $queueEvent->setId($id); $queueEvent->setData($jobEvent); $this->dispatcher->dispatch($queueEvent::NAME, $queueEvent); } }
php
{ "resource": "" }
q4620
QueueManager.dispatch
train
protected function dispatch($queueEvent) { $event = urldecode($queueEvent->data); $event = unserialize($event); if ($event) { $this->dispatcher->dispatch($event::NAME, $event); if ($event->getHasError()) { $this->setError($queueEvent->id); ...
php
{ "resource": "" }
q4621
MessageMapper.markAsRead
train
public function markAsRead(int $messageId) { $this->sql = 'update message set is_read = \'Y\' where id = ?'; $this->bindValues[] = $messageId; return $this->execute(); }
php
{ "resource": "" }
q4622
MessageMapper.markAsUnread
train
public function markAsUnread(int $messageId) { $this->sql = 'update message set is_read = \'N\' where id = ?'; $this->bindValues[] = $messageId; return $this->execute(); }
php
{ "resource": "" }
q4623
DateInterval.fromSpecification
train
public static function fromSpecification(string $specification) : self { $microseconds = 0; // Parse the microsecond component. if (false !== ($position = stripos($specification, 'U'))) { // Step backwards consuming digits until we hit a duration designator. ...
php
{ "resource": "" }
q4624
DateInterval.diff
train
public static function diff(DateTime $a, DateTime $b, bool $absolute = false) : self { $microseconds = $b->microsecond() - $a->microsecond(); if ($absolute) { $microseconds = abs($microseconds); } $diff = $a->toInternalDateTime()->diff($b->toInternalDate...
php
{ "resource": "" }
q4625
DateInterval.fromComponents
train
public static function fromComponents( int $years = null, int $months = null, int $weeks = null, int $days = null, int $hours = null, int $minutes = null, int $seconds = null, int $microseconds = null ) : self { if (!($years || $months || $week...
php
{ "resource": "" }
q4626
DateInterval.format
train
public function format(string $format) : string { // Replace microseconds first so they become literals. // Ignore any escaped microsecond identifiers. $format = preg_replace_callback( // Starting at the start of the string or the first non % character, // consume pai...
php
{ "resource": "" }
q4627
DateInterval.totalMicroseconds
train
public function totalMicroseconds() : int { if (null === $this->totalMicroseconds) { $reference = DateTime::now(); $end = $reference->add($this); $this->totalMicroseconds = $end->timestampWithMicrosecond() - $reference->timestampWithMicrosecond(); } ...
php
{ "resource": "" }
q4628
DateInterval.clone
train
private static function clone(\DateInterval $interval) { $specification = $interval->format('P%yY%mM%dDT%hH%iM%sS'); $clone = new \DateInterval($specification); $clone->days = $interval->days; $clone->invert = $interval->invert; return $clone; ...
php
{ "resource": "" }
q4629
PostsCategoriesController.view
train
public function view($slug = null) { //The category can be passed as query string, from a widget if ($this->request->getQuery('q')) { return $this->redirect([$this->request->getQuery('q')]); } $page = $this->request->getQuery('page', 1); //Sets the cache name ...
php
{ "resource": "" }
q4630
LogsController.getPath
train
protected function getPath($filename, $serialized) { if ($serialized) { $filename = pathinfo($filename, PATHINFO_FILENAME) . '_serialized.log'; } return LOGS . $filename; }
php
{ "resource": "" }
q4631
LogsController.read
train
protected function read($filename, $serialized) { $log = $this->getPath($filename, $serialized); is_readable_or_fail($log); $log = file_get_contents($log); return $serialized ? @unserialize($log) : trim($log); }
php
{ "resource": "" }
q4632
LogsController.view
train
public function view($filename) { $serialized = false; if ($this->request->getQuery('as') === 'serialized') { $serialized = true; $this->viewBuilder()->setTemplate('view_as_serialized'); } $content = $this->read($filename, $serialized); $this->set(c...
php
{ "resource": "" }
q4633
LogsController.download
train
public function download($filename) { return $this->response->withFile($this->getPath($filename, false), ['download' => true]); }
php
{ "resource": "" }
q4634
LogsController.delete
train
public function delete($filename) { $this->request->allowMethod(['post', 'delete']); $success = (new File($this->getPath($filename, false)))->delete(); $serialized = $this->getPath($filename, true); //Deletes the serialized log copy, if it exists if (file_exists($serialized...
php
{ "resource": "" }
q4635
PhotosController.view
train
public function view($slug = null, $id = null) { //This allows backward compatibility for URLs like `/photo/11` if (empty($slug)) { $slug = $this->Photos->findById($id) ->contain([$this->Photos->Albums->getAlias() => ['fields' => ['slug']]]) ->extract('alb...
php
{ "resource": "" }
q4636
PhotosController.preview
train
public function preview($id = null) { $photo = $this->Photos->findPendingById($id) ->select(['id', 'album_id', 'filename']) ->contain([$this->Photos->Albums->getAlias() => ['fields' => ['id', 'title', 'slug']]]) ->firstOrFail(); $this->set(compact('photo')); ...
php
{ "resource": "" }
q4637
MultiCurrencyBank.checkCurrencies
train
protected function checkCurrencies($currencies) { foreach ((array) $currencies as $currency) { if (!$this->hasCurrency($currency)) { throw new InvalidCurrencyException(sprintf('"%s" is an unknown currency code.', $currency)); } } }
php
{ "resource": "" }
q4638
MultiCurrencyBank.getRate
train
public function getRate($fromCurrency, $toCurrency = null) { if (null === $toCurrency) { $toCurrency = $this->getBaseCurrency(); } $this->checkCurrencies(array($fromCurrency, $toCurrency)); return $this->exchanger->getRate($fromCurrency, $toCurrency); }
php
{ "resource": "" }
q4639
MultiCurrencyBank.reduce
train
public function reduce(MoneyInterface $source, $toCurrency = null) { if (null === $toCurrency) { $toCurrency = $this->getBaseCurrency(); } $this->checkCurrencies($toCurrency); return $source->reduce($this, $toCurrency); }
php
{ "resource": "" }
q4640
MultiCurrencyBank.createMoney
train
public function createMoney($amount, $currency = null) { if (null === $currency) { $currency = $this->getBaseCurrency(); } $this->checkCurrencies($currency); $class = $this->moneyClass; return new $class($amount, $currency); }
php
{ "resource": "" }
q4641
Auth.verifyCredentials
train
public function verifyCredentials($sIdentifier, $sPassword) { // Look up the user, how we do so depends on the login mode that the app is using $oUserModel = Factory::model('User', 'nails/module-auth'); $oPasswordModel = Factory::model('UserPassword', 'nails/module-auth'); $oUse...
php
{ "resource": "" }
q4642
Auth.logout
train
public function logout() { $oUserModel = Factory::model('User', 'nails/module-auth'); $oUserModel->clearRememberCookie(); // -------------------------------------------------------------------------- // null the remember_code so that auto-logins stop $oDb = Factory::servic...
php
{ "resource": "" }
q4643
Auth.mfaTokenGenerate
train
public function mfaTokenGenerate($iUserId) { $oPasswordModel = Factory::model('UserPassword', 'nails/module-auth'); $oNow = Factory::factory('DateTime'); $oInput = Factory::service('Input'); $oDb = Factory::service('Database'); $sSalt = $oPass...
php
{ "resource": "" }
q4644
Auth.mfaTokenValidate
train
public function mfaTokenValidate($iUserId, $sSalt, $sToken, $sIp) { $oDb = Factory::service('Database'); $oDb->where('user_id', $iUserId); $oDb->where('salt', $sSalt); $oDb->where('token', $sToken); $oToken = $oDb->get(NAILS_DB_PREFIX . 'user_auth_two_factor_token')->row();...
php
{ "resource": "" }
q4645
Auth.mfaTokenDelete
train
public function mfaTokenDelete($iTokenId) { $oDb = Factory::service('Database'); $oDb->where('id', $iTokenId); $oDb->delete(NAILS_DB_PREFIX . 'user_auth_two_factor_token'); return (bool) $oDb->affected_rows(); }
php
{ "resource": "" }
q4646
Auth.mfaQuestionGet
train
public function mfaQuestionGet($iUserId) { $oDb = Factory::service('Database'); $oInput = Factory::service('Input'); $oDb->where('user_id', $iUserId); $oDb->order_by('last_requested', 'DESC'); $aQuestions = $oDb->get(NAILS_DB_PREFIX . 'user_auth_two_factor_question')->res...
php
{ "resource": "" }
q4647
Auth.mfaQuestionValidate
train
public function mfaQuestionValidate($iQuestionId, $iUserId, $answer) { $oDb = Factory::service('Database'); $oDb->select('answer, salt'); $oDb->where('id', $iQuestionId); $oDb->where('user_id', $iUserId); $oQuestion = $oDb->get(NAILS_DB_PREFIX . 'user_auth_two_factor_question...
php
{ "resource": "" }
q4648
Auth.mfaQuestionSet
train
public function mfaQuestionSet($iUserId, $aData, $bClearOld = true) { // Check input foreach ($aData as $oDatum) { if (empty($oDatum->question) || empty($oDatum->answer)) { $this->setError('Malformed question/answer data.'); return false; } ...
php
{ "resource": "" }
q4649
Auth.mfaDeviceSecretGet
train
public function mfaDeviceSecretGet($iUserId) { $oDb = Factory::service('Database'); $oEncrypt = Factory::service('Encrypt'); $oDb->where('user_id', $iUserId); $oDb->limit(1); $aResult = $oDb->get(NAILS_DB_PREFIX . 'user_auth_two_factor_device_secret')->result(); ...
php
{ "resource": "" }
q4650
Auth.mfaDeviceSecretGenerate
train
public function mfaDeviceSecretGenerate($iUserId, $sExistingSecret = null) { // Get an identifier for the user $oUserModel = Factory::model('User', 'nails/module-auth'); $oUser = $oUserModel->getById($iUserId); if (!$oUser) { $this->setError('User does not exist.')...
php
{ "resource": "" }
q4651
Auth.mfaDeviceSecretValidate
train
public function mfaDeviceSecretValidate($iUserId, $sSecret, $iCode) { // Tidy up codes so that they only contain digits $sCode = preg_replace('/[^\d]/', '', $iCode); // New instance of the authenticator $oGoogleAuth = new GoogleAuthenticator(); if ($oGoogleAuth->checkCode...
php
{ "resource": "" }
q4652
Auth.mfaDeviceCodeValidate
train
public function mfaDeviceCodeValidate($iUserId, $sCode) { // Get the user's secret $oSecret = $this->mfaDeviceSecretGet($iUserId); if (!$oSecret) { $this->setError('Invalid User'); return false; } // Has the code been used before? $oDb = Fa...
php
{ "resource": "" }
q4653
Referrer.saveReferrer
train
private function saveReferrer(ServerRequestInterface $request) { Respond::session()->set(self::REFERRER, $request->getUri()->__toString()); }
php
{ "resource": "" }
q4654
ViewData.setMessage
train
public function setMessage($type, $message) { if (!is_null($message)) { $this->messages[] = [ 'message' => $message, 'type' => $type, ]; } return $this; }
php
{ "resource": "" }
q4655
Apache.modules
train
public function modules() { $modules = []; foreach ($this->modulesToCheck as $module) { $modules[$module] = in_array('mod_' . $module, apache_get_modules()); } return $modules; }
php
{ "resource": "" }
q4656
App.brokenLinksColumnSorting
train
public function brokenLinksColumnSorting() { add_filter('posts_fields', function ($fields, $query) { if ($query->get('orderby') !== 'broken-links') { return $fields; } global $wpdb; $fields .= ", ( SELECT COUNT(*) ...
php
{ "resource": "" }
q4657
App.addListTablePage
train
public function addListTablePage() { add_submenu_page( 'options-general.php', 'Broken links', 'Broken links', 'edit_posts', 'broken-links-detector', function () { \BrokenLinkDetector\App::checkInstall(); ...
php
{ "resource": "" }
q4658
App.checkSavedPost
train
public function checkSavedPost($data, $postarr) { remove_action('wp_insert_post_data', array($this, 'checkSavedPost'), 10, 2); $detector = new \BrokenLinkDetector\InternalDetector($data, $postarr); return $data; }
php
{ "resource": "" }
q4659
App.deleteBrokenLinks
train
public function deleteBrokenLinks($postId) { global $wpdb; $tableName = self::$dbTable; $wpdb->delete($tableName, array('post_id' => $postId), array('%d')); }
php
{ "resource": "" }
q4660
UsersTable.findAuth
train
public function findAuth(Query $query, array $options) { return $query->contain('Groups', function (Query $q) { return $q->select(['name']); }); }
php
{ "resource": "" }
q4661
UsersTable.findBanned
train
public function findBanned(Query $query, array $options) { return $query->where([sprintf('%s.banned', $this->getAlias()) => true]); }
php
{ "resource": "" }
q4662
UsersTable.findPending
train
public function findPending(Query $query, array $options) { return $query->where([ sprintf('%s.active', $this->getAlias()) => false, sprintf('%s.banned', $this->getAlias()) => false, ]); }
php
{ "resource": "" }
q4663
UsersTable.getActiveList
train
public function getActiveList() { return $this->find() ->select(['id', 'first_name', 'last_name']) ->where([sprintf('%s.active', $this->getAlias()) => true]) ->order(['username' => 'ASC']) ->formatResults(function (ResultSet $results) { return ...
php
{ "resource": "" }
q4664
UsersTable.validationDoNotRequirePresence
train
public function validationDoNotRequirePresence(UserValidator $validator) { //No field is required foreach ($validator->getIterator() as $field => $rules) { $validator->requirePresence($field, false); } return $validator; }
php
{ "resource": "" }
q4665
PostsTagsWidgetsCell.getFontSizes
train
protected function getFontSizes(array $style = []) { //Maximum and minimun font sizes we want to use $maxFont = empty($style['maxFont']) ? 40 : $style['maxFont']; $minFont = empty($style['minFont']) ? 12 : $style['minFont']; is_true_or_fail($maxFont > $minFont, __d('me_cms', 'Invalid...
php
{ "resource": "" }
q4666
PostsTagsWidgetsCell.popular
train
public function popular( $limit = 10, $prefix = '#', $render = 'cloud', $shuffle = true, $style = ['maxFont' => 40, 'minFont' => 12] ) { $this->viewBuilder()->setTemplate(sprintf('popular_as_%s', $render)); //Returns on tags index if ($this->request->...
php
{ "resource": "" }
q4667
ComposerListener.registerPackage
train
public static function registerPackage(Event $event) { $installedPackage = $event->getOperation()->getPackage(); if (!self::isBundle($installedPackage)) { return; } self::enablePackage($installedPackage); }
php
{ "resource": "" }
q4668
Redirect.toPath
train
public function toPath($path) { $uri = $this->request->getUri()->withPath($path); return $this->toAbsoluteUri($uri); }
php
{ "resource": "" }
q4669
PostsWidgetsCell.months
train
public function months($render = 'form') { $this->viewBuilder()->setTemplate(sprintf('months_as_%s', $render)); //Returns on posts index if ($this->request->isUrl(['_name' => 'posts'])) { return; } $query = $this->Posts->find('active'); $time = $query->f...
php
{ "resource": "" }
q4670
DisableElementsCapableFormSettings.filterArrayStrings
train
protected function filterArrayStrings($array, $search, $replace) { $return = array(); foreach ((array)$array as $key => $value) { $key = str_replace($search, $replace, $key); $value = is_array($value) ? $this->filterArrayStrings($value, $search, $replace) ...
php
{ "resource": "" }
q4671
Escaper.escapeCharacterClass
train
public function escapeCharacterClass($char) { return (isset($this->inCharacterClass[$char])) ? $this->inCharacterClass[$char] : $char; }
php
{ "resource": "" }
q4672
Escaper.escapeLiteral
train
public function escapeLiteral($char) { return (isset($this->inLiteral[$char])) ? $this->inLiteral[$char] : $char; }
php
{ "resource": "" }
q4673
RedisService.add
train
public function add($id, $data = 1) { try { return $this->resource->hSet(static::CACHE_KEY, $id, $data); } catch (ConnectionException $e) { return false; } }
php
{ "resource": "" }
q4674
RedisService.exists
train
public function exists($id) { try { return !!$this->resource->hExists(static::CACHE_KEY, $id); } catch (ConnectionException $e) { return false; } }
php
{ "resource": "" }
q4675
RedisService.remove
train
public function remove($id) { try { return $this->resource->hDel(static::CACHE_KEY, $id); } catch (ConnectionException $e) { return false; } }
php
{ "resource": "" }
q4676
MergeSuffix.hasMatchingSuffix
train
protected function hasMatchingSuffix(array $strings) { $suffix = end($strings[1]); foreach ($strings as $string) { if (end($string) !== $suffix) { return false; } } return ($suffix !== false); }
php
{ "resource": "" }
q4677
MergeSuffix.pop
train
protected function pop(array $strings) { $cnt = count($strings); $i = $cnt; while (--$i >= 0) { array_pop($strings[$i]); } // Remove empty elements then prepend one back at the start of the array if applicable $strings = array_filter($strings); if (count($strings) < $cnt) { array_unshift($st...
php
{ "resource": "" }
q4678
User.getSearch
train
public function getSearch($aData = []) { if (!userHasPermission('admin:auth:accounts:browse')) { $oHttpCodes = Factory::service('HttpCodes'); throw new ApiException( 'You are not authorised to search users', $oHttpCodes::STATUS_UNAUTHORIZED ...
php
{ "resource": "" }
q4679
User.getEmail
train
public function getEmail() { $oHttpCodes = Factory::service('HttpCodes'); if (!userHasPermission('admin:auth:accounts:browse')) { throw new ApiException( 'You are not authorised to browse users', $oHttpCodes::STATUS_UNAUTHORIZED ); } ...
php
{ "resource": "" }
q4680
User.postRemap
train
public function postRemap() { $oUri = Factory::service('Uri'); $iItemId = (int) $oUri->segment(4); if ($iItemId && $iItemId != activeUSer('id') && !userHasPermission('admin:auth:accounts:editothers')) { return [ 'status' => 401, 'error' => 'You...
php
{ "resource": "" }
q4681
User.formatObject
train
public function formatObject($oObj) { return [ 'id' => $oObj->id, 'first_name' => $oObj->first_name, 'last_name' => $oObj->last_name, 'email' => $oObj->email, ]; }
php
{ "resource": "" }
q4682
FileUploadHandler.upload
train
public function upload(string $fileKey) { if (!isset($this->uploadedFiles[$fileKey])) { throw new Exception('PitonCMS: File upload key does not exist'); } $file = $this->uploadedFiles[$fileKey]; if ($file->getError() === UPLOAD_ERR_OK) { // Get file name and...
php
{ "resource": "" }
q4683
FileUploadHandler.getErrorMessage
train
public function getErrorMessage() { switch ($this->error) { case UPLOAD_ERR_INI_SIZE: $message = "The uploaded file exceeds the upload_max_filesize directive in php.ini"; break; case UPLOAD_ERR_FORM_SIZE: $message = "The uploaded file e...
php
{ "resource": "" }
q4684
FileUploadHandler.makeFileDirectory
train
protected function makeFileDirectory($directoryPath) { $filePath = $this->publicRoot . $directoryPath; // Create the path if the directory does not exist if (!is_dir($filePath)) { try { mkdir($filePath, 0775, true); return true; } catc...
php
{ "resource": "" }
q4685
Utf8.charsToCodepointsWithSurrogates
train
protected function charsToCodepointsWithSurrogates(array $chars) { $codepoints = []; foreach ($chars as $char) { $cp = $this->cp($char); if ($cp < 0x10000) { $codepoints[] = $cp; } else { $codepoints[] = 0xD7C0 + ($cp >> 10); $codepoints[] = 0xDC00 + ($cp & 0x3FF); } } retur...
php
{ "resource": "" }
q4686
Utf8.cp
train
protected function cp($char) { $cp = ord($char[0]); if ($cp >= 0xF0) { $cp = ($cp << 18) + (ord($char[1]) << 12) + (ord($char[2]) << 6) + ord($char[3]) - 0x3C82080; } elseif ($cp >= 0xE0) { $cp = ($cp << 12) + (ord($char[1]) << 6) + ord($char[2]) - 0xE2080; } elseif ($cp >= 0xC0) { $cp = ($c...
php
{ "resource": "" }
q4687
Page.getPublishedStatus
train
public function getPublishedStatus() { $today = date('Y-m-d'); if (empty($this->published_date)) { return 'draft'; } elseif ($this->published_date > $today) { return 'pending'; } elseif ($this->published_date <= $today) { return 'published'; ...
php
{ "resource": "" }
q4688
AttachmentAwareTrait.addAttachment
train
public function addAttachment($attachment, $group = 'contents') { if (!$attachment instanceof AttachableInterface && !$attachment instanceof ModelInterface) { return false; } $join = $this->modelFactory()->create(Join::class); $objId = $this->id(); $objType = ...
php
{ "resource": "" }
q4689
AttachmentAwareTrait.removeAttachmentJoins
train
public function removeAttachmentJoins() { $joinProto = $this->modelFactory()->get(Join::class); $loader = $this->collectionLoader(); $loader ->setModel($joinProto) ->addFilter('object_type', $this->objType()) ->addFilter('object_id', $this->id()); ...
php
{ "resource": "" }
q4690
Pager.generateLinksCenter
train
public function generateLinksCenter(string $page = null, string $ignoredKeys = null, $linksClassName = null): string { // only one page? $totalPages = $this->totalPages; if ($totalPages == 1) { return $this->template(['<a class="current" href="#">1</a>'], $linksClassName, true); ...
php
{ "resource": "" }
q4691
GetStartAndEndDateTrait.getStartAndEndDate
train
protected function getStartAndEndDate($date) { $year = $month = $day = null; //Sets the start date if (in_array($date, ['today', 'yesterday'])) { $start = Time::parse($date); } else { list($year, $month, $day) = array_replace([null, null, null], explode('/', ...
php
{ "resource": "" }
q4692
User.addTeams
train
public function addTeams(ArrayCollection $teams) { foreach ($teams as $team) { $team->addUser($this); $this->teams->add($team); } }
php
{ "resource": "" }
q4693
User.removeTeams
train
public function removeTeams(ArrayCollection $teams) { foreach ($teams as $team) { $team->removeUser($this); $this->teams->removeElement($team); } }
php
{ "resource": "" }
q4694
XMLTransformer.transform
train
public static function transform($xslFileName, DOMDocument $xml) { $xsl = new DOMDocument; $xsl->load(__DIR__.'/../../xslt/'.$xslFileName.'.xsl'); $proc = new XSLTProcessor; $proc->importStyleSheet($xsl); libxml_use_internal_errors(true); $result = $proc->transform...
php
{ "resource": "" }
q4695
PostsCategoriesController.delete
train
public function delete($id = null) { $this->request->allowMethod(['post', 'delete']); $category = $this->PostsCategories->get($id); //Before deleting, it checks if the category has some posts if (!$category->post_count) { $this->PostsCategories->deleteOrFail($category);...
php
{ "resource": "" }
q4696
TableQuery.setOption
train
protected function setOption($name, $value, $reset = false) { $changed = !isset($this->options[$name]) || $this->options[$name] !== $value; if ($changed && $reset) { $this->data = null; } $this->options[$name] = $value; return $this; }
php
{ "resource": "" }
q4697
SessionStorage.forge
train
public static function forge($name, $cookie = null) { $factory = new SessionFactory(); $cookie = $cookie ?: $_COOKIE; $session = $factory->newInstance($cookie); $self = new self($session); $self->start(); return $self->withStorage($name); }
php
{ "resource": "" }
q4698
SessionStorage.withStorage
train
public function withStorage($name) { $self = clone($this); $self->segment = $this->session->getSegment($name); return $self; }
php
{ "resource": "" }
q4699
Login.index
train
public function index() { // If you're logged in you shouldn't be accessing this method if (isLoggedIn()) { redirect($this->data['return_to']); } // -------------------------------------------------------------------------- // If there's POST data attempt to l...
php
{ "resource": "" }