_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q11100
Chart.setTypeOption
train
public function setTypeOption( $name, $option, $seriesTitle = null) { $this->jsWriter->setTypeOption( $name, $option, $seriesTitle ); return $this; }
php
{ "resource": "" }
q11101
Chart.createSeries
train
public function createSeries( $data, $title = null, $type = null ) { return new Series( $data, $title, $this->jsWriter ); }
php
{ "resource": "" }
q11102
Chart.addSeries
train
public function addSeries( $seriesOrArray ) { if (! is_array( $seriesOrArray ) ) { $seriesOrArray = array( $seriesOrArray ); } if ( is_array( $seriesOrArray ) ) { foreach ( $seriesOrArray as $series ) { if (! $series instanceof Series ) { throw new \UnexpectedValueException( '\Altamira\Chart::addSeries expects a single series or an array of series instances' ); } $this->addSingleSeries( $series ); } } return $this; }
php
{ "resource": "" }
q11103
Chart.getDiv
train
public function getDiv($width = 500, $height = 400) { $styleOptions = array('width' => $width.'px', 'height' => $height.'px' ); return ChartRenderer::render( $this, $styleOptions ); }
php
{ "resource": "" }
q11104
Client.isDir
train
public function isDir(string $name) { $current = $this->pwd(); try { $this->chDir($name); $this->chDir($current); return true; } catch (\Exception $e) { // do nothing } return false; }
php
{ "resource": "" }
q11105
Client.ls
train
public function ls(string $path = '') : array { return version_compare(PHP_VERSION, '7.2.0', '>=') ? $this->ls72($path) : $this->lsLegacy($path); }
php
{ "resource": "" }
q11106
Client.ls72
train
private function ls72(string $path) : array { $list = []; foreach ($this->mlsd($path) as $fileInfo) { $list[] = new File($fileInfo); } return $list; }
php
{ "resource": "" }
q11107
Client.lsLegacy
train
private function lsLegacy(string $path) : array { $list = []; foreach ($this->nlist($path) as $name) { $type = $this->isDir($name) ? 'dir' : 'file'; $size = $this->size($name); $mtime = $this->mdtm($name); if ($mtime == -1) { throw new RuntimeException('FTP server doesnt support \'ftp_mdtm\''); } $list[] = new File(['name' => $name, 'modify' => $mtime, 'type' => $type, 'size' => $size]); } return $list; }
php
{ "resource": "" }
q11108
Client.lsDirs
train
public function lsDirs(string $path = '') : array { return array_filter( $this->ls($path), function(File $file) { return $file->isDir(); } ); }
php
{ "resource": "" }
q11109
Client.lsFiles
train
public function lsFiles(string $path = '') : array { return array_filter( $this->ls($path), function(File $file) { return $file->isFile(); } ); }
php
{ "resource": "" }
q11110
Client.uploadFile
train
public function uploadFile(string $file, string $path, string $name) { // to store the file we have to make sure the directory exists foreach ($this->extractDirectories($path) as $dir) { // if change to directory fails // create the dir and change into it afterwards try { $this->chDir($dir); } catch (\Exception $e) { $this->mkDir($dir); $this->chDir($dir); } } if (!$this->put($name, $file, FTP_BINARY)) { $error = error_get_last(); $message = $error['message']; throw new RuntimeException(sprintf('error uploading file: %s - %s', $file, $message)); } }
php
{ "resource": "" }
q11111
Client.setup
train
private function setup(string $url) { $parts = \parse_url($url); $this->host = $parts['host'] ?? ''; $this->port = $parts['port'] ?? 21; $this->user = $parts['user'] ?? ''; $this->password = $parts['pass'] ?? ''; }
php
{ "resource": "" }
q11112
Client.login
train
private function login() { if (empty($this->host)) { throw new RuntimeException('no host to connect to'); } $old = error_reporting(0); $link = $this->isSecure ? ftp_ssl_connect($this->host, $this->port) : ftp_connect($this->host, $this->port); if (!$link) { error_reporting($old); throw new RuntimeException(sprintf('unable to connect to ftp server %s', $this->host)); } $this->connection = $link; if (!ftp_login($this->connection, $this->user, $this->password)) { error_reporting($old); throw new RuntimeException( sprintf('authentication failed for %s@%s', $this->user, $this->host) ); } // set passive mode if needed $this->pasv($this->passive); error_reporting($old); }
php
{ "resource": "" }
q11113
Client.extractDirectories
train
private function extractDirectories(string $path) : array { $remoteDirs = []; if (!empty($path)) { $remoteDirs = explode('/', $path); // fix empty first array element for absolute path if (substr($path, 0, 1) === '/') { $remoteDirs[0] = '/'; } $remoteDirs = array_filter($remoteDirs); } return $remoteDirs; }
php
{ "resource": "" }
q11114
Batch.getResultId
train
public final function getResultId(int $i): ?int { return ($result = $this->getResult($i)) ? $result->getId() : null; }
php
{ "resource": "" }
q11115
Batch.getResultsIds
train
public final function getResultsIds(bool $merge = true): array { $return = []; if (!empty($this->results)) { if ($merge) { foreach ($this->results as $result) { $return = array_merge($return, $result->getIds()); } } else { foreach ($this->results as $result) { $return[] = $result->getIds(); } } } return $return; }
php
{ "resource": "" }
q11116
Batch.doQuery
train
public final function doQuery(string $query, array $queryParams = null): BatchInterface { return $this->queue($query, $queryParams)->do(); }
php
{ "resource": "" }
q11117
Sonar.onOpen
train
public function onOpen(ConnectionInterface $conn) { // store the new connection $this->clients->attach($conn); echo Messenger::open($this->getIpAddress($conn)); // start profiler if(defined('SONAR_VERBOSE') === true) { Profiler::start(); } }
php
{ "resource": "" }
q11118
Sonar.onMessage
train
public function onMessage(ConnectionInterface $conn, $request) { if(is_array($request = json_decode($request, true)) === false) { throw new AppServiceException('The server received an invalid data format'); } if(isset($request['page']) === false) { throw new AppServiceException('There is no current page data'); } $this->queueService->push($request, function() use ($request, $conn) { // process only what is necessary for the subsequent construction of stats return [ 'ip' => $this->getIpAddress($conn), 'hash' => md5($this->getIpAddress($conn).$this->getUserAgent($conn)), 'open' => time() ]; }); // send back if(defined('SONAR_VERBOSE') === true) { echo Messenger::message(json_encode($request)); $conn->send(json_encode($request)); } }
php
{ "resource": "" }
q11119
Sonar.onClose
train
public function onClose(ConnectionInterface $conn) { // The connection is closed, remove it, as we can no longer send it messages $this->clients->detach($conn); // pulled data from queues $data = $this->queueService->pull([ // identity for open queue message 'hash' => md5($this->getIpAddress($conn).$this->getUserAgent($conn)), ], function($response) use ($conn) { return array_merge($response, [ 'ua' => $this->getUserAgent($conn), 'language' => $this->getLanguage($conn), 'location' => $this->getLocation($conn), 'close' => time() ]); }); // save data to storage $this->storageService->add($data); echo Messenger::close($this->getIpAddress($conn)); // end profiler if(defined('SONAR_VERBOSE') === true) { Profiler::finish(); Profiler::getProfilingData(); } }
php
{ "resource": "" }
q11120
Sonar.onError
train
public function onError(ConnectionInterface $conn, \Exception $e) { try { throw new \Exception($e->getMessage()); } catch(\Exception $e) { throw new SocketServiceException(Messenger::error($e->getMessage())); } finally { $conn->close(); } }
php
{ "resource": "" }
q11121
Sonar.getLocation
train
private function getLocation(ConnectionInterface $conn) { if($conn->WebSocket instanceof \StdClass) { if(($cache = $this->cacheService) != null) { $ip = $this->getIpAddress($conn); // load geo location from cache if($cache->getStorage()->exists($ip) === true) { $location = $cache->getStorage()->get($ip); } // add to cache geo location $cache->getStorage()->save($ip, $this->geoService->location($ip)); } else { try { $location = $this->geoService->location($this->getIpAddress($conn)); } catch(GeoServiceException $e) { throw new AppServiceException($e->getMessage()); } } return $location; } throw new AppServiceException('Location not defined'); }
php
{ "resource": "" }
q11122
EloquentVoucherType.byId
train
public function byId($id, $databaseConnectionName = null) { if(empty($databaseConnectionName)) { $databaseConnectionName = $this->databaseConnectionName; } return $this->VoucherType->on($databaseConnectionName)->find($id); }
php
{ "resource": "" }
q11123
ExceptionRendererCakeTheme._outputMessageSafe
train
protected function _outputMessageSafe($template) { $this->controller->layoutPath = null; $this->controller->subDir = null; $this->controller->viewPath = 'Errors'; $this->controller->layout = 'CakeTheme.error'; $this->controller->helpers = array('Form', 'Html', 'Session'); if (!empty($template)) { $template = 'CakeTheme.' . $template; } $view = new View($this->controller); $this->controller->response->body($view->render($template, 'CakeTheme.error')); $this->controller->response->type('html'); $this->controller->response->send(); }
php
{ "resource": "" }
q11124
Image.render
train
public function render($src, $class = '', $id = '', array $attrs = array()) { $attrs['class'] = false; $attrs = array_merge(array('fullUrl' => true), $attrs); $attrs['id'] = $id; $attrs = $this->_normalizeClassAttr($attrs, $this->_jbSrt('image')); if ($class !== '') { $attrs = $this->_normalizeClassAttr($attrs, $class); } $attrs['class'] = Str::clean($attrs['class']); $isFull = $attrs['fullUrl']; unset($attrs['fullUrl']); $src = FS::clean($src, '/'); $attrs['src'] = ($isFull) ? Url::root() . '/' . $src : $src; return '<img ' . $this->buildAttrs($attrs) . ' />'; }
php
{ "resource": "" }
q11125
GridBuilder.setManialink
train
public function setManialink(ManialinkInterface $manialink) { $this->manialink = $manialink; $this->actionFirstPage = $this->actionFactory ->createManialinkAction($manialink, array($this, 'goToFirstPage'), [], true); $this->actionPreviousPage = $this->actionFactory ->createManialinkAction($manialink, array($this, 'goToPreviousPage'), [], true); $this->actionNextPage = $this->actionFactory ->createManialinkAction($manialink, array($this, 'goToNextPage'), [], true); $this->actionLastPage = $this->actionFactory ->createManialinkAction($manialink, array($this, 'goToLastPage'), [], true); $this->actionGotoPage = $this->actionFactory ->createManialinkAction($manialink, array($this, 'goToPage'), [], true); return $this; }
php
{ "resource": "" }
q11126
GridBuilder.addActionColumn
train
public function addActionColumn($key, $name, $widthCoefficient, $callback, $renderer) { $this->columns[] = new ActionColumn($key, $name, $widthCoefficient, $callback, $renderer); return $this; }
php
{ "resource": "" }
q11127
GridBuilder.goToFirstPage
train
public function goToFirstPage(ManialinkInterface $manialink, $login = null, $entries = []) { $this->updateDataCollection($entries); $this->changePage(1); }
php
{ "resource": "" }
q11128
GridBuilder.goToPreviousPage
train
public function goToPreviousPage(ManialinkInterface $manialink, $login = null, $entries = []) { $this->updateDataCollection($entries); if ($this->currentPage - 1 >= 1) { $this->changePage($this->currentPage - 1); } }
php
{ "resource": "" }
q11129
GridBuilder.goToNextPage
train
public function goToNextPage(ManialinkInterface $manialink, $login = null, $entries = []) { $this->updateDataCollection($entries); if ($this->currentPage + 1 <= $this->dataCollection->getLastPageNumber()) { $this->changePage($this->currentPage + 1); } }
php
{ "resource": "" }
q11130
GridBuilder.goToLastPage
train
public function goToLastPage(ManialinkInterface $manialink, $login = null, $entries = []) { $this->updateDataCollection($entries); $this->changePage($this->dataCollection->getLastPageNumber()); }
php
{ "resource": "" }
q11131
GridBuilder.updateDataCollection
train
public function updateDataCollection($entries) { $process = false; $data = []; $start = ($this->currentPage - 1) * $this->dataCollection->getPageSize(); foreach ($entries as $key => $value) { if (substr($key, 0, 6) == "entry_") { $array = explode("_", str_replace("entry_", "", $key)); setType($value, $array[1]); $data[$array[0]] = $value; $process = true; } } if ($process) { $lines = $this->dataCollection->getData($this->currentPage); $counter = 0; foreach ($lines as $i => $lineData) { $newData = $lineData; foreach ($this->columns as $columnData) { if ($columnData instanceof InputColumn) { $newData[$columnData->getKey()] = $data[$counter]; } } $this->dataCollection->setDataByIndex($start + $counter, $newData); $counter++; } } }
php
{ "resource": "" }
q11132
GridBuilder.changePage
train
protected function changePage($page) { $this->currentPage = $page; $this->manialinkFactory->update($this->manialink->getUserGroup()); }
php
{ "resource": "" }
q11133
GridBuilder.destroy
train
public function destroy() { $this->manialink = null; $this->manialinkFactory = null; $this->dataCollection = null; // There is cyclic dependency between actions and model, remove it so that memory can be freed immediately. $this->actionFirstPage = null; $this->actionGotoPage = null; $this->actionLastPage = null; $this->actionNextPage = null; $this->temporaryActions = []; $this->temporaryEntries = []; }
php
{ "resource": "" }
q11134
PollerCollection.addPoller
train
public function addPoller(Poller $poller) { $name = $poller->getName(); if (array_key_exists($name, $this->pollers)) { throw new InvalidArgumentException("Poller named '$name' already exists"); } $this->pollers[$name] = $poller; }
php
{ "resource": "" }
q11135
PollerCollection.getPoller
train
public function getPoller($name) { if (!array_key_exists($name, $this->pollers)) { throw new InvalidArgumentException("Poller named '$name' does not exist"); } return $this->pollers[$name]; }
php
{ "resource": "" }
q11136
TreeBuilder.reset
train
public function reset(): void { $this->opening = new Record( 'Opening', new Obj(0, $this->date, 'Date'), new Text(0, 'AUTOGIRO'), new Text(0, str_pad('', 44)), new Number(0, $this->bgcNr, 'PayeeBgcNumber'), $this->payeeBgNode, new Text(0, ' ') ); $this->mandates = []; $this->payments = []; $this->amendments = []; }
php
{ "resource": "" }
q11137
TreeBuilder.addCreateMandateRequest
train
public function addCreateMandateRequest(string $payerNr, AccountNumber $account, IdInterface $id): void { $this->mandates[] = new Record( 'CreateMandateRequest', $this->payeeBgNode, new Number(0, $payerNr, 'PayerNumber'), new Obj(0, $account, 'Account'), new Obj(0, $id, 'StateId'), new Text(0, str_pad('', 24)) ); }
php
{ "resource": "" }
q11138
TreeBuilder.addDeleteMandateRequest
train
public function addDeleteMandateRequest(string $payerNr): void { $this->mandates[] = new Record( 'DeleteMandateRequest', $this->payeeBgNode, new Number(0, $payerNr, 'PayerNumber'), new Text(0, str_pad('', 52)) ); }
php
{ "resource": "" }
q11139
TreeBuilder.addUpdateMandateRequest
train
public function addUpdateMandateRequest(string $payerNr, string $newPayerNr): void { $this->mandates[] = new Record( 'UpdateMandateRequest', $this->payeeBgNode, new Number(0, $payerNr, 'PayerNumber'), $this->payeeBgNode, new Number(0, $newPayerNr, 'PayerNumber'), new Text(0, str_pad('', 26)) ); }
php
{ "resource": "" }
q11140
TreeBuilder.addOutgoingPaymentRequest
train
public function addOutgoingPaymentRequest( string $payerNr, SEK $amount, \DateTimeInterface $date, string $ref, string $interval, int $repetitions ): void { $this->addPaymentRequest( 'OutgoingPaymentRequest', $payerNr, $amount, $date, $ref, $interval, $repetitions ); }
php
{ "resource": "" }
q11141
TreeBuilder.addImmediateIncomingPaymentRequest
train
public function addImmediateIncomingPaymentRequest(string $payerNr, SEK $amount, string $ref): void { $this->addImmediatePaymentRequest('IncomingPaymentRequest', $payerNr, $amount, $ref); }
php
{ "resource": "" }
q11142
TreeBuilder.addDeletePaymentRequest
train
public function addDeletePaymentRequest(string $payerNr): void { $this->amendments[] = new Record( 'AmendmentRequest', $this->payeeBgNode, new Number(0, $payerNr, 'PayerNumber'), new Text(0, str_repeat(' ', 52)) ); }
php
{ "resource": "" }
q11143
TreeBuilder.buildTree
train
public function buildTree(): Node { $sections = []; foreach (self::SECTION_TO_RECORD_STORE_MAP as $sectionName => $recordStore) { if (!empty($this->$recordStore)) { $sections[] = new Section($sectionName, $this->opening, ...$this->$recordStore); } } return new AutogiroFile('AutogiroRequestFile', ...$sections); }
php
{ "resource": "" }
q11144
FilterController.autocomplete
train
public function autocomplete() { Configure::write('debug', 0); if (!$this->request->is('ajax') || !$this->request->is('post') || !$this->RequestHandler->prefers('json')) { throw new BadRequestException(); } $data = []; $query = $this->request->data('query'); if (empty($query)) { $this->set(compact('data')); $this->set('_serialize', 'data'); return; } $type = $this->request->data('type'); $plugin = $this->request->data('plugin'); $limit = $this->ConfigTheme->getAutocompleteLimitConfig(); $data = $this->Filter->getAutocomplete($query, $type, $plugin, $limit); if (empty($data)) { $data = []; } $this->set(compact('data')); $this->set('_serialize', 'data'); }
php
{ "resource": "" }
q11145
KBEntry.addDocumentation
train
public function addDocumentation(string $url, ?string $anchor = null ): KBDocumentation { $this->url = $url; if ($this->docs === null) { $this->docs = array(); } $kbd = new KBDocumentation($url, $anchor); $this->docs[] = $kbd; return $kbd; }
php
{ "resource": "" }
q11146
Table.getColumn
train
public function getColumn($name) { return isset($this->columns[$name]) ? $this->columns[$name] : false; }
php
{ "resource": "" }
q11147
StorageService.add
train
public function add(array $data) { try { // add user data $lastInsertId = $this->visitorMapper->add($data); return $lastInsertId; } catch(MongoMapperException $e) { throw new StorageServiceException($e->getMessage()); } }
php
{ "resource": "" }
q11148
Util.arrayPick
train
public static function arrayPick(array &$array, $key, $value = null) { if (array_key_exists($key, $array)) { $value = $array[$key] ?? $value; unset($array[$key]); } return $value; }
php
{ "resource": "" }
q11149
Util.getIp
train
public static function getIp(): string { $ip = 'unknown'; if ('' != ($ip = ($_SERVER['HTTP_X_FORWARDED_FOR'] ?? ''))) { if (false !== strpos($ip, ',')) { $ip = trim((string) end(explode(',', $ip))); } } // all ok elseif ('' != ($ip = ($_SERVER['HTTP_CLIENT_IP'] ?? ''))) {} elseif ('' != ($ip = ($_SERVER['HTTP_X_REAL_IP'] ?? ''))) {} elseif ('' != ($ip = ($_SERVER['REMOTE_ADDR_REAL'] ?? ''))) {} elseif ('' != ($ip = ($_SERVER['REMOTE_ADDR'] ?? ''))) {} return $ip; }
php
{ "resource": "" }
q11150
Util.generateDeprecatedMessage
train
public static function generateDeprecatedMessage($class, string $oldStuff, string $newStuff): void { if (is_object($class)) { $class = get_class($class); } user_error(sprintf('%1$s::%2$s is deprecated, use %1$s::%3$s instead!', $class, $oldStuff, $newStuff), E_USER_DEPRECATED); }
php
{ "resource": "" }
q11151
PlayerQueryBuilder.save
train
public function save(Player $player) { // First clear references. Player has no references that needs saving. $player->clearAllReferences(false); // Save and free memory. $player->save(); PlayerTableMap::clearInstancePool(); }
php
{ "resource": "" }
q11152
PlayerQueryBuilder.saveAll
train
public function saveAll($players) { $connection = Propel::getWriteConnection(PlayerTableMap::DATABASE_NAME); $connection->beginTransaction(); foreach ($players as $record) { $this->save($record); } $connection->commit(); PlayerTableMap::clearInstancePool(); }
php
{ "resource": "" }
q11153
AbstractMongoMapper.getConnectUri
train
private function getConnectUri(\Phalcon\Config $config) { if($config->offsetExists('user') && $config->offsetExists('password')) { return "mongodb://".$config['user'].":".$config['password']."@".$config['host'].":".$config['port']."/".$config['dbname']; } else { return "mongodb://".$config['host'].":".$config['port']."/".$config['dbname']; } }
php
{ "resource": "" }
q11154
AbstractMongoMapper.setProfiler
train
public function setProfiler($level = self::PROFILE_ALL, $slowms = 100) { return $this->db->command([ 'profile' => (int)$level, 'slowms' => (int)$slowms ]); }
php
{ "resource": "" }
q11155
Customers.get
train
public static function get(array $arg_params) { //validate params $data = self::getParams($arg_params); $url = '/ecommerce/customers'; if(!empty($data['id'])){ $url .= '/'.$data['id']; }else{ return null; } //submit to api $customer_data = APIRequests::request( $url, APIRequests::METHOD_GET ); //return response return self::toObj($customer_data['body']); }
php
{ "resource": "" }
q11156
Customers.create
train
public static function create(array $arg_params) { //validate params $data = self::getParams($arg_params); if(!empty($data['metadata'])){ $data['metadata'] = json_encode($data['metadata']); } //submit to api $customer_data = APIRequests::request( '/ecommerce/customers', APIRequests::METHOD_POST, $data ); //return response return self::toObj($customer_data['body']); }
php
{ "resource": "" }
q11157
Customers.update
train
public static function update($arg_params) { //validate params if(is_array($arg_params)){ $data = self::getParams($arg_params); }else{ $data = self::getParams(json_decode(json_encode($arg_params), true)); } $url = '/ecommerce/customers'; if(!empty($data['id'])){ $url .= '/'.$data['id']; }else{ return null; } unset($data['id']); //submit to api $customer_data = APIRequests::request( $url, APIRequests::METHOD_PUT, $data ); //return response return self::toObj($customer_data['body']); }
php
{ "resource": "" }
q11158
BaseStorageUpdateListener.onManiaplanetGameBeginMap
train
public function onManiaplanetGameBeginMap(DedicatedEvent $event) { $serverOptions = $this->factory->getConnection()->getServerOptions(); $this->gameDataStorage->setScriptOptions($this->factory->getConnection()->getModeScriptSettings()); $this->gameDataStorage->setServerOptions($serverOptions); $this->gameDataStorage->setSystemInfo($this->factory->getConnection()->getSystemInfo()); $newGameInfos = $this->factory->getConnection()->getCurrentGameInfo(); $prevousGameInfos = $this->gameDataStorage->getGameInfos(); // TODO move this logic somewhere else. $this->dispatcher->reset($this->mapStorage->getMap($event->getParameters()[0]['UId'])); if ($prevousGameInfos->gameMode != $newGameInfos->gameMode || $prevousGameInfos->scriptName != $newGameInfos->scriptName) { $this->gameDataStorage->setGameInfos(clone $newGameInfos); // TODO dispatch custom event to let it know? } }
php
{ "resource": "" }
q11159
Xpath.initNamespace
train
protected function initNamespace(DOMDocument $document, $namespace_prefix = null) { // @todo: check for conflicting namespace prefixes $this->document_namespace = trim($document->documentElement->namespaceURI); $namespace_prefix = trim($namespace_prefix); if ($this->hasNamespace()) { $this->namespace_prefix = empty($namespace_prefix) ? $this->getDefaultNamespacePrefix() : $namespace_prefix; $this->registerNamespace( $this->namespace_prefix, $this->document_namespace ); } }
php
{ "resource": "" }
q11160
Reservation.getBetterButtonsActions
train
public function getBetterButtonsActions() { /** @var FieldList $fields */ $fields = parent::getBetterButtonsActions(); $fields->push(BetterButtonCustomAction::create('send', _t('Reservation.RESEND', 'Resend the reservation'))); return $fields; }
php
{ "resource": "" }
q11161
Reservation.onBeforeWrite
train
public function onBeforeWrite() { // Set the title to the name of the reservation holder $this->Title = $this->getName(); // Create a validation code to be used for confirmation and in the barcode if ($this->exists() && empty($this->ReservationCode)) { $this->ReservationCode = $this->createReservationCode(); } parent::onBeforeWrite(); }
php
{ "resource": "" }
q11162
Reservation.onBeforeDelete
train
public function onBeforeDelete() { // If a reservation is deleted remove the names from the guest list foreach ($this->Attendees() as $attendee) { /** @var Attendee $attendee */ if ($attendee->exists()) { $attendee->delete(); } } // Remove the folder if (($folder = Folder::get()->find('Name', $this->ReservationCode)) && $folder->exists() && $folder->isEmpty()) { $folder->delete(); } parent::onBeforeDelete(); }
php
{ "resource": "" }
q11163
Reservation.isDiscarded
train
public function isDiscarded() { $deleteAfter = strtotime(self::config()->get('delete_after'), strtotime($this->Created)); return ($this->Status === 'CART') && (time() > $deleteAfter); }
php
{ "resource": "" }
q11164
Reservation.getName
train
public function getName() { /** @var Attendee $attendee */ if (($mainContact = $this->MainContact()) && $mainContact->exists() && $name = $mainContact->getName()) { return $name; } else { return 'new reservation'; } }
php
{ "resource": "" }
q11165
Reservation.calculateTotal
train
public function calculateTotal() { $total = $this->Subtotal = $this->Attendees()->leftJoin( 'Broarm\EventTickets\Ticket', '`Broarm\EventTickets\Attendee`.`TicketID` = `Broarm\EventTickets\Ticket`.`ID`' )->sum('Price'); // Calculate any price modifications if added if ($this->PriceModifiers()->exists()) { foreach ($this->PriceModifiers() as $priceModifier) { $priceModifier->updateTotal($total); } } return $this->Total = $total; }
php
{ "resource": "" }
q11166
Reservation.changeState
train
public function changeState($state) { $availableStates = $this->dbObject('Status')->enumValues(); if (in_array($state, $availableStates)) { $this->Status = $state; return true; } else { user_error(_t('Reservation.STATE_CHANGE_ERROR', 'Selected state is not available')); return false; } }
php
{ "resource": "" }
q11167
Reservation.sendReservation
train
public function sendReservation() { // Get the mail sender or fallback to the admin email if (($from = self::config()->get('mail_sender')) && empty($from)) { $from = Config::inst()->get('Email', 'admin_email'); } // Create the email with given template and reservation data $email = new Email(); $email->setSubject(_t( 'ReservationMail.TITLE', 'Your order at {sitename}', null, array( 'sitename' => SiteConfig::current_site_config()->Title ) )); $email->setFrom($from); $email->setTo($this->MainContact()->Email); $email->setTemplate('ReservationMail'); $email->populateTemplate($this); $this->extend('updateReservationMail', $email); return $email->send(); }
php
{ "resource": "" }
q11168
Reservation.sendTickets
train
public function sendTickets() { // Get the mail sender or fallback to the admin email if (($from = self::config()->get('mail_sender')) && empty($from)) { $from = Config::inst()->get('Email', 'admin_email'); } // Send the tickets to the main contact $email = new Email(); $email->setSubject(_t( 'MainContactMail.TITLE', 'Uw tickets voor {event}', null, array( 'event' => $this->Event()->Title ) )); $email->setFrom($from); $email->setTo($this->MainContact()->Email); $email->setTemplate('MainContactMail'); $email->populateTemplate($this); $this->extend('updateMainContactMail', $email); $sent = $email->send(); // Get the attendees for this event that are checked as receiver $ticketReceivers = $this->Attendees()->filter('TicketReceiver', 1)->exclude('ID', $this->MainContactID); if ($ticketReceivers->exists()) { /** @var Attendee $ticketReceiver */ foreach ($ticketReceivers as $ticketReceiver) { $sentAttendee = $ticketReceiver->sendTicket(); if ($sent && !$sentAttendee) { $sent = $sentAttendee; } } } return $sent; }
php
{ "resource": "" }
q11169
Reservation.sendNotification
train
public function sendNotification() { if (($from = self::config()->get('mail_sender')) && empty($from)) { $from = Config::inst()->get('Email', 'admin_email'); } if (($to = self::config()->get('mail_receiver')) && empty($to)) { $to = Config::inst()->get('Email', 'admin_email'); } $email = new Email(); $email->setSubject(_t( 'NotificationMail.TITLE', 'Nieuwe reservering voor {event}', null, array('event' => $this->Event()->Title) )); $email->setFrom($from); $email->setTo($to); $email->setTemplate('NotificationMail'); $email->populateTemplate($this); $this->extend('updateNotificationMail', $email); return $email->send(); }
php
{ "resource": "" }
q11170
Reservation.send
train
public function send() { $this->createFiles(); $this->SentReservation = (boolean)$this->sendReservation(); $this->SentNotification = (boolean)$this->sendNotification(); $this->SentTickets = (boolean)$this->sendTickets(); }
php
{ "resource": "" }
q11171
Reservation.getDownloadLink
train
public function getDownloadLink() { /** @var Attendee $attendee */ if ( ($attendee = $this->Attendees()->first()) && ($file = $attendee->TicketFile()) && $file->exists() ) { return $file->Link(); } return null; }
php
{ "resource": "" }
q11172
ModuleDlstatsStatistics.deleteCounter
train
protected function deleteCounter() { if ( is_null( \Input::get('dlstatsid',true) ) ) { return ; } \Database::getInstance()->prepare("DELETE FROM tl_dlstatdets WHERE pid=?") ->execute(\Input::get('dlstatsid',true)); \Database::getInstance()->prepare("DELETE FROM tl_dlstats WHERE id=?") ->execute(\Input::get('dlstatsid',true)); return ; }
php
{ "resource": "" }
q11173
ModuleDlstatsStatistics.getStatusDetailed
train
protected function getStatusDetailed() { if ( isset($GLOBALS['TL_CONFIG']['dlstats']) && (bool) $GLOBALS['TL_CONFIG']['dlstats'] === true && isset($GLOBALS['TL_CONFIG']['dlstatdets']) && (bool) $GLOBALS['TL_CONFIG']['dlstatdets'] === true ) { return '<span class="tl_green">'.$GLOBALS['TL_LANG']['tl_dlstatstatistics_stat']['status_activated'].'</span>'; } $this->boolDetails = false; return '<span class="">'.$GLOBALS['TL_LANG']['tl_dlstatstatistics_stat']['status_deactivated'].'</span>'; }
php
{ "resource": "" }
q11174
ModuleDlstatsStatistics.getMonth
train
protected function getMonth() { $arrMonth = array(); $objMonth = \Database::getInstance()->prepare("SELECT FROM_UNIXTIME(`tstamp`,'%Y-%m') AS YM , COUNT(`id`) AS SUMDL FROM `tl_dlstatdets` WHERE 1 GROUP BY YM ORDER BY YM DESC") ->limit(12) ->execute(); $intRows = $objMonth->numRows; if ($intRows>0) { while ($objMonth->next()) { $Y = substr($objMonth->YM, 0,4); $M = (int)substr($objMonth->YM, -2); $arrMonth[] = array($Y.' '.$GLOBALS['TL_LANG']['MONTHS'][($M - 1)], $this->getFormattedNumber($objMonth->SUMDL,0) ); } } return $arrMonth; }
php
{ "resource": "" }
q11175
ModuleDlstatsStatistics.getYear
train
protected function getYear() { $arrYear = array(); $objYear = \Database::getInstance()->prepare("SELECT FROM_UNIXTIME(`tstamp`,'%Y') AS Y , COUNT(`id`) AS SUMDL FROM `tl_dlstatdets` WHERE 1 GROUP BY Y ORDER BY Y DESC") ->limit(12) ->execute(); $intRows = $objYear->numRows; if ($intRows>0) { while ($objYear->next()) { // Y, formatierte Zahl, unformatierte Zahl $arrYear[] = array($objYear->Y, $this->getFormattedNumber($objYear->SUMDL,0),$objYear->SUMDL ); } } return $arrYear; }
php
{ "resource": "" }
q11176
ModuleDlstatsStatistics.getStartDate
train
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 = \Date::parse($GLOBALS['TL_CONFIG']['dateFormat'], $objStartDate->YMD); } return $StartDate; }
php
{ "resource": "" }
q11177
ModuleDlstatsStatistics.getLastDownloads
train
protected function getLastDownloads($limit=20) { $newDate = '02.02.1971'; $oldDate = '01.01.1970'; $viewDate = false; $arrLastDownloads = array(); $objLastDownloads = \Database::getInstance()->prepare("SELECT `tstamp`, `filename`, `downloads`, `id` FROM `tl_dlstats` ORDER BY `tstamp` DESC, `filename`") ->limit($limit) ->execute(); $intRows = $objLastDownloads->numRows; if ($intRows>0) { while ($objLastDownloads->next()) { $viewDate = false; if ($oldDate != \Date::parse($GLOBALS['TL_CONFIG']['dateFormat'], $objLastDownloads->tstamp)) { $newDate = \Date::parse($GLOBALS['TL_CONFIG']['dateFormat'], $objLastDownloads->tstamp); $viewDate = $newDate; } $c4d = $this->check4details($objLastDownloads->id); $arrLastDownloads[] = array( \Date::parse($GLOBALS['TL_CONFIG']['datimFormat'], $objLastDownloads->tstamp) , $objLastDownloads->filename , $this->getFormattedNumber($objLastDownloads->downloads,0) , $viewDate , $objLastDownloads->id , $c4d , $objLastDownloads->downloads // for sorting , $objLastDownloads->tstamp // for sorting ); $oldDate = $newDate; } } return $arrLastDownloads; }
php
{ "resource": "" }
q11178
ModuleDlstatsStatistics.check4details
train
protected function check4details($id) { $objC4D = \Database::getInstance()->prepare("SELECT count(`id`) AS num FROM `tl_dlstatdets` WHERE `pid`=?") ->execute($id); return $objC4D->num; }
php
{ "resource": "" }
q11179
EventContainer.addEvent
train
public function addEvent($payload, $metadata = null) { $domainEventMessage = new GenericDomainEventMessage( $this->aggregateType, $this->aggregateId, $this->newSequenceNumber(), $payload, $metadata ); $this->addEventMessage($domainEventMessage); return $domainEventMessage; }
php
{ "resource": "" }
q11180
EventContainer.getLastSequenceNumber
train
public function getLastSequenceNumber() { if (count($this->events) === 0) { return $this->lastCommittedSequenceNumber; } if ($this->lastSequenceNumber === null) { $event = end($this->events); $this->lastSequenceNumber = $event->getSequenceNumber(); } return $this->lastSequenceNumber; }
php
{ "resource": "" }
q11181
TimeZoneData.prepareTitle
train
public function prepareTitle() { $title = $this->format; // replace the placeholders with actual data foreach (array_keys(self::$db) as $key) { $title = str_ireplace('%' . $key, $this->$key, $title); } return $title; }
php
{ "resource": "" }
q11182
FileController.cancelAction
train
public function cancelAction($path) { $this->securityService->assertCommitter(); $filePath = FilePath::parse($path); $user = $this->securityService->getGitUser(); $this->wikiService->removeLock($user, $filePath); return $this->redirect($this->generateUrl('ddr_gitki_file', ['path' => $filePath])); }
php
{ "resource": "" }
q11183
EntityList.containsMultipleTypes
train
public function containsMultipleTypes() { $mixed = false; $types = []; foreach ($this->items as $item) { $class = get_class($item->getType()); if (!in_array($class, $types, true)) { $types[] = $class; } } if (count($types) > 1) { $mixed = true; } return $mixed; }
php
{ "resource": "" }
q11184
EntityList.getEntityByIdentifier
train
public function getEntityByIdentifier($identifier) { $found_entities = $this->filter( function (EntityInterface $entity) use ($identifier) { return $entity->getIdentifier() === $identifier; } ); return $found_entities->getFirst(); }
php
{ "resource": "" }
q11185
EntityList.propagateEntityChangedEvent
train
protected function propagateEntityChangedEvent(EntityChangedEvent $event) { foreach ($this->listeners as $listener) { $listener->onEntityChanged($event); } }
php
{ "resource": "" }
q11186
EntityList.propagateCollectionChangedEvent
train
protected function propagateCollectionChangedEvent(CollectionChangedEvent $event) { if ($event->getType() === CollectionChangedEvent::ITEM_REMOVED) { $event->getItem()->removeEntityChangedListener($this); } else { $event->getItem()->addEntityChangedListener($this); } parent::propagateCollectionChangedEvent($event); }
php
{ "resource": "" }
q11187
Agent.getResourceStats
train
public final function getResourceStats(): ?array { $return = null; $resourceType = $this->resource->getType(); $resourceObject = $this->resource->getObject(); if ($resourceType == Resource::TYPE_MYSQL_LINK) { $result = $resourceObject->query('SHOW SESSION STATUS'); while ($row = $result->fetch_assoc()) { $return[strtolower($row['Variable_name'])] = $row['Value']; } $result->free(); } elseif ($resourceType == Resource::TYPE_PGSQL_LINK) { $result = pg_query($resourceObject, sprintf( "SELECT * FROM pg_stat_activity WHERE usename = '%s'", pg_escape_string($resourceObject, $this->config['username']) )); $resultArray = pg_fetch_all($result); if (isset($resultArray[0])) { $return = $resultArray[0]; } pg_free_result($result); } return $return; }
php
{ "resource": "" }
q11188
Agent.quoteField
train
public function quoteField(string $input): string { $input = $this->unquoteField($input); // nope.. quote all // if (ctype_lower($input)) { // return $input; // } if ($this->isMysql()) { return '`'. str_replace('`', '``', $input) .'`'; } elseif ($this->isPgsql()) { return '"'. str_replace('"', '""', $input) .'"'; } }
php
{ "resource": "" }
q11189
Agent.escapeLikeString
train
public function escapeLikeString(string $input, bool $quote = true, bool $escape = true): string { if ($escape) { $input = $this->escapeString($input, $quote); } return addcslashes($input, '%_'); }
php
{ "resource": "" }
q11190
Agent.escapeIdentifier
train
public function escapeIdentifier($input, bool $join = true) { if (is_array($input)) { $input = array_map([$this, 'escapeIdentifier'], array_filter($input)); return $join ? join(', ', $input) : $input; } elseif ($input instanceof Sql) { return $input->toString(); } elseif ($input instanceof Identifier) { $input = $input->toString(); } if (!is_string($input)) { throw new AgentException(sprintf('String, array and Query\Sql,Identifier type identifiers'. ' accepted only, %s given!', gettype($input))); } $input = trim($input); if ($input == '' || $input == '*') { return $input; } // functions, parentheses etc are not allowed if (strpos($input, '(') !== false) { throw new AgentException('Found parentheses in input, complex identifiers not allowed!'); } // trim all non-word characters $input = preg_replace('~^[^\w]|[^\w]$~', '', $input); if ($input == '') { return $input; } // multiple fields if (strpos($input, ',')) { return $this->escapeIdentifier(Util::split(',', $input), $join); } // aliases if (strpos($input, ' ')) { return preg_replace_callback('~([^\s]+)\s+(AS\s+)?(\w+)~i', function ($match) { return $this->escapeIdentifier($match[1]) . ( ($as = trim($match[2])) ? ' '. strtoupper($as) .' ' : ' ' ) . $this->escapeIdentifier($match[3]); }, $input); } // dots if (strpos($input, '.')) { return implode('.', array_map([$this, 'escapeIdentifier'], explode('.', $input))); } return $this->quoteField($input); }
php
{ "resource": "" }
q11191
Agent.escapeBytea
train
public function escapeBytea(string $input): string { if ($this->resource->getType() != Resource::TYPE_PGSQL_LINK) { throw new AgentException('escapeBytea() available for only Pgsql!'); } return pg_escape_bytea($this->resource->getObject(), $input); }
php
{ "resource": "" }
q11192
Agent.unescapeBytea
train
public function unescapeBytea(string $input): string { if ($this->resource->getType() != Resource::TYPE_PGSQL_LINK) { throw new AgentException('unescapeBytea() available for only Pgsql!'); } return pg_unescape_bytea($input); }
php
{ "resource": "" }
q11193
Agent.prepareIdentifier
train
public final function prepareIdentifier(string $input, $inputParam): string { if (empty($inputParam)) { if (strpos($input, '%n') !== false) { throw new AgentException('Found %n operator but no replacement parameter given!'); } elseif (strpos($input, '??') !== false) { throw new AgentException('Found ?? operator but no replacement parameter given!'); } } else { $input = $this->prepare($input, (array) $inputParam); // eg: ('@a.id=?', 1), ('@a.id=@b.id') // eg: ('??=?', ['a.id',1]), ('??=??', ['a.id','b.id']) // eg: ('a.id=?, a.b=?', [1,2]), ('a.id=??, a.b=?', ['b.id',2]) if (strpos($input, '=')) { $input = implode(', ', array_map(function ($input) { $input = trim($input); if ($input != '') { $input = array_map('trim', explode('=', $input)); $input = $this->escapeIdentifier($input[0]) .' = '. ( ($input[1] && $input[1][0] == '@' ) ? $this->escapeIdentifier($input[1]) : $input[1] ); return $input; } }, explode(',', $input))); } return $input; } // eg: (a.id = 1), (a.id = @b.id) if (strpos($input, '=')) { $input = implode(', ', array_map(function ($input) { $input = trim($input); if ($input != '') { $input = array_map('trim', explode('=', $input)); $input = $this->escapeIdentifier($input[0]) .' = '. ( ($input[1] && $input[1][0] == '@' ) ? $this->escapeIdentifier($input[1]) : $this->escape($input[1]) ); return $input; } }, explode(',', $input))); } else { // eg: a.id $input = $this->escapeIdentifier($input); } return $input; }
php
{ "resource": "" }
q11194
FlashMessage.getMessage
train
public function getMessage($key = null) { $result = []; if (empty($key)) { return $result; } $sessionKey = $this->_sessionKey . '.' . $key; if (!CakeSession::check($sessionKey)) { return $result; } $data = CakeSession::read($sessionKey); if (empty($data)) { return $result; } $result = (array)$data; if (isAssoc($result)) { $result = [$result]; } return $result; }
php
{ "resource": "" }
q11195
FlashMessage.deleteMessage
train
public function deleteMessage($key = null) { if (empty($key)) { return false; } $sessionKey = $this->_sessionKey . '.' . $key; if (!CakeSession::check($sessionKey)) { return false; } return CakeSession::delete($sessionKey); }
php
{ "resource": "" }
q11196
Application.registerProviders
train
private function registerProviders() { $providers = $this->config('app')['providers']; foreach ($providers as $provider) { $obj = new $provider($this); if (!$obj instanceof Provider) { throw new \Exception("Invalid provider: $provider"); } $this->container->invoke($obj, 'register'); } }
php
{ "resource": "" }
q11197
UriValidator.isValid
train
protected function isValid($value) { $consumer = new Consumer(); $embedObject = $consumer->consume($value); if ($embedObject === null) { $this->addError('This URI has no oEmbed support.', 1403004582, [$value]); } }
php
{ "resource": "" }
q11198
Refund.getParams
train
protected static function getParams(array $arg_params) { $return = array(); //validate params $data = array( 'amount', 'transaction_id', 'customer_id', 'security_token', 'customer_ip' ); foreach ($data as $key) { if(!empty($arg_params[$key])){ $return[$key] = $arg_params[$key]; } } return $return; }
php
{ "resource": "" }
q11199
Refund.doCardRefund
train
public static function doCardRefund($arg_params) { //validate params $data = array(); if(is_array($arg_params)){ $data = self::getParams($arg_params); }else{ $transaction = json_decode(json_encode($arg_params), true); if(!empty($transaction['id'])){ $data = array('transaction_id'=>$transaction['id']); } } //submit to api $refund_data = APIRequests::request( '/ecommerce/refund/card', APIRequests::METHOD_POST, array('payload'=>$data) ); //return response return self::toObj($refund_data['body']); }
php
{ "resource": "" }