_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q11200
Ticket.getAvailableFrom
train
public function getAvailableFrom() { if ($this->AvailableFromDate) { return $this->dbObject('AvailableFromDate'); } elseif ($startDate = $this->getEventStartDate()) { $lastWeek = new Date(); $lastWeek->setValue(strtotime(self::config()->get('sale_start_threshold'), strtotime($startDate->value))); return $lastWeek; } return null; }
php
{ "resource": "" }
q11201
Ticket.getAvailableTill
train
public function getAvailableTill() { if ($this->AvailableTillDate) { return $this->dbObject('AvailableTillDate'); } elseif ($startDate = $this->getEventStartDate()) { $till = strtotime(self::config()->get('sale_end_threshold'), strtotime($startDate->Nice())); $date = SS_Datetime::create(); $date->setValue(date('Y-m-d H:i:s', $till)); return $date; } return null; }
php
{ "resource": "" }
q11202
Ticket.validateDate
train
public function validateDate() { if ( ($from = $this->getAvailableFrom()) && ($till = $this->getAvailableTill()) && $from->InPast() && $till->InFuture() ) { return true; } return false; }
php
{ "resource": "" }
q11203
Ticket.getAvailable
train
public function getAvailable() { if (!$this->getAvailableFrom() && !$this->getAvailableTill()) { return false; } elseif ($this->validateDate() && $this->validateAvailability()) { return true; } return false; }
php
{ "resource": "" }
q11204
Ticket.getEventStartDate
train
private function getEventStartDate() { $currentDate = $this->Event()->getController()->CurrentDate(); if ($currentDate && $currentDate->exists()) { $date = $currentDate->obj('StartDate')->Format('Y-m-d'); $time = $currentDate->obj('StartTime')->Format('H:i:s'); $dateTime = SS_Datetime::create(); $dateTime->setValue("$date $time"); return $dateTime; } else { return null; } }
php
{ "resource": "" }
q11205
RecordTableMap.doDelete
train
public static function doDelete($values, ConnectionInterface $con = null) { if (null === $con) { $con = Propel::getServiceContainer()->getWriteConnection(RecordTableMap::DATABASE_NAME); } if ($values instanceof Criteria) { // rename for clarity $criteria = $values; } elseif ($values instanceof \eXpansion\Bundle\LocalRecords\Model\Record) { // it's a model object // create criteria based on pk values $criteria = $values->buildPkeyCriteria(); } else { // it's a primary key, or an array of pks $criteria = new Criteria(RecordTableMap::DATABASE_NAME); $criteria->add(RecordTableMap::COL_ID, (array) $values, Criteria::IN); } $query = RecordQuery::create()->mergeWith($criteria); if ($values instanceof Criteria) { RecordTableMap::clearInstancePool(); } elseif (!is_object($values)) { // it's a primary key, or an array of pks foreach ((array) $values as $singleval) { RecordTableMap::removeInstanceFromPool($singleval); } } return $query->delete($con); }
php
{ "resource": "" }
q11206
Factory.createForPlayer
train
public function createForPlayer($login) { if (!isset($this->groups[$login])) { $class = $this->class; /** @var Group $group */ $group = new $class(null, $this->dispatcher); $this->groups[$login] = $group; $group->addLogin($login); } return $this->groups[$login]; }
php
{ "resource": "" }
q11207
Factory.createForPlayers
train
public function createForPlayers($logins) { $class = $this->class; /** @var Group $group */ $group = new $class(null, $this->dispatcher); $this->groups[$group->getName()] = $group; foreach ($logins as $login) { $group->addLogin($login); } return $group; }
php
{ "resource": "" }
q11208
Factory.create
train
public function create($name) { $class = $this->class; /** @var Group $group */ $group = new $class($name, $this->dispatcher); $this->groups[$group->getName()] = $group; return $group; }
php
{ "resource": "" }
q11209
Factory.getGroup
train
public function getGroup($groupName) { return isset($this->groups[$groupName]) ? $this->groups[$groupName] : null; }
php
{ "resource": "" }
q11210
Factory.onExpansionGroupDestroy
train
public function onExpansionGroupDestroy(Group $group, $lastLogin) { if (isset($this->groups[$group->getName()])) { unset($this->groups[$group->getName()]); } }
php
{ "resource": "" }
q11211
HttpClientUtil.buildHttpClient
train
public static function buildHttpClient( $url = NULL, $username = NULL, $password = NULL, $contentType = self::CONTENT_JSON_API, $language = self::HEADER_LOCALE ) { $client = new Client($url); $client->setHead([ 'Accept: ' . $contentType, 'Accept-Language: ' . $language, 'Content-Type: application/vnd.api+json' ]); if (is_scalar($username) && is_scalar($password)) { $client->setOptions([CURLOPT_HTTPAUTH, CURLAUTH_ANY]); $client->setOption(CURLOPT_USERPWD, $username . ':' . $password); } return $client; }
php
{ "resource": "" }
q11212
Mapper.normalizeType
train
public static function normalizeType(string $type): string { switch ($type) { case self::DATA_TYPE_INT: case self::DATA_TYPE_BIGINT: case self::DATA_TYPE_TINYINT: case self::DATA_TYPE_SMALLINT: case self::DATA_TYPE_MEDIUMINT: case self::DATA_TYPE_INTEGER: case self::DATA_TYPE_SERIAL: case self::DATA_TYPE_BIGSERIAL: return 'int'; case self::DATA_TYPE_FLOAT: case self::DATA_TYPE_DECIMAL: case self::DATA_TYPE_DOUBLE: case self::DATA_TYPE_DOUBLEP: case self::DATA_TYPE_REAL: case self::DATA_TYPE_NUMERIC: return 'float'; case self::DATA_TYPE_BOOLEAN: return 'bool'; case self::DATA_TYPE_BIT: return 'bit'; } // all others return 'string'; }
php
{ "resource": "" }
q11213
Game.addFromCsv
train
public function addFromCsv() { $files = array_diff(scandir($this->directory . '/in', SCANDIR_SORT_NONE), ['..', '.']); foreach ($files as $file) { if (0 !== strpos($file, 'game-add')) { continue; } $fileIn = $this->directory . '/in/' . $file; $fileOut = $this->directory . '/out/' . $file; $handle = fopen($fileIn, 'rb'); $idGame = substr($file, 8, -4); if (!is_numeric($idGame)) { continue; } /** @var \VideoGamesRecords\CoreBundle\Entity\Game $game */ $game = $this->em->getReference(GameEntity::class, $idGame); if ($game === null) { continue; } $group = null; $types = null; while (($row = fgetcsv($handle, null, ';')) !== false) { list($type, $libEn, $libFr) = $row; if (isset($row[3]) && null !== $row[3] && in_array($type, ['group', 'chart'])) { $types = explode('|', $row[3]); } switch ($row[0]) { case 'object': // DO nohting break; case 'group': $group = new Group(); $group->translate('en', false)->setName($libEn); $group->translate('fr', false)->setName($libFr); $group->setGame($game); $group->mergeNewTranslations(); $this->em->persist($group); break; case 'chart': $chart = new Chart(); $chart->translate('en', false)->setName($libEn); $chart->translate('fr', false)->setName($libFr); $chart->setGroup($group); $chart->mergeNewTranslations(); if ($types !== null) { foreach ($types as $idType) { $chartLib = new ChartLib(); $chartLib ->setChart($chart) ->setType($this->em->getReference(ChartType::class, $idType)); $chart->addLib($chartLib); } } $this->em->persist($chart); break; } } $this->em->flush(); rename($fileIn, $fileOut); } }
php
{ "resource": "" }
q11214
Game.updateFromCsv
train
public function updateFromCsv() { $files = array_diff(scandir($this->directory . '/in', SCANDIR_SORT_NONE), ['..', '.']); foreach ($files as $file) { if (0 !== strpos($file, 'game-update')) { continue; } $fileIn = $this->directory . '/in/' . $file; $fileOut = $this->directory . '/out/' . $file; $handle = fopen($fileIn, 'rb'); $idGame = substr($file, 11, -4); if (!is_numeric($idGame)) { continue; } $group = null; $types = null; while (($row = fgetcsv($handle, null, ';')) !== false) { list($type, $id, $libEn, $libFr) = $row; switch ($type) { case 'object': // DO nothing break; case 'group': $group = $this->em->getRepository('VideoGamesRecordsCoreBundle:Group')->find($id); $group->translate('en', false)->setName($libEn); $group->translate('fr', false)->setName($libFr); $group->mergeNewTranslations(); $this->em->persist($group); break; case 'chart': $chart = $this->em->getRepository('VideoGamesRecordsCoreBundle:Chart')->find($id); $chart->translate('en', false)->setName($libEn); $chart->translate('fr', false)->setName($libFr); $chart->mergeNewTranslations(); $this->em->persist($chart); break; } } $this->em->flush(); rename($fileIn, $fileOut); } }
php
{ "resource": "" }
q11215
Due.setEnvName
train
public static function setEnvName($arg_env_name) { if($arg_env_name == 'stage'){ self::$envName = 'stage'; self::$domain = self::$domainStage; }elseif($arg_env_name == 'prod'){ self::$envName = 'prod'; self::$domain = self::$domainProd; }else{ throw new \Exception('Invalid Environment Given',4046969); } }
php
{ "resource": "" }
q11216
Debugger.debug
train
public static function debug(array $strings, array $placeholders = []) { // Initialize messages storage. if (!isset($_SESSION[__TRAIT__])) { $_SESSION[__TRAIT__] = []; } // Mark debug message. array_unshift($strings, '<question>DEBUG:</question>'); $_SESSION[__TRAIT__][] = new Message('comment', 4, $strings, $placeholders, (bool) getenv('BEHAT_DEBUG')); }
php
{ "resource": "" }
q11217
Debugger.printMessages
train
public static function printMessages($clearQueue = true) { if (!empty($_SESSION[__TRAIT__])) { /** @var Message $message */ foreach ($_SESSION[__TRAIT__] as $message) { $message->output(); } } if ($clearQueue) { static::clearQueue(); } }
php
{ "resource": "" }
q11218
Mime.getTypeForExtension
train
public static function getTypeForExtension($extension) { static::ensureDataLoaded(); $extension = strtolower($extension); foreach (static::$mime_types as $mime_type => $extensions) { if (is_array($extensions)) { if (in_array($extension, $extensions, true)) { return $mime_type; } } else if ($extension === $extensions) { return $mime_type; } } }
php
{ "resource": "" }
q11219
Mime.getExtensionForType
train
public static function getExtensionForType($mime_type) { static::ensureDataLoaded(); if (!static::hasType($mime_type)) { return; } $extensions = static::$mime_types[$mime_type]; if (is_array($extensions)) { return $extensions[0]; } return $extensions; }
php
{ "resource": "" }
q11220
Mime.hasExtension
train
public static function hasExtension($extension) { static::ensureDataLoaded(); $extension = strtolower($extension); foreach (static::$mime_types as $extensions) { if (is_array($extensions)) { if (in_array($extension, $extensions, true)) { return true; } } else if ($extension === $extensions) { return true; } } return false; }
php
{ "resource": "" }
q11221
Mime.guessType
train
public static function guessType($file_path, $reference_name = null, $default = 'application/octet-stream') { if (!$reference_name) { $reference_name = basename($file_path); } $extension = pathinfo($reference_name, PATHINFO_EXTENSION); if ($extension and $mime_type = static::getTypeForExtension($extension)) { return $mime_type; } // While it's true that the extension doesn't determine the type, // only use finfo as a fallback because it's bad at detecting text // types like CSS and JavaScript. if ($mime_type = static::getMagicType($file_path)) { return $mime_type; } return $default; }
php
{ "resource": "" }
q11222
Mime.guessExtension
train
public static function guessExtension($file_path, $reference_name = null, $default = 'bin') { if (!$reference_name) { $reference_name = basename($file_path); } if ($extension = pathinfo($reference_name, PATHINFO_EXTENSION) and static::hasExtension($extension)) { return strtolower($extension); } $mime_type = static::getMagicType($file_path); if ($mime_type and $extension = static::getExtensionForType($mime_type)) { return $extension; } return $default; }
php
{ "resource": "" }
q11223
Mime.getMagicType
train
public static function getMagicType($file_path) { $file_info = finfo_open(FILEINFO_MIME_TYPE); $mime_type = finfo_file($file_info, $file_path); finfo_close($file_info); // Only return valid types, in order to maintain circular compatibility between methods. if (static::hasType($mime_type)) { return $mime_type; } }
php
{ "resource": "" }
q11224
ScriptAdapter.parseParameters
train
protected function parseParameters($parameters) { if (isset($parameters[0])) { $params = json_decode($parameters[0], true); if ($params) { return $params; } } // If json couldn't be encoded return string as it was return $parameters; }
php
{ "resource": "" }
q11225
UuidValueHolder.isDefault
train
public function isDefault() { if ($this->getAttribute()->hasOption(UuidAttribute::OPTION_DEFAULT_VALUE) && $this->getAttribute()->getOption(UuidAttribute::OPTION_DEFAULT_VALUE) !== 'auto_gen' ) { return $this->sameValueAs($this->getAttribute()->getDefaultValue()); } throw new RuntimeException( 'Operation not supported. A new UUIDv4 is generated for every getNullValue call. No default value set.' ); }
php
{ "resource": "" }
q11226
TempDirectory.rmdir
train
private function rmdir($dir, $recursive) { $is_link = is_link($dir); if($is_link) { if(! unlink($dir)) throw new Exception("Error unlinking $dir"); } else if(! $recursive) { if(! rmdir($dir)) throw new Exception("Error removing temp dir: $dir"); } else { $dh = opendir($dir); if(! $dh) throw new Exception("Cannot read temp dir contents for removal: $dir"); do { $file = readdir($dh); if($file === false) break; // Don't delete current dir or parent dir (yet) if($file === '.' || $file === '..') continue; $path = $dir .DIRECTORY_SEPARATOR. $file; $is_link = is_link($path); $is_dir = is_dir($path); if($is_dir && ! $is_link) { $this->rmdir($path, true); } else // anything else, should be able to unlink { if(! unlink($path)) throw new Exception("Cannot remove nested temp file: $path"); } } while($file !== false); closedir($dh); // Now remove the dir itself (non-recursive, it should now be empty) $this->rmdir($dir, false); } }
php
{ "resource": "" }
q11227
HandleException.Setup
train
public function Setup($xmlModuleName, $customArgs) { parent::Setup($xmlModuleName, $customArgs); $this->_ErrorMessage = $customArgs; }
php
{ "resource": "" }
q11228
ManiaExchange.addMapToQueue
train
public function addMapToQueue($login, $id, $mxsite) { if (!$this->adminGroups->hasPermission($login, "maps.add")) { $this->chatNotification->sendMessage('expansion_mx.chat.nopermission', $login); return; } if ($this->downloadProgressing || count($this->addQueue) > 1) { $this->addQueue[] = ['mxid' => $id, 'mxsite' => $mxsite]; $this->chatNotification->sendMessage("|info| Adding map to download queue...", $login); return; } else { $this->addMap($login, $id, $mxsite); } }
php
{ "resource": "" }
q11229
ConfigUiManager.getUiHandler
train
public function getUiHandler(ConfigInterface $config) { if ($config->isHidden()) { return null; } foreach ($this->uiHandlers as $ui) { if ($ui->isCompatible($config)) { return $ui; } } return null; }
php
{ "resource": "" }
q11230
WkPdfBuilder.render
train
public function render() { $process = $this->getProcess(); $process->run(); if (0 === $process->getExitCode()) { return file_get_contents($this->getOutput()); } throw new \RuntimeException( sprintf('Unable to render PDF. Command "%s" exited with "%s" (code: %s): %s', $process->getCommandLine(), $process->getExitCodeText(), $process->getExitCode(), $process->getErrorOutput() ) ); }
php
{ "resource": "" }
q11231
WkPdfBuilder.getProcess
train
public function getProcess() { $this->processBuilder->setArguments(array()); foreach ($this->options as $option => $value) { if (!$value) { continue; } if (!in_array($option, static::$nonPrefixedOptions)) { $option = sprintf('--%s', $option); } $this->processBuilder->add($option); if (true !== $value) { $this->processBuilder->add($value); } } $this->processBuilder->add('-')->add($this->getOutput()); $process = $this->processBuilder->getProcess(); $process->setCommandLine(sprintf('echo "%s" | %s', addslashes($this->getInput()), $process->getCommandLine())); return $process; }
php
{ "resource": "" }
q11232
XmlnukeDocument.addJavaScriptMethod
train
public function addJavaScriptMethod($jsObject, $jsMethod, $jsSource, $jsParameters = "") { $jsEventSource = "$(function() { \n" . " $('$jsObject').$jsMethod(function($jsParameters) { \n" . " $jsSource \n" . " }); \n" . "});\n\n"; $this->addJavaScriptSource($jsEventSource, false); }
php
{ "resource": "" }
q11233
XmlnukeDocument.addJavaScriptAttribute
train
public function addJavaScriptAttribute($jsObject, $jsAttrName, $attrParam) { if (!is_array($attrParam)) { $attrParam = array($attrParam); } $jsEventSource = "$(function() { \n" . " $('$jsObject').$jsAttrName({ \n"; $first = true; foreach ($attrParam as $key=>$value) { $jsEventSource .= (!$first ? ",\n" : "") . " " . (!is_numeric($key) ? "$key: " : "" ) . $value; $first = false; } $jsEventSource .= "\n }); \n" . "});\n\n"; $this->addJavaScriptSource($jsEventSource, false); }
php
{ "resource": "" }
q11234
XmlnukeDocument.CompactJs
train
protected function CompactJs( $sText ) { $sBuffer = ""; $i = 0; $iStop = strlen($sText); // Compact and Copy PHP Source Code. $sChar = ''; $sLast = ''; $sWanted = ''; $fEscape = false; for( $i = $i; $i < $iStop; $i++ ) { $sLast = $sChar; $sChar = substr( $sText, $i, 1 ); // \ in a string marks possible an escape sequence if ( $sChar == '\\' ) // are we in a string? if ( $sWanted == '"' || $sWanted == "'" ) // if we are not in an escape sequence, turn it on // if we are in an escape sequence, turn it off $fEscape = !$fEscape; // " marks start or end of a string if ( $sChar == '"' && !$fEscape ) if ( $sWanted == '' ) $sWanted = '"'; else if ( $sWanted == '"' ) $sWanted = ''; // ' marks start or end of a string if ( $sChar == "'" && !$fEscape ) if ( $sWanted == '' ) $sWanted = "'"; else if ( $sWanted == "'" ) $sWanted = ''; // // marks start of a comment if ( $sChar == '/' && $sWanted == '' ) if ( substr( $sText, $i + 1, 1 ) == '/' ) { $sWanted = "\n"; $i++; continue; } // \n marks possible end of comment if ( $sChar == "\n" && $sWanted == "\n" ) { $sWanted = ''; continue; } // /* marks start of a comment if ( $sChar == '/' && $sWanted == '' ) if ( substr( $sText, $i + 1, 1 ) == '*' ) { $sWanted = "*/"; $i++; continue; } // */ marks possible end of comment if ( $sChar == '*' && $sWanted == '*/' ) if ( substr( $sText, $i + 1, 1 ) == '/' ) { $sWanted = ''; $i++; continue; } // if we have a tab or a crlf replace it with a blank and continue if we had one recently if ( ( $sChar == "\t" || $sChar == "\n" || $sChar == "\r" ) && $sWanted == '' ) { $sChar = ' '; if ( $sLast == ' ' ) continue; } // skip blanks only if previous char was a blank or nothing if ( $sChar == ' ' && ( $sLast == ' ' || $sLast == '' ) && $sWanted == '' ) continue; // add char to buffer if we are not inside a comment if ( $sWanted == '' || $sWanted == '"' || $sWanted == "'" ) $sBuffer .= $sChar; // if we had an escape sequence and the actual char isn't the escape char, cancel escape sequence... // since we are only interested in escape sequences of \' and \". if ( $fEscape && $sChar != '\\' ) $fEscape = false; } // Copy Rest $sBuffer .= substr( $sText, $iStop ); return( $sBuffer ); }
php
{ "resource": "" }
q11235
OperationListCommand.getPropertySettings
train
private function getPropertySettings($property) { $data = []; $settings = [ 'minimum' => 'min', 'maximum' => 'max', ]; foreach ($settings as $setting => $name) { if (isset($property[$setting])) { $data[] = $name.':'.$property[$setting]; } } return implode(' | ', $data); }
php
{ "resource": "" }
q11236
PlayerTableMap.doDelete
train
public static function doDelete($values, ConnectionInterface $con = null) { if (null === $con) { $con = Propel::getServiceContainer()->getWriteConnection(PlayerTableMap::DATABASE_NAME); } if ($values instanceof Criteria) { // rename for clarity $criteria = $values; } elseif ($values instanceof \eXpansion\Framework\PlayersBundle\Model\Player) { // it's a model object // create criteria based on pk values $criteria = $values->buildPkeyCriteria(); } else { // it's a primary key, or an array of pks $criteria = new Criteria(PlayerTableMap::DATABASE_NAME); $criteria->add(PlayerTableMap::COL_ID, (array) $values, Criteria::IN); } $query = PlayerQuery::create()->mergeWith($criteria); if ($values instanceof Criteria) { PlayerTableMap::clearInstancePool(); } elseif (!is_object($values)) { // it's a primary key, or an array of pks foreach ((array) $values as $singleval) { PlayerTableMap::removeInstanceFromPool($singleval); } } return $query->delete($con); }
php
{ "resource": "" }
q11237
MigrateAttendeeFieldsTask.publishEvents
train
private function publishEvents() { /** @var CalendarEvent|TicketExtension $event */ foreach (CalendarEvent::get() as $event) { if ($event->Tickets()->exists()) { if ($event->doPublish()) { echo "[$event->ID] Published event \n"; $this->moveFieldData($event); } else { echo "[$event->ID] Failed to publish event \n\n"; } } } }
php
{ "resource": "" }
q11238
MigrateAttendeeFieldsTask.moveFieldData
train
private function moveFieldData(CalendarEvent $event) { if ($event->Attendees()->exists()) { /** @var Attendee $attendee */ foreach ($event->Attendees() as $attendee) { /** @var UserField $field */ foreach ($event->Fields() as $field) { $q = SQLSelect::create( $field->FieldName, "`{$attendee->getClassName()}`", array('ID' => $attendee->ID) ); try { $value = $q->execute()->value(); $attendee->Fields()->add($field, array( 'Value' => $value )); echo "[$event->ID][$attendee->ID] Set '$field->FieldName' with '{$value}' \n"; } catch (\Exception $e) { // fails silent echo "[$event->ID][$attendee->ID] Failed, '$field->FieldName' does not exist \n"; } } } echo "[$event->ID] Finished migrating event \n\n"; } else { echo "[$event->ID] No attendees to migrate \n\n"; } }
php
{ "resource": "" }
q11239
VisitorContainer.visitBefore
train
public function visitBefore(Node $node): void { parent::visitBefore($node); foreach ($this->visitors as $visitor) { $visitor->visitBefore($node); } }
php
{ "resource": "" }
q11240
VisitorContainer.visitAfter
train
public function visitAfter(Node $node): void { foreach ($this->visitors as $visitor) { $visitor->visitAfter($node); } parent::visitAfter($node); }
php
{ "resource": "" }
q11241
BenGorUserBundle.buildLoadableBundles
train
protected function buildLoadableBundles(ContainerBuilder $container) { $bundles = $container->getParameter('kernel.bundles'); foreach ($bundles as $bundle) { $reflectionClass = new \ReflectionClass($bundle); if ($reflectionClass->implementsInterface(LoadableBundle::class)) { (new $bundle())->load($container); } } }
php
{ "resource": "" }
q11242
EloquentFiscalYear.byYearAndByOrganization
train
public function byYearAndByOrganization($year, $organiztionId) { return $this->FiscalYear->where('year', '=', $year)->where('organization_id', '=', $organiztionId)->get()->first(); }
php
{ "resource": "" }
q11243
EloquentFiscalYear.update
train
public function update(array $data, $FiscalYear = null) { if(empty($FiscalYear)) { $FiscalYear = $this->byId($data['id']); } foreach ($data as $key => $value) { $FiscalYear->$key = $value; } return $FiscalYear->save(); }
php
{ "resource": "" }
q11244
FileDiffer.isDiff
train
public function isDiff($first, $second) { if(! file_exists($first)) throw new NoSuchFileException($first); $second = $this->oFileNameResolver->resolve($first, $second); // If the second file doesn't exist, they're definitely different if(! file_exists($second)) return true; // If the file sizes are different, definitely the file contents are different if(filesize($first) !== filesize($second)) return true; // File sizes are the same, open the files and look for differences if(! ($fh1 = fopen($first, 'rb'))) throw new FileOpenException($first); if(! ($fh2 = fopen($second, 'rb'))) throw new FileOpenException($second); while(! feof($fh1) && ! feof($fh2)) { $data1 = fread($fh1, static::READ_SIZE); if(false === $data1) throw new FileReadException($first); $data2 = fread($fh2, static::READ_SIZE); if(false === $data2) throw new FileReadException($second); if($data1 !== $data2) return true; } return false; }
php
{ "resource": "" }
q11245
MoveComponent.moveItem
train
public function moveItem($direct = null, $id = null, $delta = 1) { $isJson = $this->_controller->RequestHandler->prefers('json'); if ($isJson) { Configure::write('debug', 0); } $result = $this->_model->moveItem($direct, $id, $delta); if (!$isJson) { if (!$result) { $this->_controller->Flash->error(__d('view_extension', 'Error move record %d %s', $id, __d('view_extension_direct', $direct))); } return $this->_controller->redirect($this->_controller->request->referer(true)); } else { $data = compact('result', 'direct', 'delta'); $this->_controller->set(compact('data')); $this->_controller->set('_serialize', 'data'); } }
php
{ "resource": "" }
q11246
MoveComponent.dropItem
train
public function dropItem() { Configure::write('debug', 0); if (!$this->_controller->request->is('ajax') || !$this->_controller->request->is('post') || !$this->_controller->RequestHandler->prefers('json')) { throw new BadRequestException(); } $id = $this->_controller->request->data('target'); $newParentId = $this->_controller->request->data('parent'); $oldParentId = $this->_controller->request->data('parentStart'); $dropData = $this->_controller->request->data('tree'); $dropData = json_decode($dropData, true); $result = $this->_model->moveDrop($id, $newParentId, $oldParentId, $dropData); $data = compact('result'); $this->_controller->set(compact('data')); $this->_controller->set('_serialize', 'data'); }
php
{ "resource": "" }
q11247
RokkaApiHelper.organizationExists
train
public function organizationExists(User $client, $organizationName) { try { $org = $client->getOrganization($organizationName); return $org->getName() == $organizationName; } catch (ClientException $e) { if (404 === $e->getCode()) { return false; } throw $e; } }
php
{ "resource": "" }
q11248
RokkaApiHelper.stackExists
train
public function stackExists(Image $client, $stackName, $organizationName = '') { try { $stack = $client->getStack($stackName, $organizationName); return $stack->getName() == $stackName; } catch (ClientException $e) { if (404 === $e->getCode()) { return false; } throw $e; } }
php
{ "resource": "" }
q11249
RokkaApiHelper.imageExists
train
public function imageExists(Image $client, $hash, $organizationName = '') { try { $sourceImage = $client->getSourceImage($hash, $organizationName); return $sourceImage instanceof SourceImage && $sourceImage->hash === $hash; } catch (ClientException $e) { if (404 === $e->getCode()) { return false; } throw $e; } }
php
{ "resource": "" }
q11250
RokkaApiHelper.getSourceImageContents
train
public function getSourceImageContents(Image $client, $hash, $organizationName, $stackName = null, $format = 'jpg') { if (!$stackName) { return $client->getSourceImageContents($hash, $organizationName); } $uri = $client->getSourceImageUri($hash, $stackName, $format, null, $organizationName); $resp = (new Client())->get($uri); return $resp->getBody()->getContents(); }
php
{ "resource": "" }
q11251
ChangeUserPasswordCommandBuilder.handlerArguments
train
protected function handlerArguments($user) { return [ $this->container->getDefinition( 'bengor.user.infrastructure.persistence.' . $user . '_repository' ), $this->container->getDefinition( 'bengor.user.infrastructure.security.symfony.' . $user . '_password_encoder' ), ]; }
php
{ "resource": "" }
q11252
ChangeUserPasswordCommandBuilder.byRequestRememberPasswordSpecification
train
private function byRequestRememberPasswordSpecification($user) { (new RequestRememberPasswordCommandBuilder($this->container, $this->persistence))->build($user); return [ 'command' => ByRequestRememberPasswordChangeUserPasswordCommand::class, 'handler' => ByRequestRememberPasswordChangeUserPasswordHandler::class, ]; }
php
{ "resource": "" }
q11253
HandlerTypeAdapter.syncData
train
public function syncData($controller_data) { if (is_object($controller_data)) { $handler_data = $this->legacy_handler->getData(); $refl_class = new \ReflectionClass(get_class($handler_data)); $filter = \ReflectionProperty::IS_PUBLIC | \ReflectionProperty::IS_PROTECTED | \ReflectionProperty::IS_PRIVATE; foreach ($refl_class->getProperties($filter) as $property) { $property->setAccessible(true); $property->setValue($handler_data, $property->getValue($controller_data)); $property->setAccessible(false); } } return $this->legacy_handler->getData(); }
php
{ "resource": "" }
q11254
AbstractConnection.getProcessCallback
train
protected function getProcessCallback() { return function ($state, $response) { list($command, $callback) = $this->commands->dequeue(); switch ($command->getId()) { case 'SUBSCRIBE': case 'PSUBSCRIBE': $wrapper = $this->getStreamingWrapperCreator(); $callback = $wrapper($this, $callback); $state->setStreamingContext(State::PUBSUB, $callback); break; case 'MONITOR': $wrapper = $this->getStreamingWrapperCreator(); $callback = $wrapper($this, $callback); $state->setStreamingContext(State::MONITOR, $callback); break; case 'MULTI': $state->setState(State::MULTIEXEC); goto process; case 'EXEC': case 'DISCARD': $state->setState(State::CONNECTED); goto process; default: process: \call_user_func($callback, $response, $this, $command); break; } }; }
php
{ "resource": "" }
q11255
AbstractConnection.getStreamingWrapperCreator
train
protected function getStreamingWrapperCreator() { return function ($connection, $callback) { return function ($state, $response) use ($connection, $callback) { \call_user_func($callback, $response, $connection, null); }; }; }
php
{ "resource": "" }
q11256
AbstractConnection.createResource
train
protected function createResource(callable $callback) { $parameters = $this->parameters; $flags = STREAM_CLIENT_CONNECT | STREAM_CLIENT_ASYNC_CONNECT; if ($parameters->scheme === 'unix') { $uri = "unix://$parameters->path"; } else { $uri = "$parameters->scheme://$parameters->host:$parameters->port"; } if (!$stream = @stream_socket_client($uri, $errno, $errstr, 0, $flags)) { $this->onError(new ConnectionException($this, \trim($errstr), $errno)); return; } \stream_set_blocking($stream, 0); $this->state->setState(State::CONNECTING); $this->loop->addWriteStream($stream, function ($stream) use ($callback) { if ($this->onConnect()) { \call_user_func($callback, $this); $this->write(); } }); $this->timeout = $this->armTimeoutMonitor( $parameters->timeout ?: 5, $this->errorCallback ?: function () { } ); return $stream; }
php
{ "resource": "" }
q11257
ChatNotification.sendMessage
train
public function sendMessage($messageId, $to = null, $parameters = []) { $message = $messageId; if (is_string($to)) { $player = $this->playerStorage->getPlayerInfo($to); $message = $this->translations->getTranslation($messageId, $parameters, strtolower($player->getLanguage())); } if (is_array($to)) { $to = implode(",", $to); $message = $this->translations->getTranslations($messageId, $parameters); } if ($to instanceof Group) { $to = implode(",", $to->getLogins()); $message = $this->translations->getTranslations($messageId, $parameters); } if ($to === null || $to instanceof Group) { $message = $this->translations->getTranslations($messageId, $parameters); $this->console->writeln(end($message)['Text']); } try { $this->factory->getConnection()->chatSendServerMessage($message, $to); } catch (UnknownPlayerException $e) { $this->logger->info("can't send chat message: $message", ["to" => $to, "exception" => $e]); // Nothing to do, it happens. } catch (InvalidArgumentException $ex) { // Nothing to do } }
php
{ "resource": "" }
q11258
MimeTypeFileInfoGuesser.guess
train
public static function guess(string $filename): ?string { if (! \is_file($filename)) { throw new FileNotFoundException($filename); } if (! \is_readable($filename)) { throw new AccessDeniedException($filename); } if (self::$magicFile !== null) { $finfo = \finfo_open(\FILEINFO_MIME_TYPE, self::$magicFile); } else { $finfo = \finfo_open(\FILEINFO_MIME_TYPE); } $type = \finfo_file($finfo, $filename); \finfo_close($finfo); return $type ?? null; }
php
{ "resource": "" }
q11259
CookieHandler.remove
train
public function remove($name) { $name = $this->getFullName($name); // Delete existing response cookie if (isset($this->responseCookies[$name])) { unset($this->responseCookies[$name]); } // Set response cookie if request cookie was set if (null !== $this->get($name)) { // Note: timestamp '1' = '1970-01-01 00:00:00 UTC' $this->set($name, 'deleted', '1'); } return $this; }
php
{ "resource": "" }
q11260
ArrayFilter.checkValue
train
protected function checkValue($value, $condition) { list($filterType, $valueToCheck) = $condition; switch ($filterType) { case self::FILTER_TYPE_EQ: return $valueToCheck == $value; case self::FILTER_TYPE_NEQ: return $valueToCheck != $value; case self::FILTER_TYPE_LIKE: return strpos($value, $valueToCheck) !== false; default : throw new InvalidFilterTypeException("Filter type '$filterType' is unknown'"); } }
php
{ "resource": "" }
q11261
Countries.getCodeFromCountry
train
public function getCodeFromCountry($country) { $output = 'OTH'; if (array_key_exists($country, $this->countriesMapping)) { $output = $this->countriesMapping[$country]; } return $output; }
php
{ "resource": "" }
q11262
Countries.getCountryFromCode
train
public function getCountryFromCode($code) { $code = strtoupper($code); $output = "Other"; if (in_array($code, $this->countriesMapping)) { foreach ($this->countriesMapping as $country => $short) { if ($code == $short) { $output = $country; break; } } } return $output; }
php
{ "resource": "" }
q11263
Countries.getIsoAlpha2FromName
train
public function getIsoAlpha2FromName($name) { // First try and fetch from alpha3 code. try { return $this->iso->alpha3($this->getCodeFromCountry($name))['alpha2']; } catch (OutOfBoundsException $e) { // Nothing code continues. } // Couldn't getch alpha3 from code try from country name. try { return $this->iso->name($name)['alpha2']; } catch (OutOfBoundsException $e) { $this->logger->warning("Can't get valid alpha2 code for country '$name'"); } return "OT"; }
php
{ "resource": "" }
q11264
AbstractDataProvider.dispatch
train
protected function dispatch($method, $params) { foreach ($this->plugins as $plugin) { $plugin->$method(...$params); } }
php
{ "resource": "" }
q11265
EloquentCostCenter.byOrganizationAndByKey
train
public function byOrganizationAndByKey($organizationId, $key) { return $this->CostCenter->where('organization_id', '=', $organizationId)->where('key', '=', $key)->get(); }
php
{ "resource": "" }
q11266
ReferenceRule.execute
train
protected function execute($value, EntityInterface $entity = null) { $success = true; $collection = null; if ($value instanceof EntityList) { $collection = $value; } elseif (null === $value) { $collection = new EntityList(); } elseif (is_array($value)) { $collection = $this->createEntityList($value); } else { $this->throwError('invalid_type'); $success = false; } if ($success) { $this->setSanitizedValue($collection); } return $success; }
php
{ "resource": "" }
q11267
Localization.addMap
train
public function addMap($locale, $map) { // Get sanitized locale $locale = Locale::sanitizeLocale($locale); $this->maps[$locale] = $map; return $this; }
php
{ "resource": "" }
q11268
Localization.addMaps
train
public function addMaps(array $maps) { foreach ($maps as $locale => $map) { $this->addMap($locale, $map); } return $this; }
php
{ "resource": "" }
q11269
Localization.findAvailableLocales
train
public function findAvailableLocales() { // Check for needed data $path = $this->getPath(); $domain = $this->getDomain(); if (!$path || !$domain) { throw new Exception("Values for 'path' and 'domain' must be set."); } // Build regular expressions for finding domains and locales $regexLocale = Locale::REGEX_LOCALE; $regexDefault = "/^{$regexLocale}\/LC_MESSAGES\/{$domain}\.mo$/ui"; $regexVirtual = "/^(?<virtualLocale>C)\/LC_MESSAGES\/(?<virtualDomain>{$domain}[^a-z]{$regexLocale})\.mo$/ui"; $glob = "{$path}/*/LC_MESSAGES/{$domain}*.mo"; foreach (glob($glob) as $parse) { // Strip path prefix to fit regex $parse = str_replace($path . '/', '', $parse); // Check for default or virtual localized files if (preg_match($regexDefault, $parse, $found) || preg_match($regexVirtual, $parse, $found)) { $this->addLocale($found['locale']); if (!empty($found['virtualLocale'])) { $map = [ 'domain' => $found['virtualDomain'], 'locale' => $found['virtualLocale'], ]; $this->addMap($found['locale'], $map); } } } return $this; }
php
{ "resource": "" }
q11270
Localization.getDomain
train
public function getDomain($realDomain = false) { if ($realDomain) { return $this->getMap($this->getActive(), 'domain') ?: $this->domain; } return $this->domain; }
php
{ "resource": "" }
q11271
Localization.getMap
train
public function getMap($locale, $key = null) { // Get sanitized locale $locale = Locale::sanitizeLocale($locale); if ($key) { return isset($this->maps[$locale][$key]) ? $this->maps[$locale][$key] : null; } return isset($this->maps[$locale]) ? $this->maps[$locale] : null; }
php
{ "resource": "" }
q11272
PlayerChartRepository.getRankingForUpdate
train
public function getRankingForUpdate(Chart $chart) { $queryBuilder = $this->createQueryBuilder('pc'); $queryBuilder ->innerJoin('pc.player', 'p') ->addSelect('p') ->innerJoin('pc.status', 'status') ->addSelect('status') ->where('pc.chart = :chart') ->setParameter('chart', $chart) ->andWhere('status.boolRanking = 1'); foreach ($chart->getLibs() as $lib) { $key = 'value_' . $lib->getIdLibChart(); $alias = 'pcl_' . $lib->getIdLibChart(); $subQueryBuilder = $this->getEntityManager()->createQueryBuilder() ->select(sprintf('%s.value', $alias)) ->from('VideoGamesRecordsCoreBundle:PlayerChartLib', $alias) ->where(sprintf('%s.libChart = :%s', $alias, $key)) ->andWhere(sprintf('%s.player = pc.player', $alias)) ->setParameter($key, $lib); $queryBuilder ->addSelect(sprintf('(%s) as %s', $subQueryBuilder->getQuery()->getDQL(), $key)) ->addOrderBy($key, $lib->getType()->getOrderBy()) ->setParameter($key, $lib); } return $queryBuilder->getQuery()->getResult(); }
php
{ "resource": "" }
q11273
PlayerChartRepository.getRanking
train
public function getRanking(Chart $chart, $player = null, $limit = null) { $queryBuilder = $this->getRankingBaseQuery($chart); $queryBuilder ->andWhere('status.boolRanking = 1'); if (null !== $limit && null !== $player) { $queryBuilder ->andWhere( $queryBuilder->expr()->orX('pc.rank <= :maxRank', 'pc.player = :player') ) ->setParameter('maxRank', $limit) ->setParameter('player', $player); } elseif (null !== $limit) { $queryBuilder ->andWhere('pc.rank <= :maxRank') ->setParameter('maxRank', $limit); } return $queryBuilder->getQuery()->getResult(); }
php
{ "resource": "" }
q11274
PlayerChartRepository.getDisableRanking
train
public function getDisableRanking(Chart $chart) { $queryBuilder = $this->getRankingBaseQuery($chart); $queryBuilder ->andWhere('status.boolRanking = 0'); return $queryBuilder->getQuery()->getResult(); }
php
{ "resource": "" }
q11275
OrderListingItem.dueLabel
train
static function dueLabel($date) { $days = \FlexiPeeHP\FakturaVydana::overdueDays($date); if ($days < 0) { $type = 'success'; $msg = sprintf(_(' %s days to due'), new \Ease\TWB\Badge(abs($days))); } else { $msg = sprintf(_(' %s days after due'), new \Ease\TWB\Badge(abs($days))); if ($days > 14) { $type = 'danger'; } else { $type = 'warning'; } } return new \Ease\TWB\Label($type, $msg); }
php
{ "resource": "" }
q11276
ActionScriptHelper._createFileVersion
train
protected function _createFileVersion($timestamp = null) { if (!is_int($timestamp)) { $timestamp = time(); } $result = dechex($timestamp); return $result; }
php
{ "resource": "" }
q11277
ActionScriptHelper._prepareFilePath
train
protected function _prepareFilePath($path = null) { if (empty($path)) { return false; } if (DIRECTORY_SEPARATOR !== '\\') { return $path; } $path = str_replace('\\', '/', $path); return $path; }
php
{ "resource": "" }
q11278
ActionScriptHelper._getIncludeFilePath
train
protected function _getIncludeFilePath($specificFullPath = null, $specificPath = null, $specificFileName = null) { if (empty($specificFullPath) || empty($specificPath) || empty($specificFileName)) { return false; } $oFile = new File($specificFullPath . $specificFileName); if (!$oFile->exists()) { return false; } $includeFilePath = $this->_prepareFilePath($specificPath . $specificFileName); $lastChange = $oFile->lastChange(); $version = $this->_createFileVersion($lastChange); $result = $includeFilePath . '?v=' . $version; return $result; }
php
{ "resource": "" }
q11279
ActionScriptHelper.css
train
public function css($options = [], $params = [], $includeOnlyParam = false, $useUserRolePrefix = false) { $css = $this->getFilesForAction('css', $params, $includeOnlyParam, $useUserRolePrefix); if (empty($css)) { return null; } return $this->Html->css($css, $options); }
php
{ "resource": "" }
q11280
NewOrganizationTrigger.run
train
public function run($id, $databaseConnectionName, &$userAppsRecommendations) { $this->Setting->changeDatabaseConnection($databaseConnectionName); $this->Setting->create(array('organization_id' => $id)); array_push($userAppsRecommendations, array('appName' => $this->Lang->get('decima-accounting::menu.initialAccountingSetup'), 'appAction' => $this->Lang->get('decima-accounting::initial-accounting-setup.action'))); }
php
{ "resource": "" }
q11281
ExtBs3FormHelper.create
train
public function create($model = null, $options = []) { $form = parent::create($model, $options); if (!isset($options['url']) || ($options['url'] !== false)) { return $form; } // Ignore options `url` => false $result = mb_ereg_replace('action=\"[^\"]*\"', '', $form); return $result; }
php
{ "resource": "" }
q11282
ExtBs3FormHelper._initLabel
train
protected function _initLabel($options) { if (isset($options['label']) && is_array($options['label'])) { $options['label'] = [ 'text' => $options['label'] ]; } return parent::_initLabel($options); }
php
{ "resource": "" }
q11283
ExtBs3FormHelper.getLabelTextFromField
train
public function getLabelTextFromField($fieldName = null) { $text = ''; if (empty($fieldName)) { return $text; } if (strpos($fieldName, '.') !== false) { $fieldElements = explode('.', $fieldName); $text = array_pop($fieldElements); } else { $text = $fieldName; } if (substr($text, -3) === '_id') { $text = substr($text, 0, -3); } $text = Inflector::humanize(Inflector::underscore($text)); return $text; }
php
{ "resource": "" }
q11284
ExtBs3FormHelper._prepareExtraOptions
train
protected function _prepareExtraOptions(array &$options, $listExtraOptions = [], $optionPrefix = 'data-') { if (empty($options) || empty($listExtraOptions)) { return; } if (!is_array($listExtraOptions)) { $listExtraOptions = [$listExtraOptions]; } $extraOptions = array_intersect_key($options, array_flip($listExtraOptions)); if (empty($extraOptions)) { return; } foreach ($extraOptions as $extraOptionName => $extraOptionValue) { if (is_bool($extraOptionValue)) { if ($extraOptionValue) { $extraOptionValue = 'true'; } else { $extraOptionValue = 'false'; } } $options[$optionPrefix . $extraOptionName] = $extraOptionValue; unset($options[$extraOptionName]); } }
php
{ "resource": "" }
q11285
ExtBs3FormHelper._inputMaskAlias
train
protected function _inputMaskAlias($fieldName, $options = [], $alias = '') { if (!is_array($options)) { $options = []; } $defaultOptions = [ 'label' => false, ]; $options += $defaultOptions; $options['data-inputmask-alias'] = $alias; return $this->text($fieldName, $options); }
php
{ "resource": "" }
q11286
ExtBs3FormHelper.spin
train
public function spin($fieldName, $options = []) { if (!is_array($options)) { $options = []; } $defaultOptions = $this->_getOptionsForElem('spin.defaultOpt'); $options = $defaultOptions + $options; $listExtraOptions = $this->_getOptionsForElem('spin.extraOpt'); $this->_prepareExtraOptions($options, $listExtraOptions, 'data-spin-'); $numbers = ''; $decimals = ''; if (isset($options['data-spin-max']) && !empty($options['data-spin-max'])) { $numbers = mb_strlen($options['data-spin-max']); } if (isset($options['data-spin-decimals']) && !empty($options['data-spin-decimals'])) { $decimals = (int)$options['data-spin-decimals']; } $options['data-inputmask-mask'] = '9{1,' . $numbers . '}'; if (!empty($decimals)) { $options['data-inputmask-mask'] .= '.9{' . $decimals . '}'; } return $this->text($fieldName, $options); }
php
{ "resource": "" }
q11287
ExtBs3FormHelper.flag
train
public function flag($fieldName, $options = []) { if (!empty($fieldName)) { $this->setEntity($fieldName); } $this->unlockField($this->field()); if (!is_array($options)) { $options = []; } $defaultOptions = $this->_getOptionsForElem('flag.defaultOpt'); $options = $defaultOptions + $options; $divClass = 'form-group'; $label = ''; $list = []; $options = $this->_optionsOptions($options); if (isset($options['label'])) { $label = $this->label($fieldName, $options['label'], ['class' => 'control-label']); } if (isset($options['options'])) { $list = $options['options']; } $listExtraOptions = $this->_getOptionsForElem('flag.extraOpt'); $this->_prepareExtraOptions($options, $listExtraOptions); $errors = FormHelper::error($fieldName, null, ['class' => 'help-block']); if (!empty($errors)) { $divClass .= ' has-error error'; } $divOptions = [ 'id' => $this->domId($fieldName), 'data-input-name' => $this->_name(null, $fieldName), 'data-selected-country' => $this->value($fieldName), ]; $divOptionsDefault = $this->_getOptionsForElem('flag.divOpt'); if (!empty($list)) { $divOptions['data-countries'] = json_encode($list); } foreach ($listExtraOptions as $extraOptionName) { if (isset($options['data-' . $extraOptionName])) { $divClass['data-' . $extraOptionName] = $options['data-' . $extraOptionName]; } } $result = $this->Html->div($divClass, $label . $this->Html->div(null, '', $divOptions + $divOptionsDefault) . $errors); return $result; }
php
{ "resource": "" }
q11288
ExtBs3FormHelper.autocomplete
train
public function autocomplete($fieldName, $options = []) { if (!is_array($options)) { $options = []; } $defaultOptions = $this->_getOptionsForElem('autocomplete.defaultOpt'); $options = $defaultOptions + $options; $listExtraOptions = $this->_getOptionsForElem('autocomplete.extraOpt'); $this->_prepareExtraOptions($options, $listExtraOptions, 'data-autocomplete-'); if (!isset($options['data-autocomplete-url']) && !isset($options['data-autocomplete-local'])) { $options['data-autocomplete-url'] = $this->url( $this->ViewExtension->addUserPrefixUrl([ 'controller' => 'filter', 'action' => 'autocomplete', 'plugin' => 'cake_theme', 'ext' => 'json', 'prefix' => false ]) ); } if (isset($options['data-autocomplete-local']) && !empty($options['data-autocomplete-local'])) { if (!is_array($options['data-autocomplete-local'])) { $options['data-autocomplete-local'] = [$options['data-autocomplete-local']]; } $options['data-autocomplete-local'] = json_encode($options['data-autocomplete-local']); } return $this->text($fieldName, $options); }
php
{ "resource": "" }
q11289
ExtBs3FormHelper.createUploadForm
train
public function createUploadForm($model = null, $options = []) { if (empty($options) || !is_array($options)) { $options = []; } $optionsDefault = $this->_getOptionsForElem('createUploadForm'); $options = $this->ViewExtension->getFormOptions($optionsDefault + $options); $result = $this->create($model, $options); return $result; }
php
{ "resource": "" }
q11290
ExtBs3FormHelper.upload
train
public function upload($url = null, $maxfilesize = 0, $acceptfiletypes = null, $redirecturl = null, $btnTitle = null, $btnClass = null) { if (empty($url)) { return null; } if (empty($btnTitle)) { $btnTitle = $this->ViewExtension->iconTag('fas fa-file-upload') . '&nbsp;' . $this->_getOptionsForElem('upload.btnTitle'); } if (empty($btnClass)) { $btnClass = 'btn-success'; } $inputId = uniqid('input_'); $progressId = uniqid('progress_'); $filesId = uniqid('files_'); $inputOptions = [ 'id' => $inputId, 'data-progress-id' => $progressId, 'data-files-id' => $filesId, 'data-fileupload-url' => $url, 'data-fileupload-maxfilesize' => $maxfilesize, 'data-fileupload-acceptfiletypes' => $acceptfiletypes, 'data-fileupload-redirecturl' => $redirecturl ]; $optionsDefault = $this->_getOptionsForElem('upload.inputOpt'); $result = $this->Html->tag( 'span', $btnTitle . $this->input(null, $inputOptions + $optionsDefault), ['class' => 'fileinput-button btn ' . $btnClass] ) . $this->Html->tag('br') . $this->Html->tag('br') . $this->Html->div('progress', $this->Html->div('progress-bar progress-bar-success', ''), ['id' => $progressId]) . $this->Html->tag('hr') . $this->Html->div('files', '', ['id' => $filesId]) . $this->Html->tag('br'); return $result; }
php
{ "resource": "" }
q11291
ExtBs3FormHelper.hiddenFields
train
public function hiddenFields($hiddenFields = null) { if (empty($hiddenFields)) { return null; } if (!is_array($hiddenFields)) { $hiddenFields = [$hiddenFields]; } $result = ''; $options = ['type' => 'hidden']; foreach ($hiddenFields as $hiddenField) { $result .= $this->input($hiddenField, $options); if ($this->isFieldError($hiddenField)) { $result .= $this->Html->div( 'form-group has-error', $this->error($hiddenField, null, ['class' => 'help-block']) ); } } return $result; }
php
{ "resource": "" }
q11292
EloquentAccountType.create
train
public function create(array $data) { $AccountType = new AccountType(); $AccountType->setConnection($this->databaseConnectionName); $AccountType->fill($data)->save(); return $AccountType; }
php
{ "resource": "" }
q11293
EloquentAccountType.update
train
public function update(array $data, $AccountType = null) { if(empty($AccountType)) { $AccountType = $this->byId($data['id']); } foreach ($data as $key => $value) { $AccountType->$key = $value; } return $AccountType->save(); }
php
{ "resource": "" }
q11294
ProductShowListener.onProductShow
train
public function onProductShow(ResourceControllerEvent $event): void { $product = $event->getSubject(); if (!$product instanceof ProductInterface) { return; } $currentRequest = $this->requestStack->getCurrentRequest(); if ($currentRequest instanceof Request) { $currentRequest->attributes->set('nglayouts_sylius_product', $product); // We set context here instead in a ContextProvider, since sylius.product.show // event happens too late, after onKernelRequest event has already been executed $this->context->set('sylius_product_id', (int) $product->getId()); } }
php
{ "resource": "" }
q11295
Html.svgImg
train
public static function svgImg($src, $options = []) { $fallback = ArrayHelper::getValue($options, 'fallback', true); $fallbackExt = ArrayHelper::getValue($options, 'fallbackExt', 'png'); if ($fallback) { if (is_bool($fallback) && is_string($src)) { $fallback = rtrim($src, 'svg') . $fallbackExt; $options['onerror'] = "this.src = '$fallback'; this.onerror = '';"; } else if (is_string($fallback)) { $options['onerror'] = "this.src = '$fallback'; this.onerror = '';"; } } return self::img($src, $options); }
php
{ "resource": "" }
q11296
SocketService.run
train
public function run() { if(!$this->server) { try { // initialize socket server $this->server = new AppServer($this->config->socket->host, $this->config->socket->port); // create application with dependencies $app = new Sonar( new StorageService($this->config->storage), new QueueService($this->config->beanstalk), new GeoService(), new CacheService() ); $this->server->route('/sonar', $app, ['*']); } catch(QueueServiceException $e) { throw new AppServiceException($e->getMessage()); } catch(ConnectionException $e) { throw new SocketServiceException($e->getMessage()); } catch(StorageServiceException $e) { throw new AppServiceException($e->getMessage()); } catch(CacheServiceException $e) { throw new AppServiceException($e->getMessage()); } } if(isset($this->config->storage) === false) { throw new AppServiceException('There is no option `storage` in your configurations'); } $this->server->run(); }
php
{ "resource": "" }
q11297
ErrorHandler.handleError
train
public static function handleError($code, $message, $file, $line) { $list = static::getSystemError($code); $name = $list[0]; $type = $list[1]; $message = "\"$message\" in $file:$line"; switch ($type) { case static::E_NOTICE: throw new NoticeError($message); case static::E_WARNING: throw new WarningError($message); case static::E_ERROR: throw new FatalError($message); default: return; } }
php
{ "resource": "" }
q11298
ErrorHandler.handleShutdown
train
public static function handleShutdown($forceKill = false) { $err = error_get_last(); try { static::handleError($err['type'], $err['message'], $err['file'], $err['line']); } catch (\Error $ex) { echo call_user_func(static::$errHandler, $ex) . PHP_EOL; } catch (\Exception $ex) { echo call_user_func(static::$excHandler, $ex) . PHP_EOL; } if ($forceKill) { posix_kill(posix_getpid(), 9); } }
php
{ "resource": "" }
q11299
LdapFetcher.getInvocationId
train
public function getInvocationId() { $dsServiceNode = $this->ldap->getNode($this->getRootDse()->getDsServiceName()); $invocationId = bin2hex($dsServiceNode->getAttribute('invocationId', 0)); return $invocationId; }
php
{ "resource": "" }