_id stringlengths 2 7 | title stringlengths 3 151 | partition stringclasses 3
values | text stringlengths 83 13k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q8800 | CheckCommand.getParameter | train | public function getParameter($name, $default = null)
{
if (!$this->getContainer()->hasParameter($name)) {
return $default;
}
return $this->getContainer()->getParameter($name);
} | php | {
"resource": ""
} |
q8801 | ActiveRecordTrait.attributes | train | public function attributes( ?array $only = null, ?array $except = null, ?bool $schemaOnly = false )
{
$names = array_keys( static::getTableSchema()->columns );
if( !$schemaOnly ) {
$class = new \ReflectionClass( $this );
foreach( $class->getProperties( \ReflectionProperty::IS_PUBLIC ) as $property ) {
if( !$property->isStatic() ) {
$names[] = $property->getName();
}
}
}
$names = array_unique( $names );
if( $only ) {
$names = array_intersect( $only, $names );
}
if( $except ) {
$names = array_diff( $names, $except );
}
return $names;
} | php | {
"resource": ""
} |
q8802 | PdoWrapper.getPDO | train | public static function getPDO($dsn, $username, $password, $settings = ['attributes' => []])
{
// if not set self pdo object property or pdo set as null
if (!isset(self::$PDO) || (self::$PDO !== null)) {
self::$PDO = new self($dsn, $username, $password, $settings); // set class pdo property with new connection
}
// return class property object
return self::$PDO;
} | php | {
"resource": ""
} |
q8803 | PdoWrapper.result | train | public function result($row = 0)
{
return isset($this->results[$row]) ? $this->results[$row] : false;
} | php | {
"resource": ""
} |
q8804 | PdoWrapper.error | train | public function error($msg)
{
file_put_contents($this->config['logDir'] . self::LOG_FILE, date('Y-m-d h:m:s') . ' :: ' . $msg . "\n",
FILE_APPEND);
// log set as true
if ($this->log) {
// show executed query with error
$this->showQuery();
// die code
$this->helper()->errorBox($msg);
}
throw new \PDOException($msg);
} | php | {
"resource": ""
} |
q8805 | PdoWrapper.showQuery | train | public function showQuery($logfile = false)
{
if (!$logfile) {
echo "<div style='color:#990099; border:1px solid #777; padding:2px; background-color: #E5E5E5;'>";
echo " Executed Query -> <span style='color:#008000;'> ";
echo $this->helper()->formatSQL($this->interpolateQuery());
echo '</span></div>';
}
file_put_contents($this->config['logDir'] . self::LOG_FILE,
date('Y-m-d h:m:s') . ' :: ' . $this->interpolateQuery() . "\n", FILE_APPEND);
return $this;
} | php | {
"resource": ""
} |
q8806 | PdoWrapper.getFieldFromArrayKey | train | public function getFieldFromArrayKey($array_key)
{
// get table column from array key
$key_array = explode(' ', $array_key);
// check no of chunk
return (count($key_array) == '2') ? $key_array[0] : ((count($key_array) > 2) ? $key_array[1] : $key_array[0]);
} | php | {
"resource": ""
} |
q8807 | PdoWrapper.insert | train | public function insert($table, $data = [])
{
// check if table name not empty
if (!empty($table)) {
// and array data not empty
if (count($data) > 0 && is_array($data)) {
// get array insert data in temp array
$tmp = [];
foreach ($data as $f => $v) {
$tmp[] = ":s_$f";
}
// make name space param for pdo insert statement
$sNameSpaceParam = implode(',', $tmp);
// unset temp var
unset($tmp);
// get insert fields name
$sFields = implode(',', array_keys($data));
// set pdo insert statement in class property
$this->sql = "INSERT INTO `$table` ($sFields) VALUES ($sNameSpaceParam);";
// pdo prepare statement
$this->STH = $this->prepare($this->sql);
// set class where property with array data
$this->data = $data;
// bind pdo param
$this->_bindPdoNameSpace($data);
// use try catch block to get pdo error
try {
// execute pdo statement
if ($this->STH->execute()) {
// set class property with last insert id
$this->lastId = $this->lastInsertId();
// close pdo
$this->STH->closeCursor();
// return this object
return $this;
} else {
self::error($this->STH->errorInfo());
}
} catch (\PDOException $e) {
// get pdo error and pass on error method
self::error($e->getMessage() . ': ' . __LINE__);
}
} else {
self::error('Data not in valid format..');
}
} else {
self::error('Table name not found..');
}
} | php | {
"resource": ""
} |
q8808 | PdoWrapper.insertBatch | train | public function insertBatch($table, $data = [], $safeModeInsert = true)
{
// PDO transactions start
$this->start();
// check if table name not empty
if (!empty($table)) {
// and array data not empty
if (count($data) > 0 && is_array($data)) {
// get array insert data in temp array
$tmp = [];
foreach ($data[0] as $f => $v) {
$tmp[] = ":s_$f";
}
// make name space param for pdo insert statement
$sNameSpaceParam = implode(', ', $tmp);
// unset temp var
unset($tmp);
// get insert fields name
$sFields = implode(', ', array_keys($data[0]));
// handle safe mode. If it is set as false means user not using bind param in pdo
if (!$safeModeInsert) {
// set pdo insert statement in class property
$this->sql = "INSERT INTO `$table` ($sFields) VALUES ";
foreach ($data as $key => $value) {
$this->sql .= '(' . "'" . implode("', '", array_values($value)) . "'" . '), ';
}
$this->sql = rtrim($this->sql, ', ');
// return this object
// return $this;
// pdo prepare statement
$this->STH = $this->prepare($this->sql);
// start try catch block
try {
// execute pdo statement
if ($this->STH->execute()) {
// store all last insert id in array
$this->allLastId[] = $this->lastInsertId();
} else {
self::error($this->STH->errorInfo());
}
} catch (\PDOException $e) {
// get pdo error and pass on error method
self::error($e->getMessage() . ': ' . __LINE__);
// PDO Rollback
$this->back();
}// end try catch block
// PDO Commit
$this->end();
// close pdo
$this->STH->closeCursor();
// return this object
return $this;
}
// end here safe mode
// set pdo insert statement in class property
$this->sql = "INSERT INTO `$table` ($sFields) VALUES ($sNameSpaceParam);";
// pdo prepare statement
$this->STH = $this->prepare($this->sql);
// set class property with array
$this->data = $data;
// set batch insert flag true
$this->batch = true;
// parse batch array data
foreach ($data as $key => $value) {
// bind pdo param
$this->_bindPdoNameSpace($value);
try {
// execute pdo statement
if ($this->STH->execute()) {
// set class property with last insert id as array
$this->allLastId[] = $this->lastInsertId();
} else {
self::error($this->STH->errorInfo());
// on error PDO Rollback
$this->back();
}
} catch (\PDOException $e) {
// get pdo error and pass on error method
self::error($e->getMessage() . ': ' . __LINE__);
// on error PDO Rollback
$this->back();
}
}
// fine now PDO Commit
$this->end();
// close pdo
$this->STH->closeCursor();
// return this object
return $this;
} else {
self::error('Data not in valid format..');
}
} else {
self::error('Table name not found..');
}
} | php | {
"resource": ""
} |
q8809 | PdoWrapper.update | train | public function update($table = '', $data = [], $arrayWhere = [], $other = '')
{
// if table name is empty
if (!empty($table)) {
// check if array data and where array is more then 0
if (count($data) > 0 && count($arrayWhere) > 0) {
// parse array data and make a temp array
$tmp = [];
foreach ($data as $k => $v) {
$tmp[] = "$k = :s_$k";
}
// join temp array value with ,
$sFields = implode(', ', $tmp);
// delete temp array from memory
unset($tmp);
$tmp = [];
// parse where array and store in temp array
foreach ($arrayWhere as $k => $v) {
$tmp[] = "$k = :s_$k";
}
$this->data = $data;
$this->arrayWhere = $arrayWhere;
// join where array value with AND operator and create where condition
$where = implode(' AND ', $tmp);
// unset temp array
unset($tmp);
// make sql query to update
$this->sql = "UPDATE `$table` SET $sFields WHERE $where $other;";
// on PDO prepare statement
$this->STH = $this->prepare($this->sql);
// bind pdo param for update statement
$this->_bindPdoNameSpace($data);
// bind pdo param for where clause
$this->_bindPdoNameSpace($arrayWhere);
// try catch block start
try {
// if PDO run
if ($this->STH->execute()) {
// get affected rows
$this->affectedRows = $this->STH->rowCount();
// close PDO
$this->STH->closeCursor();
// return self object
return $this;
} else {
self::error($this->STH->errorInfo());
}
} catch (\PDOException $e) {
// get pdo error and pass on error method
self::error($e->getMessage() . ': ' . __LINE__);
} // try catch block end
} else {
self::error('update statement not in valid format..');
}
} else {
self::error('Table name not found..');
}
} | php | {
"resource": ""
} |
q8810 | PdoWrapper.count | train | public function count($table = '', $where = '')
{
// if table name not pass
if (!empty($table)) {
if (empty($where)) {
$this->sql = "SELECT COUNT(*) AS NUMROWS FROM `$table`;"; // create count query
} else {
$this->sql = "SELECT COUNT(*) AS NUMROWS FROM `$table` WHERE $where;"; // create count query
}
// pdo prepare statement
$this->STH = $this->prepare($this->sql);
try {
if ($this->STH->execute()) {
// fetch array result
$this->results = $this->STH->fetch();
// close pdo
$this->STH->closeCursor();
// return number of count
return $this->results['NUMROWS'];
} else {
self::error($this->STH->errorInfo());
}
} catch (\PDOException $e) {
// get pdo error and pass on error method
self::error($e->getMessage() . ': ' . __LINE__);
}
} else {
self::error('Table name not found..');
}
} | php | {
"resource": ""
} |
q8811 | PdoWrapper.truncate | train | public function truncate($table = '')
{
// if table name not pass
if (!empty($table)) {
// create count query
$this->sql = "TRUNCATE TABLE `$table`;";
// pdo prepare statement
$this->STH = $this->prepare($this->sql);
try {
if ($this->STH->execute()) {
// close pdo
$this->STH->closeCursor();
// return number of count
return true;
} else {
self::error($this->STH->errorInfo());
}
} catch (\PDOException $e) {
// get pdo error and pass on error method
self::error($e->getMessage() . ': ' . __LINE__);
}
} else {
self::error('Table name not found..');
}
} | php | {
"resource": ""
} |
q8812 | PdoWrapper.describe | train | public function describe($table = '')
{
$this->sql = $sql = "DESC $table;";
$this->STH = $this->prepare($sql);
$this->STH->execute();
$colList = $this->STH->fetchAll();
$field = [];
$type = [];
foreach ($colList as $key) {
$field[] = $key['Field'];
$type[] = $key['Type'];
}
return array_combine($field, $type);
} | php | {
"resource": ""
} |
q8813 | PdoWrapper.pdoPrepare | train | public function pdoPrepare($statement, $options = [])
{
$this->STH = $this->prepare($statement, $options);
return $this;
} | php | {
"resource": ""
} |
q8814 | Dispatcher.sortListeners | train | protected function sortListeners($eventName)
{
// If listeners exist for the given event, we will sort them by the priority
// so that we can call them in the correct order. We will cache off these
// sorted event listeners so we do not have to re-sort on every events.
$listeners = isset($this->listeners[$eventName])
? $this->listeners[$eventName] : [];
if (class_exists($eventName)) {
foreach (class_implements($eventName) as $interface) {
if (isset($this->listeners[$interface])) {
foreach ($this->listeners[$interface] as $priority => $names) {
if (isset($listeners[$priority])) {
$listeners[$priority] = array_merge($listeners[$priority], $names);
} else {
$listeners[$priority] = $names;
}
}
}
}
}
if ($listeners) {
krsort($listeners);
$this->sorted[$eventName] = call_user_func_array('array_merge', $listeners);
} else {
$this->sorted[$eventName] = [];
}
} | php | {
"resource": ""
} |
q8815 | DatabaseQueue.isReservedButExpired | train | protected function isReservedButExpired($query)
{
$expiration = Carbon::now()->subSeconds($this->expire)->getTimestamp();
$query->orWhere(function ($query) use ($expiration) {
$query->where('reserved_at', '<=', $expiration);
});
} | php | {
"resource": ""
} |
q8816 | HavingStringChunk.flatter | train | public function flatter($array)
{
$result = [];
foreach ($array as $item) {
if (is_array($item)) {
$result = array_merge($result, $this->flatter($item));
} else {
$result[] = $item;
}
}
return $result;
} | php | {
"resource": ""
} |
q8817 | MelisFrontMenuPlugin.checkValidPagesRecursive | train | public function checkValidPagesRecursive($siteMenu = array())
{
$checkedSiteMenu = array();
foreach($siteMenu as $key => $val){
if($val['menu'] != 'NONE'){
if($val['menu'] == 'NOLINK'){
$val['uri'] = '#';
}
if(!empty($val['pages'])){
$pages = $this->checkValidPagesRecursive($val['pages']);
if(!empty($pages)){
$val['pages'] = $pages;
}
}
$checkedSiteMenu[] = $val;
}
}
return $checkedSiteMenu;
} | php | {
"resource": ""
} |
q8818 | TableText.getSetValues | train | protected function getSetValues($arrCell, $intId)
{
return array(
'tstamp' => time(),
'value' => (string) $arrCell['value'],
'att_id' => $this->get('id'),
'row' => (int) $arrCell['row'],
'col' => (int) $arrCell['col'],
'item_id' => $intId,
);
} | php | {
"resource": ""
} |
q8819 | BaseApi.getAsync | train | protected function getAsync(array $endpoints, $params = [])
{
/** @var Promise[] $promises */
$promises = array_map(function (Endpoint $endpoint) use ($params) {
$isCached = $this->client->getCache() && $this->client->getCache()->getItem(KeyGenerator::fromEndpoint($endpoint))->isHit();
if ($endpoint->countsTowardsLimit() && !$isCached) {
try {
$this->client->getMethodRateLimiter()->hit($endpoint);
$this->client->getAppRateLimiter()->hit($endpoint);
} catch (RateLimitReachedException $e) {
return new RejectedPromise($e);
}
}
return $this->client->getHttpClient()
->sendAsyncRequest($this->buildRequest($endpoint, $params))
->then(function (ResponseInterface $response) use ($endpoint) {
return $response
->withHeader('X-Endpoint', $endpoint->getName())
->withHeader('X-Request', $endpoint->getUrl())
->withHeader('X-Region', $endpoint->getRegion()->getName());
});
}, is_array($endpoints) ? $endpoints : [$endpoints]);
// Wait for multiple requests to complete, even if some fail
if (count($promises) > 1) {
$results = \GuzzleHttp\Promise\settle($promises)->wait();
return BatchResult::fromSettledPromises($results);
}
// Resolve a single request
$result = $promises[0]->wait();
if (! $result instanceof ResponseInterface) {
throw $result;
}
return Result::fromPsr7($result);
} | php | {
"resource": ""
} |
q8820 | BaseApi.loadAllEndpoints | train | private function loadAllEndpoints()
{
self::$endpointClasses = array_map(function ($classPath) {
// For ./Api/Endpoints/MatchById -> ('MatchById.php')
list($endpointClass) = array_slice(explode('/', $classPath), -1, 1);
// Build the full class name with namespace
$fullClassName = join('\\', [__NAMESPACE__, 'Endpoints', str_replace('.php', '', $endpointClass)]);
/** @var Endpoint $endpoint */
$endpoint = new $fullClassName($this->region);
self::$endpointDefinitions[$endpoint->getName()] = [
'class' => $fullClassName,
'instance' => $endpoint,
];
return $fullClassName;
}, glob(__DIR__.'/Endpoints/*.php'));
} | php | {
"resource": ""
} |
q8821 | FacetofaceAttend.getSignupEvent | train | private function getSignupEvent($signup, $opts) {
$currentStatus = null;
$previousAttendance = false;
$previousPartialAttendance = false;
foreach ($signup->statuses as $status) {
if ($status->timecreated == $opts['event']['timecreated']) {
$currentStatus = $status;
} else if ($status->timecreated < $opts['event']['timecreated']
&& $status->statuscode == $this->statuscodes->partial) {
$previousPartialAttendance = true;
} else if ($status->timecreated < $opts['event']['timecreated']
&& $status->statuscode == $this->statuscodes->attended) {
$previousAttendance = true;
}
}
if (is_null($currentStatus)){
// There is no status with a timestamp matching the event.
return null;
}
$duration = null;
$completion = null;
if ($currentStatus->statuscode == $this->statuscodes->attended){
if ($previousAttendance == true){
// Attendance has already been recorded for this user and session.'
return null;
}
$duration = $this->sessionDuration;
$completion = true;
} else if ($currentStatus->statuscode == $this->statuscodes->partial){
if ($previousPartialAttendance == true){
// Partial attendance has already been recorded for this user and session.
return null;
}
$duration = $this->sessionDuration * $this->partialAttendanceDurationCredit;
$completion = false;
} else {
// This user did not attend this session.
return null;
}
return [
'recipe' => 'training_session_attend',
'attendee_id' => $signup->attendee->id,
'attendee_url' => $signup->attendee->url,
'attendee_name' => $signup->attendee->fullname,
'attempt_duration' => "PT".(string) $duration."S",
'attempt_completion' => $completion
];
} | php | {
"resource": ""
} |
q8822 | strawberryFieldharvester.processFileField | train | public function processFileField(array $element, WebformSubmissionInterface $webform_submission, &$cleanvalues) {
$key = $element['#webform_key'];
$original_data = $webform_submission->getOriginalData();
$value = isset($cleanvalues[$key]) ? $cleanvalues[$key] : [];
$fids = (is_array($value)) ? $value : [$value];
$original_value = isset($original_data[$key]) ? $original_data[$key] : [];
$original_fids = (is_array($original_value)) ? $original_value : [$original_value];
// Delete the old file uploads?
// @TODO build some cleanup logic here. Could be moved to attached field hook.
$delete_fids = array_diff($original_fids, $fids);
// @TODO what do we do with removed files?
// Idea. Check the fileUsage. If there is still some other than this one
// don't remove.
// But also, if a revision is using it? what a mess!
// @see \Drupal\webform\Plugin\WebformElement\WebformManagedFileBase::deleteFiles
// Exit if there is no fids.
if (empty($fids)) {
return;
}
/** @var \Drupal\file\FileInterface[] $files */
try {
$files = $this->entityTypeManager->getStorage('file')->loadMultiple(
$fids
);
} catch (InvalidPluginDefinitionException $e) {
} catch (PluginNotFoundException $e) {
}
$fileinfo_many = [];
//@TODO refactor this urgently to a NEW TECHMD class.
foreach ($files as $file) {
$fileinfo = [];
if (isset($cleanvalues['as:image'])) {
$fileinfo = $this->check_file_in_metadata(
$cleanvalues['as:image'],
(int) $file->id()
);
if ($fileinfo) {
$fileinfo_many[$fileinfo['dr:url']] = $fileinfo;
}
}
if (!$fileinfo) {
// Only do this is file was not previusly processed and stored.
$uri = $file->getFileUri();
$md5 = md5_file($uri);
$fileinfo = [
'type' => 'Image',
'dr:url' => $uri,
'url' => $uri,
'checksum' => $md5,
'dr:for' => $key,
'dr:fid' => (int) $file->id(),
'name' => $file->getFilename(),
];
$relativefolder = substr($md5, 0, 3);
$source_uri = $file->getFileUri();
$realpath_uri = $this->fileSystem->realpath($source_uri);
if (empty(!$realpath_uri)) {
$command = escapeshellcmd(
'/usr/local/bin/fido ' . $realpath_uri . ' -pronom_only -matchprintf '
);
// @TODO handle the exit code from output
$output = shell_exec($command . '"OK,%(info.puid)" -q');
}
// We will use the original scheme here since our HD operations are over.
$destination_uri = $this->getFileDestinationUri(
$element,
$file,
$relativefolder,
$webform_submission
);
//Use the wished storagepoint as key.
//Then the node save hook will deal with moving data.
$fileinfo_many[$destination_uri] = $fileinfo;
}
}
$cleanvalues['as:image'] = $fileinfo_many;
} | php | {
"resource": ""
} |
q8823 | strawberryFieldharvester.getUriSchemeForManagedFile | train | protected function getUriSchemeForManagedFile(array $element) {
if (isset($element['#uri_scheme'])) {
return $element['#uri_scheme'];
}
$scheme_options = \Drupal\webform\Plugin\WebformElement\WebformManagedFileBase::getVisibleStreamWrappers();
if (isset($scheme_options['private'])) {
return 'private';
}
elseif (isset($scheme_options['public'])) {
return 'public';
}
else {
return 'private';
}
} | php | {
"resource": ""
} |
q8824 | ViewContextTrait.getLayoutPath | train | public function getLayoutPath( $sufix = 'layouts' )
{
if( $this->_layoutPath === null ) {
$path = parent::getLayoutPath();
if( !is_dir( $path ) && $parentPath = $this->getParentPath( $sufix ) ) {
$path = $parentPath;
}
$this->_layoutPath = $path;
}
return $this->_layoutPath;
} | php | {
"resource": ""
} |
q8825 | Installer.prepare | train | public function prepare($listener)
{
if (! $this->requirements->check()) {
return $listener->preparationNotCompleted();
}
$this->installer->migrate();
return $listener->preparationCompleted();
} | php | {
"resource": ""
} |
q8826 | Installer.create | train | public function create($listener)
{
$model = new Fluent([
'site' => ['name' => \config('app.name', 'Orchestra Platform')],
]);
$form = $this->presenter->form($model);
return $listener->createSucceed(\compact('form', 'model'));
} | php | {
"resource": ""
} |
q8827 | FileLoader.requireInstallerFiles | train | protected function requireInstallerFiles(bool $once = true): void
{
$paths = \config('orchestra/installer::installers.paths', []);
$method = ($once === true ? 'requireOnce' : 'getRequire');
foreach ($paths as $path) {
$file = \rtrim($path, '/').'/installer.php';
if (File::exists($file)) {
File::{$method}($file);
}
}
} | php | {
"resource": ""
} |
q8828 | Service.dispatch | train | public function dispatch(Queueable $job)
{
if (isset($job->queue, $job->delay)) {
return $this->connection->laterOn($job->queue, $job->delay, $job);
}
if (isset($job->queue)) {
return $this->connection->pushOn($job->queue, $job);
}
if (isset($job->delay)) {
return $this->connection->later($job->delay, $job);
}
return $this->connection->push($job);
} | php | {
"resource": ""
} |
q8829 | Service.failJob | train | protected function failJob($job, $e)
{
if ($job->isDeleted()) {
return;
}
$job->delete();
$job->failed($e);
} | php | {
"resource": ""
} |
q8830 | TShortcode.shortCode | train | public function shortCode($text)
{
/* Needs PHP 7
$patternsAndCallbacks = [
"/\[(FIGURE)[\s+](.+)\]/" => function ($match) {
return self::ShortCodeFigure($matches[2]);
},
"/(```([\w]*))\n([^`]*)```[\n]{1}/s" => function ($match) {
return $this->syntaxHighlightGeSHi($matches[3], $matches[2]);
},
];
return preg_replace_callback_array($patternsAndCallbacks, $text);
*/
$patterns = [
"/\[(FIGURE)[\s+](.+)\]/",
//'/\[(YOUTUBE) src=(.+) width=(.+) caption=(.+)\]/',
"/\[(YOUTUBE)[\s+](.+)\]/",
"/\[(CODEPEN)[\s+](.+)\]/",
"/\[(ASCIINEMA)[\s+](.+)\]/",
"/\[(BOOK)[\s+](.+)\]/",
//"/(```)([\w]*)\n([.]*)```[\n]{1}/s",
"/(```)([\w]*)\n(.*?)```\n/s",
'/\[(INFO)\]/',
'/\[(\/INFO)\]/',
'/\[(WARNING)\]/',
'/\[(\/WARNING)\]/',
];
return preg_replace_callback(
$patterns,
function ($matches) {
switch ($matches[1]) {
case "FIGURE":
return self::shortCodeFigure($matches[2]);
break;
case "YOUTUBE":
return self::shortCodeYoutube($matches[2]);
break;
case "CODEPEN":
return self::shortCodeCodepen($matches[2]);
break;
case "ASCIINEMA":
return self::shortCodeAsciinema($matches[2]);
break;
case "BOOK":
return self::shortCodeBook($matches[2]);
break;
case "```":
//return $this->syntaxHighlightGeSHi($matches[3], $matches[2]);
return $this->syntaxHighlightJs($matches[3], $matches[2]);
break;
case 'INFO':
return <<<EOD
<div class="info">
<span class="icon fa-stack fa-lg">
<i class="fa fa-circle fa-stack-2x"></i>
<i class="fa fa-info fa-stack-1x fa-inverse" aria-hidden="true"></i>
</span>
<div markdown=1>
EOD;
break;
case 'WARNING':
return <<<EOD
<div class="warning">
<span class="icon fa-stack fa-lg">
<i class="fa fa-circle fa-stack-2x"></i>
<i class="fa fa-exclamation-triangle fa-stack-1x fa-inverse" aria-hidden="true"></i>
</span>
<div markdown=1>
EOD;
break;
case '/INFO':
case '/WARNING':
return "</div></div>";
break;
default:
return "{$matches[1]} is unknown shortcode.";
}
},
$text
);
} | php | {
"resource": ""
} |
q8831 | TShortcode.shortCodeInit | train | public static function shortCodeInit($options)
{
preg_match_all('/[a-zA-Z0-9]+="[^"]+"|\S+/', $options, $matches);
$res = array();
foreach ($matches[0] as $match) {
$pos = strpos($match, '=');
if ($pos === false) {
$res[$match] = true;
} else {
$key = substr($match, 0, $pos);
$val = trim(substr($match, $pos+1), '"');
$res[$key] = $val;
}
}
return $res;
} | php | {
"resource": ""
} |
q8832 | FormComponent.processSubmit | train | protected function processSubmit(FormInterface $form, Request $request): void
{
// Restored request should only render the form, not immediately submit it.
if ($request->hasFlag(Request::RESTORED)) {
return;
}
$form->handleRequest($request);
if (!$form->isSubmitted()) {
throw new BadRequestException('The form was not submitted.');
}
$data = $form->getData();
if ($form->isValid()) {
$this->onSuccess($data, $this);
} else {
$this->onError($data, $this);
}
$this->onSubmit($data, $this);
} | php | {
"resource": ""
} |
q8833 | FormComponent.processValidate | train | protected function processValidate(FormInterface $form, Request $request): void
{
/** @var Presenter $presenter */
$presenter = $this->getPresenter();
if (!$presenter->isAjax()) {
throw new BadRequestException('The validate signal is only allowed in ajax mode.');
}
$form->handleRequest($request);
if (!$form->isSubmitted()) {
throw new BadRequestException('The form was not submitted.');
}
$view = $this->getView();
$errors = [];
$this->walkErrors(
$form->getErrors(true, false),
$view,
function (FormView $view) use (&$errors) {
$errors[$view->vars['id']] = $this->renderer->searchAndRenderBlock($view, 'errors_content');
}
);
$presenter->sendJson((object) ['errors' => $errors]);
} | php | {
"resource": ""
} |
q8834 | FormComponent.processRender | train | protected function processRender(FormInterface $form, Request $request): void
{
/** @var Presenter $presenter */
$presenter = $this->getPresenter();
if (!$presenter->isAjax()) {
throw new BadRequestException('The render signal is only allowed in ajax mode.');
}
$fields = $request->getPost($this->lookupPath(Presenter::class, true).self::NAME_SEPARATOR.'fields');
if (!$fields) {
throw new BadRequestException('No fields specified for rendering.');
}
$form->handleRequest($request);
if (!$form->isSubmitted()) {
throw new BadRequestException('The form was not submitted.');
}
$view = $this->getView();
$widgets = [];
foreach ($fields as $field) {
// Validate the field identifier for security reasons. A dot in the identifier would be particularly dangerous.
if (!Strings::match($field, '~^(?:\[\w++\])++$~')) {
throw new BadRequestException(
sprintf('Field identifier "%s" contains unallowed characters.', $field)
);
}
// Skip duplicates. The renderer would return an empty string on second try.
if (isset($widgets[$field])) {
continue;
}
// Wrap an exception from PropertyAccessor in a BadRequestException.
try {
$fieldView = $this->propertyAccessor->getValue($view, $field);
} catch (ExceptionInterface $e) {
throw new BadRequestException(
sprintf('FormView not found for field identifier "%s".', $field),
0,
$e
);
}
// Render the field widget.
$widgets[$field] = $this->renderer->searchAndRenderBlock($fieldView, 'widget');
}
$presenter->sendJson((object) ['widgets' => $widgets]);
} | php | {
"resource": ""
} |
q8835 | ShortcodeUI.register | train | public function register( $context = null ) {
if ( ! $this->is_needed() ) {
return;
}
\shortcode_ui_register_for_shortcode(
$this->shortcode_tag,
$this->config
);
} | php | {
"resource": ""
} |
q8836 | DatastreamProtocol.mapToList | train | public function mapToList($map)
{
$list = array();
foreach ($map as $key => $value) {
// explicitly pass key as UTF-8 byte array
// pass value with automatic type detection
$list []= new QVariant($key, Types::TYPE_QBYTE_ARRAY);
$list []= $value;
}
return $list;
} | php | {
"resource": ""
} |
q8837 | DatastreamProtocol.listToMap | train | public function listToMap(array $list)
{
$map = array();
for ($i = 0, $n = count($list); $i < $n; $i += 2) {
$map[$list[$i]] = $list[$i + 1];
}
return (object)$map;
} | php | {
"resource": ""
} |
q8838 | Installation.make | train | public function make(array $input, bool $multiple = true): bool
{
try {
$this->validate($input);
} catch (ValidationException $e) {
Session::flash('errors', $e->validator->messages());
return false;
}
try {
! $multiple && $this->hasNoExistingUser();
$this->create(
$this->createUser($input), $input
);
// Installation is successful, we should be able to generate
// success message to notify the user. Installer route will be
// disabled after this point.
Messages::add('success', \trans('orchestra/foundation::install.user.created'));
return true;
} catch (Exception $e) {
Messages::add('error', $e->getMessage());
}
return false;
} | php | {
"resource": ""
} |
q8839 | Installation.create | train | public function create(User $user, array $input): void
{
$memory = \app('orchestra.memory')->make();
// Bootstrap auth services, so we can use orchestra/auth package
// configuration.
$actions = ['Manage Orchestra', 'Manage Users'];
$admin = \config('orchestra/foundation::roles.admin', 1);
$roles = Role::pluck('name', 'id')->all();
$theme = [
'frontend' => 'default',
'backend' => 'default',
];
// Attach Administrator role to the newly created administrator.
$user->roles()->sync([$admin]);
// Add some basic configuration for Orchestra Platform, including
// email configuration.
$memory->put('site.name', $input['site_name']);
$memory->put('site.theme', $theme);
$memory->put('email', \config('mail'));
$memory->put('email.from', [
'name' => $input['site_name'],
'address' => $input['email'],
]);
// We should also create a basic ACL for Orchestra Platform, since
// the basic roles is create using Fluent Query Builder we need
// to manually insert the roles.
$acl = \app('orchestra.platform.acl');
$acl->attach($memory);
$acl->actions()->attach($actions);
$acl->roles()->attach(\array_values($roles));
$acl->allow($roles[$admin], $actions);
\event('orchestra.install: acl', [$acl]);
} | php | {
"resource": ""
} |
q8840 | Installation.validate | train | public function validate(array $input): bool
{
// Grab input fields and define the rules for user validations.
$rules = [
'email' => ['required', 'email'],
'password' => ['required'],
'fullname' => ['required'],
'site_name' => ['required'],
];
$validation = \app('validator')->make($input, $rules);
// Validate user registration, we should stop this process if
// the user not properly formatted.
if ($validation->fails()) {
throw new ValidationException($validation);
}
return true;
} | php | {
"resource": ""
} |
q8841 | Installation.createUser | train | public function createUser(array $input): User
{
User::unguard();
$user = new User([
'email' => $input['email'],
'password' => $input['password'],
'fullname' => $input['fullname'],
'status' => User::VERIFIED,
]);
\event('orchestra.install: user', [$user, $input]);
$user->save();
return $user;
} | php | {
"resource": ""
} |
q8842 | AbstractDomAccessor.getArgumentsString | train | protected function getArgumentsString()
{
$arguments = array($this->getIdentifierArgumentString());
if ($this->hasRelations()) {
$arguments[] = $this->getRelationArgumentsString();
}
return implode(', ', $arguments);
} | php | {
"resource": ""
} |
q8843 | DoctrineORMPaginator.useOutputWalker | train | protected function useOutputWalker(Query $query)
{
if (null === $this->useOutputWalkers) {
return false === (bool) $query->getHint(Query::HINT_CUSTOM_OUTPUT_WALKER);
}
return $this->useOutputWalkers;
} | php | {
"resource": ""
} |
q8844 | DoctrineORMPaginator.appendTreeWalker | train | protected function appendTreeWalker(Query $query, $walkerClass)
{
$hints = $query->getHint(Query::HINT_CUSTOM_TREE_WALKERS);
if (false === $hints) {
$hints = [];
}
$hints[] = $walkerClass;
$query->setHint(Query::HINT_CUSTOM_TREE_WALKERS, $hints);
} | php | {
"resource": ""
} |
q8845 | PDOHelper.arrayToXml | train | public function arrayToXml($arrayData = [])
{
$xml = '<?xml version="1.0" encoding="UTF-8"?>';
$xml .= '<root>';
foreach ($arrayData as $key => $value) {
$xml .= '<xml_data>';
if (is_array($value)) {
foreach ($value as $k => $v) {
//$k holds the table column name
$xml .= "<$k>";
//embed the SQL data in a CDATA element to avoid XML entity issues
$xml .= "<![CDATA[$v]]>";
//and close the element
$xml .= "</$k>";
}
} else {
//$key holds the table column name
$xml .= "<$key>";
//embed the SQL data in a CDATA element to avoid XML entity issues
$xml .= "<![CDATA[$value]]>";
//and close the element
$xml .= "</$key>";
}
$xml .= '</xml_data>';
}
$xml .= '</root>';
return $xml;
} | php | {
"resource": ""
} |
q8846 | PDOHelper.formatSQL | train | public function formatSQL($sql = '')
{
// Reserved SQL Keywords Data
$reserveSqlKey = 'select|insert|update|delete|truncate|drop|create|add|except|percent|all|exec|plan|alter|execute|precision|and|exists|primary|any|exit|print|as|fetch|proc|asc|file|procedure|authorization|fillfactor|public|backup|for|raiserror|begin|foreign|read|between|freetext|readtext|break|freetexttable|reconfigure|browse|from|references|bulk|full|replication|by|function|restore|cascade|goto|restrict|case|grant|return|check|group|revoke|checkpoint|having|right|close|holdlock|rollback|clustered|identity|rowcount|coalesce|identity_insert|rowguidcol|collate|identitycol|rule|column|if|save|commit|in|schema|compute|index|select|constraint|inner|session_user|contains|insert|set|containstable|intersect|setuser|continue|into|shutdown|convert|is|some|create|join|statistics|cross|key|system_user|current|kill|table|current_date|left|textsize|current_time|like|then|current_timestamp|lineno|to|current_user|load|top|cursor|national|tran|database|nocheck|transaction|dbcc|nonclustered|trigger|deallocate|not|truncate|declare|null|tsequal|default|nullif|union|delete|of|unique|deny|off|update|desc|offsets|updatetext|disk|on|use|distinct|open|user|distributed|opendatasource|values|double|openquery|varying|drop|openrowset|view|dummy|openxml|waitfor|dump|option|when|else|or|where|end|order|while|errlvl|outer|with|escape|over|writetext|absolute|overlaps|action|pad|ada|partial|external|pascal|extract|position|allocate|false|prepare|first|preserve|float|are|prior|privileges|fortran|assertion|found|at|real|avg|get|global|relative|go|bit|bit_length|both|rows|hour|cascaded|scroll|immediate|second|cast|section|catalog|include|char|session|char_length|indicator|character|initially|character_length|size|input|smallint|insensitive|space|int|sql|collation|integer|sqlca|sqlcode|interval|sqlerror|connect|sqlstate|connection|sqlwarning|isolation|substring|constraints|sum|language|corresponding|last|temporary|count|leading|time|level|timestamp|timezone_hour|local|timezone_minute|lower|match|trailing|max|min|translate|date|minute|translation|day|module|trim|month|true|dec|names|decimal|natural|unknown|nchar|deferrable|next|upper|deferred|no|usage|none|using|describe|value|descriptor|diagnostics|numeric|varchar|disconnect|octet_length|domain|only|whenever|work|end-exec|write|year|output|zone|exception|free|admin|general|after|reads|aggregate|alias|recursive|grouping|ref|host|referencing|array|ignore|result|returns|before|role|binary|initialize|rollup|routine|blob|inout|row|boolean|savepoint|breadth|call|scope|search|iterate|large|sequence|class|lateral|sets|clob|less|completion|limit|specific|specifictype|localtime|constructor|localtimestamp|sqlexception|locator|cube|map|current_path|start|current_role|state|cycle|modifies|statement|data|modify|static|structure|terminate|than|nclob|depth|new|deref|destroy|treat|destructor|object|deterministic|old|under|dictionary|operation|unnest|ordinality|out|dynamic|each|parameter|variable|equals|parameters|every|without|path|postfix|prefix|preorder';
// convert in array
$list = explode('|', $reserveSqlKey);
foreach ($list as &$verb) {
$verb = '/\b' . preg_quote($verb, '/') . '\b/';
}
$regex_sign = ['/\b', '\b/'];
// replace matching words
return str_replace(
$regex_sign,
'',
preg_replace(
$list,
array_map(
[
$this,
'highlight_sql',
],
$list
),
strtolower($sql)
)
);
} | php | {
"resource": ""
} |
q8847 | PDOHelper.displayHtmlTable | train | public function displayHtmlTable($aColList = [])
{
$r = '';
if (count($aColList) > 0) {
$r .= '<table border="1">';
$r .= '<thead>';
$r .= '<tr>';
foreach ($aColList[0] as $k => $v) {
$r .= '<td>' . $k . '</td>';
}
$r .= '</tr>';
$r .= '</thead>';
$r .= '<tbody>';
foreach ($aColList as $record) {
$r .= '<tr>';
foreach ($record as $data) {
$r .= '<td>' . $data . '</td>';
}
$r .= '</tr>';
}
$r .= '</tbody>';
$r .= '<table>';
} else {
$r .= '<div class="no-results">No results found for query.</div>';
}
return $r;
} | php | {
"resource": ""
} |
q8848 | FileOwnerValidator.validate | train | public function validate($value, Constraint $constraint)
{
if (!$value) {
return;
}
$fileHistory = $this->em->getRepository('JbFileUploaderBundle:FileHistory')->find($value);
if (!$fileHistory) {
return;
}
// No userid associated with file. Every one can use it.
if (!$fileHistory->getUserId()) {
return;
}
// No token. Violation as there is a user id associate with file.
$token = $this->tokenStorage->getToken();
if (!$token) {
return $this->createViolation($value, $constraint);
}
// No user. Violation as there is a user id associate with file.
$user = $token->getUser();
if (!$user) {
return $this->createViolation($value, $constraint);
}
if ($user->getId() !== $fileHistory->getUserId()) {
return $this->createViolation($value, $constraint);
}
return;
} | php | {
"resource": ""
} |
q8849 | FileOwnerValidator.createViolation | train | protected function createViolation($value, Constraint $constraint)
{
$this
->context
->buildViolation($constraint->message)
->setParameter('%filename%', $value)
->addViolation();
} | php | {
"resource": ""
} |
q8850 | Croper.getCropResolver | train | protected function getCropResolver($endpoint)
{
$cropedResolver = $this->configuration->getValue($endpoint, 'croped_resolver');
if (!$cropedResolver) {
throw new JbFileUploaderException('No croped_resolver configuration for endpoint '.$endpoint);
}
return $cropedResolver;
} | php | {
"resource": ""
} |
q8851 | MelisFrontMinifiedAssetsCheckerListener.loadAssetsFromConfig | train | private function loadAssetsFromConfig($content, $dir, $type = null, $isFromVendor = false, $siteName = '')
{
$newContent = $content;
$assetsConfig = $dir.'assets.config.php';
/**
* check if the config exist
*/
if (file_exists($assetsConfig)) {
$files = include($assetsConfig);
/**
* check if assets config is not empty
*/
if (!empty($files)) {
foreach($files as $key => $file){
/**
* check if type to know what asset are
* we going to load
*/
if(empty($type)) {
/**
* this will load the assets from the config
*/
$cssToAdd = "\n";
$jsToLoad = "\n";
if (strtolower($key) == 'css') {
foreach ($file as $k => $css) {
$css = str_replace('/public', '', $css);
$css = $this->editFileName($css, $isFromVendor, $siteName);
$cssToAdd .= '<link href="' . $css . '" media="screen" rel="stylesheet" type="text/css">' . "\n";
}
}
elseif (strtolower($key) == 'js') {
foreach ($file as $k => $js) {
$js = str_replace('/public', '', $js);
$js = $this->editFileName($js, $isFromVendor, $siteName);
$jsToLoad .= '<script type="text/javascript" src="' . $js . '"></script>' . "\n";
}
}
$newContent = $this->createLink($newContent, $cssToAdd, $jsToLoad);
}
elseif($type == 'css'){
/**
* this will load only the css
* from the config
*/
if (strtolower($key) == 'css') {
$cssToAdd = "\n";
foreach ($file as $k => $css) {
$css = str_replace('/public', '', $css);
$css = $this->editFileName($css, $isFromVendor, $siteName);
$cssToAdd .= '<link href="' . $css . '" media="screen" rel="stylesheet" type="text/css">' . "\n";
}
$newContent = $this->createCssLink($content, $cssToAdd);
}
}elseif($type == 'js'){
/**
* this will load the js only from the config
*/
if (strtolower($key) == 'js') {
$jsToLoad = "\n";
foreach ($file as $k => $js) {
$js = str_replace('/public', '', $js);
$js = $this->editFileName($js, $isFromVendor, $siteName);
$jsToLoad .= '<script type="text/javascript" src="' . $js . '"></script>' . "\n";
}
$newContent = $this->createJsLink($content, $jsToLoad);
}
}
}
}
}
return $newContent;
} | php | {
"resource": ""
} |
q8852 | MelisFrontMinifiedAssetsCheckerListener.editFileName | train | private function editFileName($fileName, $isFromVendor, $siteName){
if($isFromVendor){
$pathInfo = explode('/', $fileName);
for($i = 0; $i <= sizeof($pathInfo); $i++){
if(!empty($pathInfo[1])){
if(str_replace('-', '', ucwords($pathInfo[1], '-')) == $siteName){
$fileName = preg_replace('/'.$pathInfo[1].'/', $siteName, $fileName, 1);
}
}
}
}
return $fileName;
} | php | {
"resource": ""
} |
q8853 | Setup.form | train | public function form(Fluent $model)
{
return $this->form->of('orchestra.install', function (FormGrid $form) use ($model) {
$form->fieldset(\trans('orchestra/foundation::install.steps.account'), function (Fieldset $fieldset) use ($model) {
$this->userForm($fieldset, $model);
});
$form->fieldset(\trans('orchestra/foundation::install.steps.application'), function (Fieldset $fieldset) use ($model) {
$this->applicationForm($fieldset, $model);
});
});
} | php | {
"resource": ""
} |
q8854 | Setup.applicationForm | train | protected function applicationForm(Fieldset $fieldset, Fluent $model): void
{
$fieldset->control('text', 'site_name')
->label(\trans('orchestra/foundation::label.name'))
->value(\data_get($model, 'site.name'))
->attributes(['autocomplete' => 'off']);
} | php | {
"resource": ""
} |
q8855 | Setup.userForm | train | protected function userForm(Fieldset $fieldset, Fluent $model): void
{
$fieldset->control('input:email', 'email')
->label(\trans('orchestra/foundation::label.users.email'));
$fieldset->control('password', 'password')
->label(\trans('orchestra/foundation::label.users.password'));
$fieldset->control('text', 'fullname')
->label(\trans('orchestra/foundation::label.users.fullname'))
->value('Administrator');
} | php | {
"resource": ""
} |
q8856 | Paragraph._renderInlineTag | train | protected function _renderInlineTag($string)
{
$string = $this->engine->inlineParser->parse($string);
// handling of carriage-returns inside paragraphs
$string = (!$this->_firstLine) ? " $string" : $string;
$this->_firstLine = false;
return ($string);
} | php | {
"resource": ""
} |
q8857 | Builder.setText | train | public function setText($text)
{
$this->text = $text;
$this->encodeManager->setData($text);
return $this;
} | php | {
"resource": ""
} |
q8858 | Builder.setForegroundColor | train | public function setForegroundColor($foregroundColor)
{
if ( is_null($this->frontColor) ) {
$this->frontColor = new Color;
}
$this->frontColor->setFromArray($foregroundColor);
return $this;
} | php | {
"resource": ""
} |
q8859 | Builder.setBackgroundColor | train | public function setBackgroundColor($backgroundColor)
{
if ( is_null($this->backColor) ) {
$this->backColor = new Color;
}
$this->backColor->setFromArray($backgroundColor);
return $this;
} | php | {
"resource": ""
} |
q8860 | Builder.getModuleSize | train | public function getModuleSize()
{
if ( is_null($this->moduleSize) )
{
$this->moduleSize = $this->getImageFormat() == "jpeg" ? 8 : 4;
}
return $this->moduleSize;
} | php | {
"resource": ""
} |
q8861 | Builder.autoVersionAndGetMaxDataBits | train | private function autoVersionAndGetMaxDataBits($codewordNumPlus, $dataBitsTotal)
{
$i = 1 + 40 * $this->getEccCharacter();
$j = $i + 39;
$version = 1;
while ($i <= $j) {
$maxDataBits = $this->getMaxDataBitsByIndexFormArray($i);
if ( ($maxDataBits) >= ($dataBitsTotal + $codewordNumPlus[$version]) ) {
$this->setVersion($version);
return $maxDataBits;
}
$i++; $version++;
}
return 0;
} | php | {
"resource": ""
} |
q8862 | Cache.remember | train | public static function remember($key, $seconds, Closure $callback, $initDir = '/', $basedir = 'cache')
{
$debug = \Bitrix\Main\Data\Cache::getShowCacheStat();
if ($seconds <= 0) {
try {
$result = $callback();
} catch (AbortCacheException $e) {
$result = null;
}
if ($debug) {
CacheDebugger::track('zero_ttl', $initDir, $basedir, $key, $result);
}
return $result;
}
$obCache = new CPHPCache();
if ($obCache->InitCache($seconds, $key, $initDir, $basedir)) {
$vars = $obCache->GetVars();
if ($debug) {
CacheDebugger::track('hits', $initDir, $basedir, $key, $vars['cache']);
}
return $vars['cache'];
}
$obCache->StartDataCache();
try {
$cache = $callback();
$obCache->EndDataCache(['cache' => $cache]);
} catch (AbortCacheException $e) {
$obCache->AbortDataCache();
$cache = null;
}
if ($debug) {
CacheDebugger::track('misses', $initDir, $basedir, $key, $cache);
}
return $cache;
} | php | {
"resource": ""
} |
q8863 | Cache.rememberForever | train | public static function rememberForever($key, Closure $callback, $initDir = '/', $basedir = 'cache')
{
return static::remember($key, 99999999, $callback, $initDir, $basedir);
} | php | {
"resource": ""
} |
q8864 | Cache.flushAll | train | public static function flushAll()
{
$GLOBALS["CACHE_MANAGER"]->cleanAll();
$GLOBALS["stackCacheManager"]->cleanAll();
$staticHtmlCache = StaticHtmlCache::getInstance();
$staticHtmlCache->deleteAll();
BXClearCache(true);
} | php | {
"resource": ""
} |
q8865 | Config.getParam | train | public function getParam($param)
{
if (isset($this->_parentConfig))
return ($this->_parentConfig->getParam($param));
return (isset($this->_params[$param]) ? $this->_params[$param] : null);
} | php | {
"resource": ""
} |
q8866 | Config.titleToIdentifier | train | public function titleToIdentifier($depth, $text)
{
/** @var callable $func */
$func = $this->getParam('titleToIdFunction');
if (isset($func)) {
return ($func($depth, $text));
}
// conversion of accented characters
// see http://www.weirdog.com/blog/php/supprimer-les-accents-des-caracteres-accentues.html
$text = htmlentities($text, ENT_NOQUOTES, 'utf-8');
$text = preg_replace('#&([A-za-z])(?:acute|cedil|circ|grave|orn|ring|slash|th|tilde|uml);#', '\1', $text);
$text = preg_replace('#&([A-za-z]{2})(?:lig);#', '\1', $text); // for ligatures e.g. 'œ'
$text = preg_replace('#&([lr]s|sb|[lrb]d)(quo);#', ' ', $text); // for *quote (http://www.degraeve.com/reference/specialcharacters.php)
$text = str_replace(' ', ' ', $text); // for non breaking space
$text = preg_replace('#&[^;]+;#', '', $text); // strips other characters
$text = preg_replace("/[^a-zA-Z0-9_-]/", ' ', $text); // remove any other characters
$text = str_replace(' ', '-', $text);
$text = preg_replace('/\s+/', " ", $text);
$text = preg_replace('/-+/', "-", $text);
$text = trim($text, '-');
$text = trim($text);
$text = empty($text) ? '-' : $text;
return ($text);
} | php | {
"resource": ""
} |
q8867 | Config.onStart | train | public function onStart($text)
{
// process of smileys and other special characters
if ($this->getParam('convertSmileys'))
$text = Smiley::convertSmileys($text);
if ($this->getParam('convertSymbols'))
$text = Smiley::convertSymbols($text);
// if a specific pre-parse function was defined, it is called
/** @var callable $func */
$func = $this->getParam('preParseFunction');
if (isset($func))
$text = $func($text);
return ($text);
} | php | {
"resource": ""
} |
q8868 | Config.onParse | train | public function onParse($finalText)
{
// if a specific post-parse function was defined, it is called
/** @var callable $func */
$func = $this->getParam('postParseFunction');
if (isset($func))
$finalText = $func($finalText);
// add footnotes' content if needed
if ($this->getParam('addFootnotes')) {
$footnotes = $this->getFootnotes();
if (!empty($footnotes))
$finalText .= "\n" . $footnotes;
}
return ($finalText);
} | php | {
"resource": ""
} |
q8869 | Config.processLink | train | public function processLink($url, $tagName = '')
{
$label = $url = trim($url);
$targetBlank = $this->getParam('targetBlank');
$nofollow = $this->getParam('nofollow');
// shortening of long URLs
if ($this->getParam('shortenLongUrl') && strlen($label) > 40)
$label = substr($label, 0, 40) . '...';
// Javascript XSS check
if (substr($url, 0, strlen('javascript:')) === 'javascript:')
$url = '#';
else {
// email check
if (filter_var($url, FILTER_VALIDATE_EMAIL)) {
$url = "mailto:$url";
$targetBlank = $nofollow = false;
} else if (substr($url, 0, strlen('mailto:')) === 'mailto:') {
$label = substr($url, strlen('mailto:'));
$targetBlank = $nofollow = false;
}
// if a specific URL process function was defined, it is called
/** @var callable $func */
$func = $this->getParam('urlProcessFunction');
if (isset($func))
list($url, $label, $targetBlank, $nofollow) = $func($url, $label, $targetBlank, $nofollow);
}
return (array($url, $label, $targetBlank, $nofollow));
} | php | {
"resource": ""
} |
q8870 | Config.addTocEntry | train | public function addTocEntry($depth, $title, $identifier)
{
if (!isset($this->_toc))
$this->_toc = array();
$this->_addTocSubEntry($depth, $depth, $title, $identifier, $this->_toc);
} | php | {
"resource": ""
} |
q8871 | Config.getToc | train | public function getToc($raw = false)
{
if ($raw === true)
return ($this->_toc['sub']);
$html = "<b>On this page:</b>" . $this->_getRenderedToc($this->_toc['sub']);
return ($html);
} | php | {
"resource": ""
} |
q8872 | Config.addFootnote | train | public function addFootnote($text, $label = null)
{
if (isset($this->_parentConfig))
return ($this->_parentConfig->addFootnote($text, $label));
if (is_null($label))
$this->_footnotes[] = $text;
else
$this->_footnotes[] = array(
'label' => $label,
'text' => $text
);
$index = count($this->_footnotes);
return (array(
'id' => $this->getParam('footnotesPrefix') . "-$index",
'index' => $index
));
} | php | {
"resource": ""
} |
q8873 | Config.getFootnotes | train | public function getFootnotes($raw = false)
{
if ($raw === true)
return ($this->_footnotes);
if (empty($this->_footnotes))
return (null);
$footnotes = '';
$index = 1;
foreach ($this->_footnotes as $note) {
$id = $this->getParam('footnotesPrefix') . "-$index";
$noteHtml = "<p class=\"footnote\"><a href=\"#cite_ref-$id\" name=\"cite_note-$id\" id=\"cite_note-$id\">";
if (is_string($note))
$noteHtml .= "$index</a>. $note";
else
$noteHtml .= htmlspecialchars($note['label']) . "</a>. " . $note['text'];
$noteHtml .= "</p>\n";
$footnotes .= $noteHtml;
$index++;
}
$footnotes = "<div class=\"footnotes\">\n$footnotes</div>\n";
return ($footnotes);
} | php | {
"resource": ""
} |
q8874 | Config._addTocSubEntry | train | private function _addTocSubEntry($depth, $level, $title, $identifier, &$list)
{
if (!isset($list['sub']))
$list['sub'] = array();
$offset = count($list['sub']);
if ($depth === 1) {
$list['sub'][$offset] = array(
'id' => $identifier,
'value' => $title
);
return;
}
$offset--;
if (!isset($list['sub'][$offset]))
$list['sub'][$offset] = array();
$this->_addTocSubEntry($depth - 1, $level, $title, $identifier, $list['sub'][$offset]);
} | php | {
"resource": ""
} |
q8875 | Craftremote.key | train | private function key(int $length, string $extraChars = ''): string
{
$licenseKey = '';
$codeAlphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'.$extraChars;
$alphabetLength = strlen($codeAlphabet);
$log = log($alphabetLength, 2);
$bytes = (int)($log / 8) + 1; // length in bytes
$bits = (int)$log + 1; // length in bits
$filter = (int)(1 << $bits) - 1; // set all lower bits to 1
for ($i = 0; $i < $length; $i++) {
do {
$rnd = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes)));
$rnd = $rnd & $filter; // discard irrelevant bits
} while ($rnd >= $alphabetLength);
$licenseKey .= $codeAlphabet[$rnd];
}
return $licenseKey;
} | php | {
"resource": ""
} |
q8876 | Asset.printStyles | train | public function printStyles()
{
foreach ($this->styles as $key => $options) {
$href = (is_string($options['src'])) ? $options['src'] : $this->getStyleLink($key);
if ($options['with_version']) {
$href = call_user_func_array($this->assetInsertMethod, [$href, $this->assetVersion]);
}
echo "<link rel='stylesheet' href='" . $href . "' type='text/css' media='" . $options["media"] . "' />\n";
}
} | php | {
"resource": ""
} |
q8877 | Asset.enqueueStyle | train | public function enqueueStyle($slug, $src = false, $media = 'all', $withVersion = true)
{
$this->styles[$slug] = [
'src' => $src,
'media' => $media,
'with_version' => $withVersion,
];
} | php | {
"resource": ""
} |
q8878 | Asset.printInlineScript | train | public function printInlineScript($print = true)
{
$this->scriptNonces[] = ($nonce = $this->newNonce());
if ($print) {
echo "<script type='text/javascript' nonce='".$nonce."'>" . $this->scriptInline . "</script>\n";
} else {
return "<script type='text/javascript' nonce='".$nonce."'>" . $this->scriptInline . "</script>\n";
}
} | php | {
"resource": ""
} |
q8879 | Asset.printScript | train | public function printScript()
{
foreach ($this->scripts as $key => $options) {
$src = (is_string($options['src'])) ? $options['src'] : $this->getScriptLink($key);
if ($options['with_version']) {
$src = call_user_func_array($this->assetInsertMethod, [$src, $this->assetVersion]);
}
echo "<script type='text/javascript' src='$src'></script>\n";
}
$this->printInlineScript();
} | php | {
"resource": ""
} |
q8880 | Asset.enqueueScript | train | public function enqueueScript($slug, $src = false, $withVersion = true)
{
$this->scripts[$slug] = [
'src' => $src,
'with_version' => $withVersion,
];
} | php | {
"resource": ""
} |
q8881 | QrCode.get | train | public function get($format = null)
{
if ( ! is_null($format) )
$this->setFormat($format);
ob_start();
call_user_func($this->getFunctionName(), $this->getImage());
return ob_get_clean();
} | php | {
"resource": ""
} |
q8882 | QrCode.save | train | public function save($filename)
{
$this->setFilename($filename);
call_user_func_array($this->getFunctionName(), [$this->getImage(), $filename]);
return $filename;
} | php | {
"resource": ""
} |
q8883 | Requirement.add | train | public function add(SpecificationContract $specification)
{
$this->items->put($specification->uid(), $specification);
return $this;
} | php | {
"resource": ""
} |
q8884 | Requirement.check | train | public function check(): bool
{
return $this->installable = $this->items->filter(function ($specification) {
return $specification->check() === false && $specification->optional() === false;
})->isEmpty();
} | php | {
"resource": ""
} |
q8885 | EtagSetter.getEtag | train | private function getEtag(ResourceObject $ro, HttpCache $httpCache = null) : string
{
$etag = $httpCache instanceof HttpCache && $httpCache->etag ? $this->getEtagByPartialBody($httpCache, $ro) : $this->getEtagByEitireView($ro);
return (string) \crc32(\get_class($ro) . $etag);
} | php | {
"resource": ""
} |
q8886 | ConfiguredValidationListener.onValidate | train | public function onValidate(ValidationEvent $event)
{
try {
$this->validator->validate(
$event->getType(),
$event->getFile(),
'upload_validators'
);
} catch (JbFileUploaderValidationException $e) {
throw new ValidationException($e->getMessage(), null, $e);
}
} | php | {
"resource": ""
} |
q8887 | File.encode | train | public function encode($data, $ttl)
{
$expire = null;
if ($ttl !== null) {
$expire = time() + $ttl;
}
return serialize(array($data, $expire));
} | php | {
"resource": ""
} |
q8888 | TwigWrapper.setTemplatePath | train | private function setTemplatePath($templatePath)
{
$return = false;
if (is_string($templatePath)) {
if ($this->checkTemplatePath($templatePath) === true) {
$this->templatePath[] = $templatePath;
$return = true;
}
}
else if (is_array($templatePath)) {
foreach ($templatePath as $path) {
if ($this->checkTemplatePath($path) === true) {
$this->templatePath[] = $path;
$return = true;
}
}
}
return $return;
} | php | {
"resource": ""
} |
q8889 | TwigWrapper.checkTemplatePath | train | private function checkTemplatePath($templatePath, $exitOnError = true)
{
if (!is_dir($templatePath)) {
if ($exitOnError === true) {
exit();
}
return false;
} else {
return true;
}
} | php | {
"resource": ""
} |
q8890 | TwigWrapper.optimizer | train | private function optimizer()
{
$optimizeOption = -1;
if ($this->environment['cache'] === false) {
$optimizeOption = 2;
}
switch ($optimizeOption) {
case -1:
$nodeVisitorOptimizer = Twig_NodeVisitor_Optimizer::OPTIMIZE_ALL;
break;
case 0:
$nodeVisitorOptimizer = Twig_NodeVisitor_Optimizer::OPTIMIZE_NONE;
break;
case 2:
$nodeVisitorOptimizer = Twig_NodeVisitor_Optimizer::OPTIMIZE_FOR;
break;
case 4:
$nodeVisitorOptimizer = Twig_NodeVisitor_Optimizer::OPTIMIZE_RAW_FILTER;
break;
case 8:
$nodeVisitorOptimizer = Twig_NodeVisitor_Optimizer::OPTIMIZE_VAR_ACCESS;
break;
default:
$nodeVisitorOptimizer = Twig_NodeVisitor_Optimizer::OPTIMIZE_ALL;
break;
}
$optimizer = new Twig_Extension_Optimizer($nodeVisitorOptimizer);
$this->twig->addExtension($optimizer);
} | php | {
"resource": ""
} |
q8891 | TwigWrapper.render | train | public function render($withHeader = true)
{
// DEBUG
if (isset($_GET['twigDebug']) && $_GET['twigDebug'] == 1) {
$this->debug();
}
$this->template = $this->twig->loadTemplate($this->filename);
if ($withHeader === true) {
header('X-UA-Compatible: IE=edge,chrome=1');
header('Content-Type: text/html; charset=utf-8');
}
return $this->template->render($this->data);
} | php | {
"resource": ""
} |
q8892 | WhereChunk.build | train | public function build()
{
$params = [];
if ($this->value !== null) {
$op = !is_null($this->operator) ? $this->operator : '=';
$paramName = str_replace('.', '_', $this->key);
if ($op == 'BETWEEN') {
$sql = "{$this->key} $op ? AND ?";
$between = explode('AND', $this->value);
$params[':dateFrom'] = trim($between[0]);
$params[':dateTo'] = trim($between[1]);
} else {
$sql = "{$this->key} $op ?"; // $sql = "{$this->key} $op {$paramName}";
$params[":{$paramName}"] = $this->value;
}
} else {
$sql = $sql = "{$this->key} IS NULL ";
}
return [$sql, $params];
} | php | {
"resource": ""
} |
q8893 | Seed.getFormat | train | public function getFormat()
{
switch (true) {
case ($this->encoder instanceof Base32Encoder):
$format = self::FORMAT_BASE32;
break;
case ($this->encoder instanceof HexEncoder):
$format = self::FORMAT_HEX;
break;
case ($this->encoder instanceof RawEncoder):
default:
$format = self::FORMAT_RAW;
}
return $format;
} | php | {
"resource": ""
} |
q8894 | Seed.setFormat | train | public function setFormat($format)
{
switch ($format) {
case self::FORMAT_BASE32:
$this->encoder = new Base32Encoder();
break;
case self::FORMAT_HEX:
$this->encoder = new HexEncoder();
break;
case self::FORMAT_RAW:
default:
$this->encoder = new RawEncoder();
}
return $this;
} | php | {
"resource": ""
} |
q8895 | Seed.setValue | train | public function setValue($value, $format = null)
{
$this->value = $this->decode($value, $format);
} | php | {
"resource": ""
} |
q8896 | Seed.decode | train | private function decode($seed, $format = null)
{
$encoder = new RawEncoder();
// Auto-detect
if ($format === null) {
if (preg_match('/^[0-9a-f]+$/i', $seed)) {
$encoder = new HexEncoder();
} elseif (preg_match('/^[2-7a-z]+$/i', $seed)) {
$encoder = new Base32Encoder();
}
// User-specified
} else {
if ($format == self::FORMAT_HEX) {
$encoder = new HexEncoder();
} elseif ($format == self::FORMAT_BASE32) {
$encoder = new Base32Encoder();
}
}
$output = $encoder->decode($seed);
return $output;
} | php | {
"resource": ""
} |
q8897 | Seed.encode | train | private function encode($seed, $format = null)
{
$encoder = $this->encoder;
if ($format == self::FORMAT_HEX) {
$encoder = new HexEncoder();
} elseif ($format == self::FORMAT_BASE32) {
$encoder = new Base32Encoder();
} elseif ($format == self::FORMAT_RAW) {
$encoder = new RawEncoder();
}
$output = $encoder->encode($seed);
return $output;
} | php | {
"resource": ""
} |
q8898 | TemplatedShortcode.init_template_loader | train | public function init_template_loader() {
$loader_class = $this->hasConfigKey( 'template', 'custom_loader' )
? $this->getConfigKey( 'template', 'custom_loader' )
: $this->get_default_template_loader_class();
$filter_prefix = $this->hasConfigKey( 'template', 'filter_prefix' )
? $this->getConfigKey( 'template', 'filter_prefix' )
: $this->get_default_filter_prefix();
$template_dir = $this->hasConfigKey( 'template', 'template_directory' )
? $this->getConfigKey( 'template', 'template_directory' )
: $this->get_default_template_directory();
$view_dir = $this->hasConfigKey( 'view' )
? $this->get_directory_from_view( $this->getConfigKey( 'view' ) )
: $this->get_default_view_directory();
return new $loader_class(
$filter_prefix,
$template_dir,
$view_dir
);
} | php | {
"resource": ""
} |
q8899 | Bindings.prepare | train | private function prepare($args)
{
$bindings = array();
// Two parameters (key, value).
if (count($args) == 2) {
$bindings[$args[0]] = $args[1];
}
// Array of parameters.
elseif (is_array($args[0])) {
$bindings = $args[0];
}
return $bindings;
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.