_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q250700 | TicketClient.getByIds | validation | public function getByIds(array $ids, $page=1, $per_page=100){
return $this->getCollection('tickets/show_many.json?ids='.implode(',',$ids), 'tickets',$page, $per_page);
} | php | {
"resource": ""
} |
q250701 | TicketClient.deleteTickets | validation | public function deleteTickets(array $tickets){
$ids = array();
foreach($tickets as $ticket){
$ids[] = $ticket->getId();
}
return parent::deleteByIds($ids, 'tickets/destroy_many.json');
} | php | {
"resource": ""
} |
q250702 | FiltersAbstract.appendValueFilter | validation | public function appendValueFilter($key, $value)
{
if (!empty($value)) {
if ($this->getValues($key)) {
return $this->append($key, $value);
} else {
return $this->addValuesFilter($key, [$value]);
}
} else {
//do nothing
return $this;
}
} | php | {
"resource": ""
} |
q250703 | LurkerWatcher.getEventMap | validation | private function getEventMap()
{
return [
WatcherInterface::CREATE_EVENT => FilesystemEvent::CREATE,
WatcherInterface::MODIFY_EVENT => FilesystemEvent::MODIFY,
WatcherInterface::DELETE_EVENT => FilesystemEvent::DELETE,
WatcherInterface::ALL_EVENT => FilesystemEvent::ALL
];
} | php | {
"resource": ""
} |
q250704 | SidebarComposer.compose | validation | public function compose(View $view)
{
$this->sidebar->loadItemsFromConfig('arcanesoft.foundation.sidebar.items');
$this->sidebar->setCurrent(
Arr::get($view->getData(), 'current_page', '')
);
} | php | {
"resource": ""
} |
q250705 | PackagesServiceProvider.registerLogViewerPackage | validation | private function registerLogViewerPackage()
{
$this->registerProvider(LogViewerServiceProvider::class);
$config = $this->config();
// Setting up the LogViewer config.
$config->set('log-viewer.route.enabled', false);
$config->set(
'log-viewer.menu.filter-route',
$config->get('arcanesoft.foundation.log-viewer.filter-route')
);
} | php | {
"resource": ""
} |
q250706 | AbstractCollection.getSummary | validation | public function getSummary()
{
$string = "---\n";
foreach ($this->getWords() as $k => $v) {
$string .= '['.$k.']: Docs:'.$v['docs']
.' | Hits:'.$v['hits']."\n";
}
return $string;
} | php | {
"resource": ""
} |
q250707 | ServerRequirementsComposer.getServerModules | validation | private function getServerModules(array $requirements)
{
if ( ! function_exists('apache_get_modules')) {
return collect([]);
}
$modules = apache_get_modules();
$requirements = array_combine($requirements, $requirements);
return collect($requirements)->transform(function ($requirement) use ($modules) {
return in_array($requirement, $modules);
});
} | php | {
"resource": ""
} |
q250708 | Attachable.initializer | validation | protected function initializer(string $key, array $storage): void
{
$this->_name = $key;
$this->attached($storage);
} | php | {
"resource": ""
} |
q250709 | SystemRoutes.map | validation | public function map()
{
$this->namespace('System')->prefix('system')->name('system.')->group(function () {
$this->registerSystemInformationRoutes();
$this->registerLogViewerRoutes();
$this->registerRouteViewerRoutes();
});
} | php | {
"resource": ""
} |
q250710 | SystemRoutes.registerLogViewerRoutes | validation | private function registerLogViewerRoutes()
{
$this->prefix('log-viewer')->name('log-viewer.')->group(function () {
$this->get('/', 'LogViewerController@index')
->name('index'); // admin::foundation.system.log-viewer.index
$this->prefix('logs')->name('logs.')->group(function() {
$this->get('/', 'LogViewerController@listLogs')
->name('list'); // admin::foundation.system.log-viewer.logs.list
$this->prefix('{logviewer_log_date}')->group(function () {
$this->get('/', 'LogViewerController@show')
->name('show'); // admin::foundation.system.log-viewer.logs.show
$this->get('download', 'LogViewerController@download')
->name('download'); // admin::foundation.system.log-viewer.logs.download
$this->get('{level}', 'LogViewerController@showByLevel')
->name('filter'); // admin::foundation.system.log-viewer.logs.filter
$this->get('{level}/search', 'LogViewerController@search')
->name('search'); // admin::foundation.system.log-viewer.logs.search
$this->delete('delete', 'LogViewerController@delete')
->middleware('ajax')
->name('delete'); // admin::foundation.system.log-viewer.logs.delete
});
});
});
} | php | {
"resource": ""
} |
q250711 | Router.loadingGroups | validation | protected function loadingGroups(): void
{
foreach ($this->groups as $group) {
$this->addPattern($group->toArray());
}
} | php | {
"resource": ""
} |
q250712 | PaginatorAbstract.paginate | validation | public function paginate($numTotal, $page, $limit = 10)
{
$this->setTotalItemCount($numTotal);
$this->setCurrentPageNumber($page);
$this->setItemNumberPerPage($limit);
} | php | {
"resource": ""
} |
q250713 | Messages.deleteSucceeded | validation | public function deleteSucceeded( $message = null ) {
if ( is_null( $message ) )
$message = $this->config[ 'success' ][ 'delete' ];
return $this->setStatusCode( 200 )
->setStatusText( 'success' )
->respondWithMessage( $message );
} | php | {
"resource": ""
} |
q250714 | Messages.deleteFaild | validation | public function deleteFaild( $message = null ) {
if ( is_null( $message ) )
$message = $this->config[ 'fail' ][ 'delete' ];
return $this->setStatusCode( 447 )
->setStatusText( 'fail' )
->setErrorCode( 5447 )
->respondWithMessage( $message );
} | php | {
"resource": ""
} |
q250715 | StringReader.readOne | validation | public function readOne()
{
if ($this->pos <= $this->max) {
$value = $this->string[$this->pos];
$this->pos += 1;
} else {
$value = null;
}
return $value;
} | php | {
"resource": ""
} |
q250716 | StringReader.stripQuotes | validation | public function stripQuotes($string)
{
// Only remove exactly one quote from the start and the end,
// and then only if there is one at each end.
if (strlen($string) < 2 || substr($string, 0, 1) !== '"' || substr($string, -1, 1) !== '"') {
// Too short, or does not start or end with a quote.
return $string;
}
// Return the middle of the string, from the second character to the second-but-last.
return substr($string, 1, -1);
} | php | {
"resource": ""
} |
q250717 | ModuleDlstatsStatistics.getStartDate | validation | protected function getStartDate()
{
$StartDate = false;
$objStartDate = \Database::getInstance()->prepare("SELECT
MIN(`tstamp`) AS YMD
FROM `tl_dlstatdets`
WHERE 1")
->execute();
if ($objStartDate->YMD !== null)
{
$StartDate = $this->parseDate($GLOBALS['TL_CONFIG']['dateFormat'], $objStartDate->YMD);
}
return $StartDate;
} | php | {
"resource": ""
} |
q250718 | ModuleDlstatsStatistics.getTopDownloads | validation | protected function getTopDownloads($limit=20)
{
$arrTopDownloads = array();
$objTopDownloads = \Database::getInstance()->prepare("SELECT `tstamp`, `filename`, `downloads`, `id`
FROM `tl_dlstats`
ORDER BY `downloads` DESC")
->limit($limit)
->execute();
$intRows = $objTopDownloads->numRows;
if ($intRows>0)
{
while ($objTopDownloads->next())
{
$c4d = $this->check4details($objTopDownloads->id);
$arrTopDownloads[] = array( $objTopDownloads->filename
, $this->getFormattedNumber($objTopDownloads->downloads,0)
, $this->parseDate($GLOBALS['TL_CONFIG']['datimFormat'], $objTopDownloads->tstamp)
, $objTopDownloads->id
, $c4d
, $objTopDownloads->downloads //no formatted number for sorting
, $objTopDownloads->tstamp //for sorting
);
}
}
return $arrTopDownloads;
} | php | {
"resource": ""
} |
q250719 | ModuleDlstatsStatistics.getCalendarDayDownloads | validation | protected function getCalendarDayDownloads($limit=30)
{
$arrCalendarDayDownloads = array();
$CalendarDays = date('Y-m-d', mktime(0, 0, 0, date("m"), date("d")-$limit, date("Y") ) );
$objCalendarDayDownloads = \Database::getInstance()
->prepare("SELECT dl.`id`
, FROM_UNIXTIME(det.`tstamp`,GET_FORMAT(DATE,'ISO')) as datum
, count(dl.`filename`) as downloads
, dl.`filename`
FROM `tl_dlstats` dl
INNER JOIN `tl_dlstatdets` det on dl.id = det.pid
WHERE FROM_UNIXTIME(det.`tstamp`,GET_FORMAT(DATE,'ISO')) >=?
GROUP BY dl.`id`, datum
ORDER BY datum DESC, `filename`")
->execute($CalendarDays);
while ($objCalendarDayDownloads->next())
{
$viewDate = $this->parseDate($GLOBALS['TL_CONFIG']['dateFormat'], strtotime($objCalendarDayDownloads->datum) );
$c4d = $this->check4details($objCalendarDayDownloads->id);
$arrCalendarDayDownloads[] = array(
$viewDate
, $objCalendarDayDownloads->filename
, $this->getFormattedNumber($objCalendarDayDownloads->downloads,0)
, $objCalendarDayDownloads->id
, $c4d
, $objCalendarDayDownloads->downloads
, strtotime($objCalendarDayDownloads->datum)
);
}
return $arrCalendarDayDownloads;
} | php | {
"resource": ""
} |
q250720 | Main.respondWithMessage | validation | public function respondWithMessage( $message = null ) {
$res[ 'status' ] = $this->getStatusText();
//if it's about failure
if ( $this->getErrorCode() ) {
$res[ 'error' ] = $this->getErrorCode();
if ( is_null( $message ) )
$res[ 'message' ] = $this->getErrorMessage();
else
$res[ 'message' ] = $message;
} else {
$res[ 'message' ] = $message;
}
return $this->respond( $res );
} | php | {
"resource": ""
} |
q250721 | Main.setErrorCode | validation | public function setErrorCode( $errorCode ) {
$this->error = $this->config[ $errorCode ];
$this->errorCode = $errorCode;
return $this;
} | php | {
"resource": ""
} |
q250722 | Main.respondWithResult | validation | public function respondWithResult( $data = NULL ) {
$res[ 'status' ] = $this->getStatusText();
//if it's about laravel validation error
if ( $this->getErrorCode() && $this->getStatusCode() == 420 ) {
$res[ 'error' ] = $this->getErrorCode();
$res[ 'message' ] = $data;
} else {
$res[ 'result' ] = $data;
}
return $this->respond( $res );
} | php | {
"resource": ""
} |
q250723 | FoldersPermissionsComposer.prepare | validation | private function prepare(array $folders)
{
return collect($folders)->mapWithKeys(function ($folder) {
$path = base_path($folder);
return [
$folder => [
'chmod' => (int) substr(sprintf('%o', fileperms($path)), -4),
'writable' => is_writable($path),
],
];
});
} | php | {
"resource": ""
} |
q250724 | BaseEntity.toArray | validation | public function toArray($changedOnly = false, $extraData = null)
{
$vars = get_object_vars($this);
$object = array();
if (!is_array($this->_changes)) {
$this->_changes = array();
}
if(is_array($extraData)){
$vars = array_merge($vars, $extraData);
}
foreach ($vars as $k => $v) {
if (strpos($k, '_') !== 0 && $v !== null && (!$changedOnly || array_key_exists($k, $this->_changes) || array_key_exists($k, $extraData) )) {
if (is_array($v)) {
$subV = array();
foreach ($v as $sub) {
if (is_a($sub, 'Dlin\Zendesk\Entity\BaseEntity')) {
$subV[] = $sub->toArray();
} else {
$subV[] = $sub;
}
}
$object[$k] = $subV;
} else if (is_a($v, 'Dlin\Zendesk\Entity\BaseEntity')) {
$object[$k] = $v->toArray();
} else {
$object[$k] = $v;
}
}
}
return $object;
} | php | {
"resource": ""
} |
q250725 | BaseEntity.fromArray | validation | public function fromArray(array $array)
{
foreach ($array as $k => $v) {
if (!is_null($v) && property_exists(get_class($this), $k)) {
$meta = new \ReflectionProperty(get_class($this), $k);
$info = $this->parsePropertyDocComment($meta->getDocComment());
$type = $info['type'];
if (strtolower($type) == "array" && $elementType = $info['array_element']) {
if (class_exists($elementType)) {
$children = array();
foreach ($v as $subV) {
$newElement = new $elementType();
$children[] = $newElement->fromArray($subV);
}
$this->$k = $children;
} else {
throw new \Exception('@element Class Not Found:' . $elementType);
}
} else if (class_exists($type)) {
$typeObject = new $type();
$this->$k = $typeObject->fromArray($v);
} else {
$this->$k = $v;
}
}
}
return $this;
} | php | {
"resource": ""
} |
q250726 | BaseEntity.checkCreatable | validation | public function checkCreatable()
{
if (property_exists($this, 'id') && $this->id > 0) {
throw new \Exception(get_class($this) . " has ID:" . $this->id() . " thus not creatable.");
}
} | php | {
"resource": ""
} |
q250727 | BaseEntity.checkFieldsSet | validation | protected function checkFieldsSet($fields)
{
foreach ($fields as $field) {
if (property_exists($this, $field) && $this->$field === null) {
throw new \Exception("'$field' is required");
}
}
} | php | {
"resource": ""
} |
q250728 | InstallCommand.installModules | validation | private function installModules()
{
$this->frame('Installing the modules');
$this->line('');
foreach ($this->config()->get('arcanesoft.foundation.modules.commands.install', []) as $command) {
$this->call($command);
}
$this->call('db:seed', ['--class' => DatabaseSeeder::class]);
$this->line('');
$this->comment('Modules installed !');
$this->line('');
} | php | {
"resource": ""
} |
q250729 | Paginator.getPages | validation | public function getPages()
{
if ($this->getPageRange() > $this->getPagesCount()) {
$this->setPageRange($this->getPagesCount());
}
$delta = ceil($this->getPageRange() / 2);
if ($this->getCurrentPageNumber() - $delta > $this->getPagesCount() - $this->getPageRange()) {
$pages = range($this->getPagesCount() - $this->getPageRange() + 1, $this->getPagesCount());
} else {
if ($this->getCurrentPageNumber() - $delta < 0) {
$delta = $this->getCurrentPageNumber();
}
$offset = $this->getCurrentPageNumber() - $delta;
$pages = range($offset + 1, $offset + $this->getPageRange());
}
return $pages;
} | php | {
"resource": ""
} |
q250730 | DataFileModel.getFileData | validation | public function getFileData($sFieldName) {
if(empty($sFieldName)) {
return null;
}
/** @var File $obFile */
$obFile = $this->$sFieldName;
if(empty($obFile) || !$obFile instanceof File) {
return null;
}
return $this->getFileDataValue($obFile);
} | php | {
"resource": ""
} |
q250731 | DataFileModel.getFileDataValue | validation | protected function getFileDataValue($obFile) {
if(empty($obFile) || !$obFile instanceof File) {
return null;
}
$sUploadFolder = Config::get('cms.storage.uploads.path', '/storage/app/uploads');
return [
'full_path' => $obFile->getPath(),
'path' => $sUploadFolder . str_replace('uploads', '', $obFile->getDiskPath()),
'title' => $obFile->getAttribute('title'),
'alt' => $obFile->getAttribute('description'),
];
} | php | {
"resource": ""
} |
q250732 | DataFileModel.getFileListData | validation | public function getFileListData($sFieldName) {
if(empty($sFieldName)) {
return [];
}
/** @var Collection $obFileList */
$obFileList = $this->$sFieldName;
if($obFileList->isEmpty()) {
return [];
}
$arResult = [];
/** @var File $obFile */
foreach($obFileList as $obFile) {
if(empty($obFile) || !$obFile instanceof File) {
continue;
}
$arResult[] = $this->getFileDataValue($obFile);
}
return $arResult;
} | php | {
"resource": ""
} |
q250733 | ApplicationInfoComposer.getApplicationSize | validation | private function getApplicationSize()
{
$size = cache()->remember('foundation.app.size', 5, function () {
return $this->getFolderSize(base_path());
});
return $this->formatSize($size);
} | php | {
"resource": ""
} |
q250734 | ApplicationInfoComposer.getFolderSize | validation | private function getFolderSize($path)
{
$size = 0;
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path)) as $directory) {
/** @var \SplFileInfo $directory */
$size += $directory->getSize();
}
return $size;
} | php | {
"resource": ""
} |
q250735 | ApplicationInfoComposer.formatSize | validation | private function formatSize($bytes)
{
$kb = 1024;
$mb = $kb * 1024;
$gb = $mb * 1024;
$tb = $gb * 1024;
if (($bytes >= 0) && ($bytes < $kb)) {
return $bytes . ' B';
}
elseif (($bytes >= $kb) && ($bytes < $mb)) {
return ceil($bytes / $kb).' KB';
}
elseif (($bytes >= $mb) && ($bytes < $gb)) {
return ceil($bytes / $mb).' MB';
}
elseif (($bytes >= $gb) && ($bytes < $tb)) {
return ceil($bytes / $gb).' GB';
}
elseif ($bytes >= $tb) {
return ceil($bytes / $tb).' TB';
}
return $bytes.' B';
} | php | {
"resource": ""
} |
q250736 | SphinxService.createService | validation | public function createService()
{
$host = $this->getParameters()->get('host');
$port = $this->getParameters()->get('port');
$timeout = $this->getParameters()->get('timeout');
if (is_null($host) || is_null($port)) {
throw new \Exception(
'No sphinx server information found within the configuration!'
);
}
$sphinxClient = new SphinxClient();
$sphinxClient->SetServer($host, $port);
$sphinxClient->SetConnectTimeout($timeout);
$sphinxClient->SetArrayResult(true);
$sphinxClient->setMatchModeByModeName('any');
$sphinxClient->SetSortMode(SPH_SORT_RELEVANCE);
$sphinxClient->SetRankingMode(SPH_RANK_PROXIMITY);
return $sphinxClient;
} | php | {
"resource": ""
} |
q250737 | BaseClient.getCollection | validation | public function getCollection($end_point, $collectionName, $page = 1, $per_page = 100, $sort_by = null, $sort_order = 'asc')
{
$end_point = strtolower($end_point);
if (strpos($end_point, 'http') !== 0) {
$end_point = $this->api->getApiUrl() . $end_point;
}
$request = $this->api->get($end_point);
$query = $request->getQuery()->set('page', $page)->set('per_page', $per_page);
if ($sort_by) {
$query->set('sort_by', $sort_by)->set('sort_order', $sort_order == 'asc' ? 'asc' : 'desc');
}
$response = $this->processRequest($request);
$values = $response->json();
$result = new PaginatedResult();
$result->setClient($this);
if (array_key_exists('count', $values)) {
$result->setCount($values['count']);
}
/*
if (array_key_exists('next_page', $values)) {
$result->setNextPage($values['next_page']); //Note: the api skips the per_page parameter, making it useless
}
if (array_key_exists('previous_page', $values)) {
$result->setPreviousPage($values['previous_page']); //Note: the api always return null
}
*/
$result->setCurrentPage($page);
$result->setPerPage($per_page);
$result->setEndPoint($end_point);
$type = $this->getType();
if (array_key_exists($collectionName, $values) && is_array($values[$collectionName])) {
foreach ($values[$collectionName] as $value) {
$entity = new $type();
$this->manage($entity);
$result[] = $entity->fromArray($value);
}
}
return $result;
} | php | {
"resource": ""
} |
q250738 | BaseClient.getOne | validation | protected function getOne($end_point)
{
$end_point = strtolower($end_point);
if (strpos($end_point, 'http') !== 0) {
$end_point = $this->api->getApiUrl() . $end_point;
}
$request = $this->api->get($end_point);
$response = $this->processRequest($request);
$result = $response->json();
$type = $this->getType();
$className = explode('\\', $type);
$baseName = strtolower(end($className));
if ($result && isset($result[$baseName])) {
$t = new $type();
$t->setManagingClient($this);
return $t->fromArray($result[$baseName]);
}
return null;
} | php | {
"resource": ""
} |
q250739 | BaseClient.saveEntity | validation | public function saveEntity(BaseEntity $entity, $endPoint='', $extraData=null)
{
$end_point = strtolower($endPoint);
if (strpos($end_point, 'http') !== 0) {
$end_point = $this->api->getApiUrl() . $end_point;
}
$type = $this->getType();
$className = explode('\\', $type);
$baseName = strtolower(end($className));
$method = $entity->getId() ? 'put':'post';
if($method == 'post'){
$entity->checkCreatable();
}
$changes = $entity->toArray(true, $extraData);
if(empty($changes)){
return null;
}
$request = $this->api->$method($end_point, null, json_encode(array($baseName => $changes)));
$response = $this->processRequest($request);
$result = $response->json();
if ($result && isset($result[$baseName])) {
$changeResult = new ChangeResult();
$t = new $type();
$this->manage($t);
$t->fromArray($result[$baseName]);
$changeResult->setItem($t);
if (isset($result['audit'])) {
$audit = new TicketAudit();
$audit->fromArray($result['audit']);
$changeResult->setAudit($audit);
}
return $changeResult;
}
return null;
} | php | {
"resource": ""
} |
q250740 | BaseClient.processRequest | validation | public function processRequest(RequestInterface $request)
{
$response = $request->send();
$attempt = 0;
while ($response->getStatusCode() == 429 && $attempt < 5) {
$wait = $response->getHeader('Retry-After');
if ($wait > 0) {
sleep($wait);
}
$attempt++;
$response = $request->send();
}
if ($response->getStatusCode() >= 500) {
throw new ZendeskException('Zendesk Server Error Detected.');
}
if ($response->getStatusCode() >= 400) {
if ($response->getContentType() == 'application/json') {
$result = $response->json();
$description = array_key_exists($result, 'description') ? $result['description'] : 'Invalid Request';
$value = array_key_exists($result, 'value') ? $result['value'] : array();
$exception = new ZendeskException($description);
$exception->setError($value);
throw $exception;
} else {
throw new ZendeskException('Invalid API Request');
}
}
return $response;
} | php | {
"resource": ""
} |
q250741 | WatcherPlugin.supportsEvent | validation | public function supportsEvent($eventId)
{
$supportedEvents = [WatcherInterface::CREATE_EVENT, WatcherInterface::MODIFY_EVENT, WatcherInterface::DELETE_EVENT, WatcherInterface::ALL_EVENT];
return array_search($eventId, $supportedEvents, true) !== false;
} | php | {
"resource": ""
} |
q250742 | WatcherPlugin.watch | validation | public function watch(WatcherInterface $watcher)
{
$events = $this->getEvents();
$watcher->watch($this->getTrackedPaths(), $events, [$this, 'runPeridot']);
} | php | {
"resource": ""
} |
q250743 | WatcherPlugin.runPeridot | validation | public function runPeridot(InputInterface $input, OutputInterface $output)
{
global $argv;
$command = $this->joinCommand($argv);
$process = new Process($command);
$process->run(function($type, $buffer) use ($output) {
$buffer = preg_replace('/\[([\d]{1,2})m/', "\033[$1m", $buffer);
$output->write($buffer);
});
} | php | {
"resource": ""
} |
q250744 | WatcherPlugin.joinCommand | validation | public function joinCommand(array $parts)
{
$command = 'php ' . implode(' ', $parts);
$stripped = str_replace('--watch', '', $command);
return trim($stripped);
} | php | {
"resource": ""
} |
q250745 | WatcherPlugin.listen | validation | private function listen()
{
$this->emitter->on('peridot.configure', [$this, 'onPeridotConfigure']);
$this->emitter->on('peridot.start', [$this, 'onPeridotStart']);
$this->emitter->on('peridot.end', [$this, 'onPeridotEnd']);
} | php | {
"resource": ""
} |
q250746 | LogViewerController.index | validation | public function index()
{
$this->authorize(LogViewerPolicy::PERMISSION_DASHBOARD);
$stats = $this->logViewer->statsTable();
$percents = $this->calcPercentages($stats->footer(), $stats->header());
$this->setTitle('LogViewer Dashboard');
$this->addBreadcrumb('Dashboard');
return $this->view('admin.system.log-viewer.dashboard', compact('percents'));
} | php | {
"resource": ""
} |
q250747 | LogViewerController.listLogs | validation | public function listLogs(Request $request)
{
$this->authorize(LogViewerPolicy::PERMISSION_LIST);
$stats = $this->logViewer->statsTable();
$headers = $stats->header();
// $footer = $stats->footer();
$page = $request->get('page', 1);
$offset = ($page * $this->perPage) - $this->perPage;
$rows = new LengthAwarePaginator(
array_slice($stats->rows(), $offset, $this->perPage, true),
count($stats->rows()),
$this->perPage,
$page
);
$rows->setPath($request->url());
$this->setTitle($title = trans('foundation::log-viewer.titles.logs-list'));
$this->addBreadcrumb($title);
return $this->view('admin.system.log-viewer.list', compact('headers', 'rows', 'footer'));
} | php | {
"resource": ""
} |
q250748 | LogViewerController.show | validation | public function show(Log $log)
{
$this->authorize(LogViewerPolicy::PERMISSION_SHOW);
$levels = $this->logViewer->levelsNames();
$entries = $log->entries($level = 'all')->paginate($this->perPage);
$this->addBreadcrumbRoute(trans('foundation::log-viewer.titles.logs-list'), 'admin::foundation.system.log-viewer.logs.list');
$this->setTitle($title = "Log : {$log->date}");
$this->addBreadcrumb($title);
return $this->view('admin.system.log-viewer.show', compact('log', 'levels', 'level', 'search', 'entries'));
} | php | {
"resource": ""
} |
q250749 | LogViewerController.showByLevel | validation | public function showByLevel(Log $log, $level)
{
$this->authorize(LogViewerPolicy::PERMISSION_SHOW);
if ($level == 'all')
return redirect()->route('admin::foundation.system.log-viewer.logs.show', [$log->date]);
$levels = $this->logViewer->levelsNames();
$entries = $this->logViewer->entries($log->date, $level)->paginate($this->perPage);
$this->addBreadcrumbRoute(trans('foundation::log-viewer.titles.logs-list'), 'admin::foundation.system.log-viewer.logs.list');
$this->setTitle($log->date.' | '.ucfirst($level));
$this->addBreadcrumbRoute($log->date, 'admin::foundation.system.log-viewer.logs.show', [$log->date]);
$this->addBreadcrumb(ucfirst($level));
return $this->view('admin.system.log-viewer.show', compact('log', 'levels', 'entries', 'level'));
} | php | {
"resource": ""
} |
q250750 | LogViewerController.search | validation | public function search(Log $log, $level = 'all', Request $request)
{
if (is_null($query = $request->get('query')))
return redirect()->route('admin::foundation.system.log-viewer.logs.show', [$log->date]);
$levels = $this->logViewer->levelsNames();
$entries = $log->entries($level)->filter(function (LogEntry $value) use ($query) {
return Str::contains($value->header, $query);
})->paginate($this->perPage);
return $this->view('admin.system.log-viewer.show', compact('log', 'levels', 'level', 'query', 'entries'));
} | php | {
"resource": ""
} |
q250751 | LogViewerController.download | validation | public function download(Log $log)
{
$this->authorize(LogViewerPolicy::PERMISSION_DOWNLOAD);
return $this->logViewer->download($log->date);
} | php | {
"resource": ""
} |
q250752 | LogViewerController.delete | validation | public function delete(Log $log)
{
$this->authorize(LogViewerPolicy::PERMISSION_DELETE);
$date = $log->date;
if ($this->logViewer->delete($date)) {
$this->notifySuccess(
$message = trans('foundation::log-viewer.messages.deleted.message', compact('date')),
trans('foundation::log-viewer.messages.deleted.title')
);
return $this->jsonResponseSuccess(compact('message'));
}
return $this->jsonResponseError([
'message' => "An error occurred while deleting the log [$date]"
]);
} | php | {
"resource": ""
} |
q250753 | PermissionsTableSeeder.getLogViewerPermissions | validation | private function getLogViewerPermissions()
{
return [
[
'name' => 'LogViewer - View dashboard',
'description' => 'Allow to view the LogViewer dashboard.',
'slug' => LogViewerPolicy::PERMISSION_DASHBOARD,
],
[
'name' => 'LogViewer - List all logs',
'description' => 'Allow to list all the logs.',
'slug' => LogViewerPolicy::PERMISSION_LIST,
],
[
'name' => 'LogViewer - View a log',
'description' => 'Allow to display a log.',
'slug' => LogViewerPolicy::PERMISSION_SHOW,
],
[
'name' => 'LogViewer - Download a log',
'description' => 'Allow to download a log.',
'slug' => LogViewerPolicy::PERMISSION_DOWNLOAD,
],
[
'name' => 'LogViewer - Delete a log',
'description' => 'Allow to delete a log.',
'slug' => LogViewerPolicy::PERMISSION_DELETE,
],
];
} | php | {
"resource": ""
} |
q250754 | SphinxClient.setMatchModeByModeName | validation | public function setMatchModeByModeName($modeName)
{
$modes = [
'all' => 0,
'any' => 1,
'phrase' => 2,
'boolean' => 3,
'extended' => 4,
'fullscan' => 5,
];
if (array_key_exists($modeName, $modes)) {
$mode = $modes[$modeName];
$this->SetMatchMode($mode);
} else {
throw new \LogicException('Wrong Mode');
}
} | php | {
"resource": ""
} |
q250755 | SphinxClient.addFacetedQuery | validation | public function addFacetedQuery($query, $index, array $keys)
{
$this->AddQuery($query, $index);
//Clear Offset
$currentOffset = $this->_offset;
$mode = $this->_sort;
$sortby = $this->_sortby;
$limit = $this->_limit;
$this->_offset = 0;
$this->_sort = 0;
$this->_sortby = '';
$this->SetLimits(0, 999);
foreach ($keys as $key) {
$this->setGroupByAttr($key);
$this->AddQuery($query, $index);
}
//Reset
$this->_offset = $currentOffset;
$this->_sort = $mode;
$this->_sortby = $sortby;
$this->SetLimits($currentOffset, $limit);
} | php | {
"resource": ""
} |
q250756 | Logger._initLoggerCascade | validation | private function _initLoggerCascade($configFile, $loggerName)
{
$err = '';
try {
$fs = $this->_obm->get(Filesystem::class);
if ($fs->isAbsolutePath($configFile)) {
$fileName = $configFile;
} else {
$fileName = BP . '/' . $configFile;
}
$realPath = realpath($fileName);
if ($realPath) {
Cascade::fileConfig($realPath);
$this->_logger = Cascade::getLogger($loggerName);
} else {
$err = "Cannot open logging configuration file '$fileName'. Default Magento logger is used.";
}
} catch (\Exception $e) {
$err = $e->getMessage();
} finally {
if (is_null($this->_logger)) {
$this->_logger = $this->_obm->get(\Magento\Framework\Logger\Monolog::class);
$this->warning($err);
}
}
} | php | {
"resource": ""
} |
q250757 | Component.settings | validation | public function settings($name = null, $value = null)
{
switch (func_num_args()) {
case 0: // they want it all
return $this->info('settings');
break;
case 1: // they want to retrieve a specific setting
return $this->info('settings', func_get_arg(0));
break;
case 2: // they want to establish a setting
$update = false;
list($name, $value) = func_get_args();
$current = $this->info('settings', $name);
if (is_null($value)) {
// then we don't want this in the database as "null" is the default value
if (!is_null($current)) {
unset($this->info['settings'][$name]);
$update = true;
}
} elseif ($current !== $value) {
$this->info['settings'][$name] = $value;
$update = true;
}
if ($update) {
$this->exec('UPDATE config SET settings = ?', serialize($this->info['settings']));
}
break;
}
} | php | {
"resource": ""
} |
q250758 | Component.recreate | validation | public function recreate($file)
{
if (is_file($file)) {
return;
}
$virtual = $tables = $indexes = array();
if ($result = $this->query('SELECT type, name, sql FROM sqlite_master')) {
while (list($type, $name, $sql) = $this->fetch($result)) {
if (!empty($sql)) {
switch ($type) {
case 'table':
$tables[$name] = $sql;
break;
case 'index':
$indexes[] = $sql;
break;
}
}
}
$this->close($result);
}
foreach ($tables as $name => $sql) {
if (strpos($sql, 'VIRTUAL TABLE')) {
$virtual[] = $name;
}
}
foreach ($virtual as $table) {
foreach ($tables as $name => $sql) {
if (strpos($name, "{$table}_") === 0) {
unset($tables[$name]);
}
}
}
$db = new self($file);
$this->exec('ATTACH DATABASE '.$this->dbEscape($file).' AS recreate');
foreach ($tables as $table => $sql) {
$db->connection()->exec($sql);
if ($fields = $this->row('SELECT * FROM '.$table.' LIMIT 1', '', 'assoc')) {
$fields = implode(', ', array_keys($fields));
$this->exec("INSERT INTO recreate.{$table} ({$fields}) SELECT * FROM {$table}");
}
}
foreach ($indexes as $sql) {
$db->connection()->exec($sql);
}
$db->connection()->close();
} | php | {
"resource": ""
} |
q250759 | ParameterClosure.getUsage | validation | public function getUsage($withEncapsulation = true, $withAliases = true)
{
$usage = '';
if ($withEncapsulation) {
$usage = ($this->required ? '' : '[');
}
$aliases = ($withAliases ? $this->getAliasUsage() : '');
$usage .= $this->prefix.$this->parameterName.$aliases.' ';
$usage .= $this->getPropertiesAsString();
return $usage.($withEncapsulation ? ($this->required ? '' : ']') : '');
} | php | {
"resource": ""
} |
q250760 | ParameterClosure.getPropertiesAsString | validation | public function getPropertiesAsString()
{
$result = '';
$rFunction = new ReflectionFunction($this->parameterClosure);
if ($rFunction->isVariadic()) {
$result .= '<'.
$rFunction->getParameters()[0]->getName().', ...>';
} else {
for ($i = 0; $i < count($rFunction->getParameters()); $i++) {
$result .= ($result == '' ? '' : ' ').'<'.
$rFunction->getParameters()[$i]->getName().
'>';
}
}
return $result;
} | php | {
"resource": ""
} |
q250761 | ParameterClosure.getAliasUsage | validation | public function getAliasUsage($withEncapsulation = true)
{
$aliases = '';
foreach ($this->aliases as $prefix => $alias) {
if ($withEncapsulation) {
$aliases = ($aliases == '') ? ' (' : $aliases;
$aliases .= ' '.$prefix.$alias;
} else {
$aliases = ($aliases == '') ? $prefix.$alias : $aliases.', '.$prefix.$alias;
}
}
if ($withEncapsulation) {
$aliases .= ($aliases == '') ? '' : ' )';
}
return $aliases;
} | php | {
"resource": ""
} |
q250762 | ParameterClosure.addAlias | validation | public function addAlias($parameterName, $prefix = null)
{
if ($prefix == null) {
$this->aliases[$this->prefix] = $parameterName;
} else {
$this->aliases[$prefix] = $parameterName;
}
} | php | {
"resource": ""
} |
q250763 | PostgresDocumentStore.upsertDoc | validation | public function upsertDoc(string $collectionName, string $docId, array $docOrSubset): void
{
$doc = $this->getDoc($collectionName, $docId);
if($doc) {
$this->updateDoc($collectionName, $docId, $docOrSubset);
} else {
$this->addDoc($collectionName, $docId, $docOrSubset);
}
} | php | {
"resource": ""
} |
q250764 | TravisDeployer.getConfig | validation | private function getConfig()
{
$yaml = new Parser();
$configFile = getenv('TRAVIS_BUILD_DIR') . '/.travis.yml';
$config = $yaml->parse(file_get_contents($configFile));
$config = $config['travisdeployer'];
$this->branches = $config['branches'];
if (count($this->branches) === 0) {
die('No branches are configured to deploy to.' . PHP_EOL);
}
$this->verbose = filter_input(FILTER_VALIDATE_BOOLEAN, $config['verbose']);
} | php | {
"resource": ""
} |
q250765 | TravisDeployer.deploy | validation | public function deploy()
{
$pullRequest = getenv('TRAVIS_PULL_REQUEST');
$branch = getenv('TRAVIS_BRANCH');
if ((int) $pullRequest >= 1) {
die('Not deploying pull requests.' . PHP_EOL);
}
if (!array_key_exists($branch, $this->branches)) {
die('Branch ' . $branch . ' has no environment to deploy to.' . PHP_EOL);
}
$environment = $this->branches[$branch];
echo 'Downloading Deployer.phar...' . PHP_EOL;
passthru('wget http://deployer.org/deployer.phar');
echo 'Deploying...' . PHP_EOL;
$deployCommand = 'php deployer.phar deploy';
$deployCommand .= ' ' . $environment;
$deployCommand .= $this->verbose ? ' -vvv' : '';
passthru($deployCommand);
} | php | {
"resource": ""
} |
q250766 | ParameterParser.parse | validation | public function parse(
$argv = null,
ParameterCluster $parameterCluster = null
) {
$this->initialize($argv, $parameterCluster);
return $this->checkValidityAndContinueParse();
} | php | {
"resource": ""
} |
q250767 | ParameterParser.checkValidityAndContinueParse | validation | private function checkValidityAndContinueParse()
{
$valid = $this->validateRequiredParameters();
if ($valid !== true) {
$this->errorHandler->call(
$this,
$valid,
'Missing required argument: '.$valid->parameterName
);
$this->valid = false;
return [];
}
return $this->parseEvery();
} | php | {
"resource": ""
} |
q250768 | ParameterParser.parseEvery | validation | private function parseEvery()
{
$results = [];
$i = 0;
while ($i < count($this->argv)) {
$parameter = $this->argv[$i];
if ($this->parseSingle($i, $parameter, $results) === false) {
break;
}
}
return $results;
} | php | {
"resource": ""
} |
q250769 | ParameterParser.parseSingle | validation | private function parseSingle(&$i, $parameter, &$results)
{
if ($this->prefixExists($parameter)) {
$closure = $this->getClosure($parameter);
if ($closure != null) {
$prefix = $this->getPrefix($parameter);
$closure_arguments = [];
$rFunction = new ReflectionFunction($closure);
if ($rFunction->isVariadic()) {
$this->parseVariadicParameter(
$i,
$results,
$closure,
$closure_arguments,
$prefix,
$parameter
);
} else {
$this->parseUniadicParameter(
$i,
$results,
$closure,
$closure_arguments,
$prefix,
$parameter,
$rFunction
);
}
$result_key = $this->getRealName($parameter);
$result = $results[$result_key];
if (! $result instanceof ParameterResult) {
if ($result == self::HALT_PARSE) {
$this->haltedBy = $this->getParameterClosure($parameter);
unset($results[$result_key]);
return false;
}
} else {
if ($result->shouldHalt()) {
$this->haltedBy = $this->getParameterClosure($parameter);
if ($result->isHaltOnly()) {
unset($results[$result_key]);
} else {
$results[$result_key] = $result->getValue();
}
return false;
}
}
} else {
$this->respondDefault($i, $results, $parameter);
}
} else {
$this->respondDefault($i, $results, $parameter);
}
return true;
} | php | {
"resource": ""
} |
q250770 | ParameterParser.validateRequiredParameters | validation | private function validateRequiredParameters()
{
$ret = true;
foreach ($this->parameterCluster->prefixes as $prefix => $parameters) {
foreach ($parameters as $parameterClosure) {
if ($parameterClosure->required) {
if (! in_array(
$parameterClosure
->prefix.
$parameterClosure
->parameterName,
$this->argv
)) {
$aliasFound = false;
foreach ($parameterClosure->aliases as $prefix => $alias) {
if (in_array($prefix.$alias, $this->argv)) {
$aliasFound = true;
break;
}
}
if (! $aliasFound) {
$ret = $parameterClosure;
break 2;
}
}
}
}
}
return $ret;
} | php | {
"resource": ""
} |
q250771 | ParameterParser.initialize | validation | private function initialize($argv, $parameterCluster)
{
$this->valid = true;
$this->haltedBy = null;
if ($parameterCluster != null) {
$this->parameterCluster = $parameterCluster;
if ($argv != null) {
$this->preloadAliases($argv);
}
}
if ($argv != null) {
$this->preloadParameters($argv);
}
} | php | {
"resource": ""
} |
q250772 | ParameterParser.respondDefault | validation | private function respondDefault(&$i, &$results, $parameter)
{
$defaultResult = $this->parameterCluster->default->call(
$this, $parameter
);
if ($defaultResult === -1) {
$this->valid = false;
}
$results[$parameter] = $defaultResult;
$i++;
} | php | {
"resource": ""
} |
q250773 | ParameterParser.preloadAliases | validation | private function preloadAliases()
{
foreach (array_keys($this->parameterCluster->prefixes) as $prefix) {
foreach (
$this->parameterCluster->prefixes[$prefix] as $parameterClosure
) {
foreach ($parameterClosure->aliases as $prefix => $alias) {
$aliasClosure = new ParameterClosure(
$prefix,
$alias,
$parameterClosure->parameterClosure
);
$aliasClosure->parent = $parameterClosure;
$this->parameterCluster->add(
$aliasClosure
);
}
}
}
} | php | {
"resource": ""
} |
q250774 | ParameterParser.preloadParameters | validation | private function preloadParameters($argv)
{
array_shift($argv);
$this->argv = [];
while (($argument = array_shift($argv)) != null) {
switch (substr($argument, 0, 1)) {
case '\'': {
$this->parseQuote($argv, $argument, '\'');
break;
}
case '"': {
$this->parseQuote($argv, $argument, '"');
break;
}
default: {
$this->argv[] = $argument;
}
}
}
} | php | {
"resource": ""
} |
q250775 | ParameterParser.parseQuote | validation | private function parseQuote(&$argv, $argument, $quoteType)
{
if (substr($argument, strlen($argument) - 1, 1) !== $quoteType) {
$this->argv[] = substr($argument, 1);
while (
($argument_part = array_shift($argv)) != null
&& substr(
$argument_part,
strlen($argument_part) - 1,
1
) !== $quoteType
) {
$this->argv[count($this->argv) - 1] .= ' '.$argument_part;
}
$this->argv[count($this->argv) - 1] .=
' '.substr($argument_part, 0, strlen($argument_part) - 1);
} else {
$this->argv[] = substr(
substr(
$argument,
1
),
0,
strlen($argument) - 2
);
}
} | php | {
"resource": ""
} |
q250776 | ParameterParser.parseVariadicParameter | validation | private function parseVariadicParameter(
&$i,
&$results,
$closure,
&$closure_arguments,
$prefix,
$parameter
) {
$i++;
while (
isset($this->argv[$i]) &&
($argument = $this->argv[$i]) != null &&
! $this->prefixExists($argument)
) {
$closure_arguments[] = $argument;
$i++;
}
$parameterClosure = $this->getParameterClosure($parameter);
if ($parameterClosure->parent != null) {
if (count($closure_arguments) > 0) {
$results[
$parameterClosure->parent->parameterName
] = $closure(...$closure_arguments);
} else {
$this->valid = false;
if ($this->errorHandler != null) {
$this->errorHandler->call(
$this,
$parameterClosure,
'Missing argument for parameter closure.'
);
}
}
} else {
if (count($closure_arguments) > 0) {
$results[
substr(
$parameter,
strlen($prefix),
strlen($parameter) - strlen($prefix)
)
] = $closure(...$closure_arguments);
} else {
$this->valid = false;
if ($this->errorHandler != null) {
$this->errorHandler->call(
$this,
$parameterClosure,
'Missing argument for parameter closure.'
);
}
}
}
} | php | {
"resource": ""
} |
q250777 | ParameterParser.prefixExists | validation | private function prefixExists($parameter)
{
$prefixExists = false;
foreach (array_keys($this->parameterCluster->prefixes) as $prefix) {
if (substr($parameter, 0, strlen($prefix)) == $prefix) {
$prefixExists = true;
break;
}
}
return $prefixExists;
} | php | {
"resource": ""
} |
q250778 | ParameterParser.getPrefix | validation | private function getPrefix($parameter)
{
$prefix = null;
foreach (array_keys($this->parameterCluster->prefixes) as $_prefix) {
if (substr($parameter, 0, strlen($_prefix)) == $_prefix) {
$prefix = $_prefix;
}
}
return $prefix;
} | php | {
"resource": ""
} |
q250779 | ParameterParser.getRealName | validation | private function getRealName($param)
{
$parameterClosure = $this->getParameterClosure($param);
if ($parameterClosure->parent != null) {
return $parameterClosure->parent->parameterName;
} else {
return $parameterClosure->parameterName;
}
} | php | {
"resource": ""
} |
q250780 | ParameterParser.getClosure | validation | private function getClosure($parameter)
{
$closure = null;
foreach (array_keys($this->parameterCluster->prefixes) as $prefix) {
if (substr($parameter, 0, strlen($prefix)) == $prefix) {
@$closure = $this->parameterCluster->prefixes[$prefix][
substr(
$parameter,
strlen($prefix),
strlen($parameter) - strlen($prefix)
)
]->parameterClosure;
}
}
return $closure;
} | php | {
"resource": ""
} |
q250781 | ParameterParser.getParameterClosure | validation | private function getParameterClosure($parameter)
{
$parameterClosure = null;
foreach (array_keys($this->parameterCluster->prefixes) as $prefix) {
if (substr($parameter, 0, strlen($prefix)) == $prefix) {
@$parameterClosure = $this->parameterCluster->prefixes[$prefix][
substr(
$parameter,
strlen($prefix),
strlen($parameter) - strlen($prefix)
)
];
}
}
return $parameterClosure;
} | php | {
"resource": ""
} |
q250782 | Client.decodeResponse | validation | private function decodeResponse(Response $response)
{
$data = json_decode($response->getBody()->read($response->getBody()->getSize()), true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new ClientException('Unable to parse response body into JSON: ' . json_last_error());
}
return $data === null ? array() : $data;
} | php | {
"resource": ""
} |
q250783 | Client.runSyncAction | validation | public function runSyncAction($syncActionBaseUrl, $component, $action, array $configData)
{
$uriParts = [];
if ($this->super) {
$uriParts[] = $this->super;
}
$uriParts[] = $component;
$uriParts[] = 'action';
$uriParts[] = $action;
$uri = rtrim($syncActionBaseUrl, '/') . '/' . implode('/', $uriParts);
$body = [
'configData' => $configData,
];
try {
$request = new Request('POST', $uri, [], json_encode($body));
$response = $this->guzzle->send($request);
} catch (RequestException $e) {
throw new ClientException($e->getMessage(), 0, $e);
}
return $this->decodeResponse($response);
} | php | {
"resource": ""
} |
q250784 | Response.getMessages | validation | public function getMessages()
{
$messages = array();
if (!empty($this->error)) {
$messages[] = $this->error;
}
if (!empty($this->warning)) {
$messages[] = $this->warning;
}
return $messages;
} | php | {
"resource": ""
} |
q250785 | FullUsageStyle.allExcept | validation | public static function allExcept($except)
{
$result = [
'parameter' => [
// 9 = Length of the word 'Parameter'
'longest' => 9 + $columnPadding,
'values' => [],
'fetch' => function ($parameter) {
return $parameter->prefix.$parameter->parameterName;
},
],
'properties' => [
// 10 = Length of the word 'Properties'
'longest' => 10 + $columnPadding,
'values' => [],
'fetch' => function ($parameter) {
return $parameter->getPropertiesAsString();
},
],
'aliases' => [
// 7 = Length of the word 'Aliases'
'longest' => 7 + $columnPadding,
'values' => [],
'fetch' => function ($parameter) {
return $parameter->getAliasUsage(false);
},
],
'description' => [
// 11 = Length of the word 'Description'
'longest' => 11 + $columnPadding,
'values' => [],
'fetch' => function ($parameter) {
return $parameter->description;
},
],
'required' => [
// 8 = Length of the word 'Required'
'longest' => 8 + $columnPadding,
'values' => [],
'fetch' => function ($parameter) {
return $parameter->required ? 'Yes' : '';
},
],
];
// Remove the exceptions
foreach ($except as $exceptKey) {
unset($result[$exceptKey]);
}
return $result;
} | php | {
"resource": ""
} |
q250786 | Fts.create | validation | public function create($table, array $fields, $tokenize = 'porter')
{
$fields = implode(', ', $fields);
$query = "CREATE VIRTUAL TABLE {$table} USING fts4({$fields}, tokenize={$tokenize})";
$executed = $this->db->info('tables', $table);
if ($query == $executed) {
return false; // the table has already been created
}
if (!is_null($executed)) {
$this->db->exec('DROP TABLE '.$table);
}
$this->db->exec($query);
$this->db->info('tables', $table, $query); // add or update
return true; // the table has been created anew
} | php | {
"resource": ""
} |
q250787 | Fts.count | validation | public function count($table, $search, $where = '')
{
if (empty($where)) {
$where = 'WHERE';
} else {
$where = (stripos($where, 'WHERE') === false) ? "WHERE {$where} AND" : "{$where} AND";
}
return $this->db->value("SELECT COUNT(*) FROM {$table} AS s {$where} s.{$table} MATCH ?", $search);
} | php | {
"resource": ""
} |
q250788 | Fts.rank | validation | public function rank($info, $weights)
{
if (!empty($weights)) {
$weights = explode(',', $weights);
}
$score = (float) 0.0; // the value to return
$isize = 4; // the amount of string we need to collect for each integer
$phrases = (int) ord(substr($info, 0, $isize));
$columns = (int) ord(substr($info, $isize, $isize));
$string = $phrases.' '.$columns.' ';
for ($p = 0; $p < $phrases; ++$p) {
$term = substr($info, (2 + $p * $columns * 3) * $isize); // the start of $info for current phrase
for ($c = 0; $c < $columns; ++$c) {
$here = (float) ord(substr($term, (3 * $c * $isize), 1)); // total occurrences in this row and column
$total = (float) ord(substr($term, (3 * $c + 1) * $isize, 1)); // total occurrences for all rows in this column
$rows = (float) ord(substr($term, (3 * $c + 2) * $isize, 1)); // total rows with at least one occurence in this column
$relevance = (!empty($total)) ? ($rows / $total) * $here : 0;
$weight = (isset($weights[$c])) ? (float) $weights[$c] : 1;
$score += $relevance * $weight;
$string .= $here.$total.$rows.' ('.round($relevance, 2).'*'.$weight.') ';
}
}
// return $string . '- ' . $score; // to debug
return $score;
} | php | {
"resource": ""
} |
q250789 | Validator.validate | validation | public function validate(UploadedFile $file)
{
foreach ($this->constraints as $constraint) {
if (!$constraint->validate($file)) {
throw new ConstraintException($constraint, $file);
}
}
return true;
} | php | {
"resource": ""
} |
q250790 | SphinxQL.setPdo | validation | public function setPdo(PDO $pdo)
{
$this->pdo = $pdo;
$this->pdo->setAttribute(
PDO::ATTR_DEFAULT_FETCH_MODE,
PDO::FETCH_ASSOC
);
return $this;
} | php | {
"resource": ""
} |
q250791 | SphinxQL.getPdo | validation | public function getPdo()
{
if (empty($this->pdo)) {
$this->pdo = new PDO(sprintf("mysql:host=%s;port=%d", $this->host, $this->port));
$this->pdo->setAttribute(
PDO::ATTR_DEFAULT_FETCH_MODE,
PDO::FETCH_ASSOC
);
}
return $this->pdo;
} | php | {
"resource": ""
} |
q250792 | SphinxQL.setOrderBy | validation | public function setOrderBy($order_by, $order = null)
{
$this->order_by = $order_by;
$this->order = $order;
return $this;
} | php | {
"resource": ""
} |
q250793 | UploadHandlerBuilder.allowMimeTypes | validation | public function allowMimeTypes($mimeTypes)
{
if (!is_array($mimeTypes)) {
$mimeTypes = [$mimeTypes];
}
$this->constraints[] = new MimeTypeConstraint($mimeTypes);
return $this;
} | php | {
"resource": ""
} |
q250794 | UploadHandlerBuilder.allowExtensions | validation | public function allowExtensions($extensions)
{
if (!is_array($extensions)) {
$extensions = [$extensions];
}
$this->constraints[] = new ExtensionConstraint($extensions);
return $this;
} | php | {
"resource": ""
} |
q250795 | UploadHandlerBuilder.naming | validation | public function naming($namer)
{
if ($namer instanceof \Closure) {
$namer = new ClosureNamer($namer);
}
$this->namer = $namer;
return $this;
} | php | {
"resource": ""
} |
q250796 | UploadHandlerBuilder.getHandler | validation | public function getHandler()
{
if ($this->namer === null) {
$this->namer = new GenericNamer();
}
if ($this->filesystem === null) {
throw new \LogicException(sprintf('You should set a filesystem for the builder.'));
}
$handler = new UploadHandler($this->filesystem, $this->namer, $this->overwrite);
$validator = $handler->getValidator();
foreach ($this->constraints as $constraint) {
$validator->addConstraint($constraint);
}
return $handler;
} | php | {
"resource": ""
} |
q250797 | ParameterCluster.add | validation | public function add(ParameterClosure $closure)
{
$this->prefixes[$closure->prefix][$closure->parameterName] = $closure;
return $this;
} | php | {
"resource": ""
} |
q250798 | ParameterCluster.addMany | validation | public function addMany($parameters)
{
foreach ($parameters as $parameter) {
$this->prefixes[$parameter->prefix][
$parameter->parameterName
] = $parameter;
}
return $this;
} | php | {
"resource": ""
} |
q250799 | ParameterCluster.getUsage | validation | public function getUsage(
$showRequiredFirst = true,
$customBinary = null,
$customScript = null
) {
$fullUsage = '';
if ($customBinary == null) {
$fullUsage = 'php ';
} else {
$fullUsage = $customBinary.' ';
}
if ($customScript == null) {
$fullUsage .= basename($_SERVER['SCRIPT_NAME']).' ';
} else {
$fullUsage .= $customScript.' ';
}
foreach ($this->prefixes as $prefix => $parameters) {
if ($showRequiredFirst) {
usort($parameters, function ($p1, $p2) {
if ($p1->required && $p2->required) {
return 0;
}
if ($p1->required && ! $p2->required) {
return -1;
}
if ($p2->required && ! $p1->required) {
return 1;
}
});
}
foreach ($parameters as $parameter) {
if ($parameter->parent == null) {
$fullUsage .= $parameter->getUsage().' ';
}
}
}
return $fullUsage;
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.