_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
33
8k
language
stringclasses
1 value
meta_information
dict
q5400
DateController.syncCommand
train
public function syncCommand($url = 'http://www.baidu.com') { $timestamp = $this->_getRemoteTimestamp($url); if ($timestamp === false) {
php
{ "resource": "" }
q5401
DateController.remoteCommand
train
public function remoteCommand($url = 'http://www.baidu.com') { $timestamp = $this->_getRemoteTimestamp($url); if ($timestamp === false) {
php
{ "resource": "" }
q5402
DateController.diffCommand
train
public function diffCommand($url = 'http://www.baidu.com') { $remote_ts = $this->_getRemoteTimestamp($url); $local_ts = time(); if ($remote_ts === false) { return $this->console->error(['fetch remote timestamp failed: `:url`', 'url' => $url]); } else { $this->console->writeLn(' local: ' . date('Y-m-d H:i:s',
php
{ "resource": "" }
q5403
PluploadHandler._getRequestFile
train
private function _getRequestFile() { $data = [ 'name' => $this->_fileName, 'size' => $this->_fileSize,
php
{ "resource": "" }
q5404
TvheadendCommand.askQuestion
train
protected function askQuestion($question, $choices, $default) { // Ask until we get a valid response do { echo $question.' '.$choices.': '; $handle = fopen("php://stdin", "r"); $line = fgets($handle); $response = trim($line);
php
{ "resource": "" }
q5405
ApiKeyController.requestApiKeyAction
train
public function requestApiKeyAction(Request $request) { /** @var \Symfony\Component\EventDispatcher\EventDispatcherInterface $dispatcher */ $dispatcher = $this->get('event_dispatcher'); $credentials = []; if ($request->request->has('login')) { $credentials[$this->getPropertyName(ClassMetadata::LOGIN_PROPERTY)] = $request->request->get('login'); } if ($request->request->has('password')) { $credentials[$this->getPropertyName(ClassMetadata::PASSWORD_PROPERTY)] =
php
{ "resource": "" }
q5406
ApiKeyController.removeSessionAction
train
public function removeSessionAction(Request $request) { /** @var \Doctrine\Common\Persistence\ObjectManager $om */ $om = $this->get($this->container->getParameter('ma27_api_key_authentication.object_manager')); if (!$header = (string) $request->headers->get($this->container->getParameter('ma27_api_key_authentication.key_header'))) {
php
{ "resource": "" }
q5407
ApiKeyController.processAuthentication
train
private function processAuthentication(array $credentials) { /** @var \Ma27\ApiKeyAuthenticationBundle\Service\Auth\AuthenticationHandlerInterface $authenticationHandler */ $authenticationHandler = $this->get('ma27_api_key_authentication.auth_handler'); /** @var \Symfony\Component\EventDispatcher\EventDispatcherInterface $dispatcher */ $dispatcher = $this->get('event_dispatcher'); try { $user = $authenticationHandler->authenticate($credentials); } catch (CredentialException $ex) { $userOrNull = $user ?? null;
php
{ "resource": "" }
q5408
OracleMetaDataDAO.hydrateDataObject
train
private function hydrateDataObject($data) { $dataObject = new MetadataDataObjectOracle( new MetaDataColumnCollection(), new MetaDataRelationCollection() ); $tableName = $data['TABLE_NAME']; $owner = $data['OWNER']; $dataObject->setName($owner . '/' . $tableName); $columnDataObject = new MetaDataColumn(); $statement = $this->pdo->prepare( sprintf( "SELECT COLUMN_NAME as name, NULLABLE as nullable, DATA_TYPE as type, DATA_LENGTH as length FROM SYS.ALL_TAB_COLUMNS WHERE TABLE_NAME = '%s' and OWNER= '%s'", $tableName, $owner ) ); $statement->execute(array()); $allFields = $statement->fetchAll(PDO::FETCH_ASSOC); $identifiers = $this->getIdentifiers($owner, $tableName); foreach ($allFields as $metadata) { $column = clone $columnDataObject; $type = $metadata['type']; if (isset($this->typeConversion[$type]) ===
php
{ "resource": "" }
q5409
MySQLMetaDataDAO.pdoMetadataToGeneratorMetadata
train
private function pdoMetadataToGeneratorMetadata(array $metadataCollection) { $metaDataCollection = new MetaDataCollection(); foreach ($metadataCollection as $tableName) { $metaDataCollection->append(
php
{ "resource": "" }
q5410
MySQLMetaDataDAO.hydrateDataObject
train
private function hydrateDataObject($tableName, array $parentName = array()) { $dataObject = new MetadataDataObjectMySQL( new MetaDataColumnCollection(), new MetaDataRelationCollection() ); $dataObject->setName($tableName); $statement = $this->pdo->prepare( "SELECT columnTable.column_name, columnTable.table_name, columnTable.data_type, columnTable.column_key, columnTable.is_nullable, k.referenced_table_name, k.referenced_column_name FROM information_schema.columns as columnTable left outer join information_schema.key_column_usage k on k.table_schema=columnTable.table_schema and k.table_name=columnTable.table_name and k.column_name=columnTable.column_name WHERE columnTable.table_name = :tableName AND columnTable.table_schema = :databaseName" ); $statement->execute( array( ':tableName' => $tableName, ':databaseName' => $this->pdoConfig->getResponse('configDatabaseName'),
php
{ "resource": "" }
q5411
Auth.authenticate
train
public static function authenticate($identity, $credential) { //błędna autoryzacja (brak aktywnego użytkownika) if (null === $record = self::_findUserByIdentity($identity)) { return; } //próby logowania lokalnie
php
{ "resource": "" }
q5412
Auth.idAuthenticate
train
public static function idAuthenticate($id) { //wyszukiwanie aktywnego użytkownika if (null === $record = self::_findUserByIdentity($id)) {
php
{ "resource": "" }
q5413
Auth._authSuccess
train
protected static function _authSuccess(CmsAuthRecord $record) { //zapis poprawnego logowania do rekordu $record->lastIp = \Mmi\App\FrontController::getInstance()->getEnvironment()->remoteAddress; $record->lastLog = date('Y-m-d H:i:s'); $record->save(); \Mmi\App\FrontController::getInstance()->getLogger()->info('Logged in: ' . $record->username);
php
{ "resource": "" }
q5414
ConnectorModel.importFileMeta
train
public function importFileMeta(array $files) { //iteracja po plikach (ta sama nazwa "name") foreach ($files as $importData) { //brak id if (!isset($importData['name']) || !isset($importData['id'])) { return; } //sprawdzanie istnienia pliku if (null === $file = (new \Cms\Orm\CmsFileQuery)->findPk($importData['id'])) { $file = new \Cms\Orm\CmsFileRecord; } //identyfikatory niezgodne if ($file->name && $file->name != $importData['name']) {
php
{ "resource": "" }
q5415
Client.decode
train
public function decode($json) { $decoded = json_decode($json, true); if (null !== $decoded) {
php
{ "resource": "" }
q5416
CustomColumn.renderCell
train
public function renderCell(\Mmi\Orm\RecordRo $record) { $view = FrontController::getInstance()->getView(); $view->record
php
{ "resource": "" }
q5417
SerializeHydrator.extract
train
public function extract(callable $callback = null) { if ($callback === null) { $result = $this->result->serialize();
php
{ "resource": "" }
q5418
PHPCompiler.set_conf
train
function set_conf( $confname ){ $this->confname = $confname; $this->confdir = PLUG_HOST_DIR.'/'.$confname; if( ! PLUGTool::check_dir($this->confdir) ){ throw new PLUGException('bad conf'); } // parse default plug conf using external parser
php
{ "resource": "" }
q5419
PHPCompiler.load_conf
train
function load_conf( $confpath ){ if( ! PLUGTool::check_file($confpath) ){ throw new PLUGException('bad conf'); } $e = PLUG::exec_bin( 'parseconf', array($confpath), $s ); if( $e ){ trigger_error('Failed to parse '.basename($confpath), E_USER_NOTICE );
php
{ "resource": "" }
q5420
PHPCompiler.register_include
train
function register_include( $path ){ if( ! isset($this->incs[$path]) ){
php
{ "resource": "" }
q5421
PHPCompiler.next_dependency
train
function next_dependency(){ foreach( $this->dependencies as $path => $done ){ if( ! $done ){
php
{ "resource": "" }
q5422
PHPCompiler.open_php
train
private function open_php( &$src ){ if( ! $this->inphp ){ $this->inphp = true; // this may result in back to back tags, which we can avoid with a bit of string manipulation. $makenice = $this->opt(COMPILER_OPTION_NICE_TAGS); if( $makenice && substr( $src, -2 ) === '?>' ){ // trim trailing close tag, so no need to open one
php
{ "resource": "" }
q5423
PHPCompiler.close_php
train
private function close_php( &$src ){ if( $this->inphp ){ $this->inphp = false; // this may result in back to back tags, which we can avoid with a bit of string manipulation. $makenice = $this->opt(COMPILER_OPTION_NICE_TAGS); if( $makenice && substr( $src,
php
{ "resource": "" }
q5424
PLUGSessionObject.session_lifespan
train
function session_lifespan( $ttl = null, $hibernate = null ){ $current = $this->sess_ttl; if( $ttl !== null ){ $this->sess_ttl = $ttl; } if( $hibernate !==
php
{ "resource": "" }
q5425
PLUG.raise_error
train
static function raise_error( $code, $message, $type, array $trace = null ){ if( error_reporting() === 0 ){ // suppressed with `@' operator return; } self::clear_error_handlers();
php
{ "resource": "" }
q5426
PLUG.raise_exception
train
static function raise_exception( Exception $Ex, $type ){ if( error_reporting() === 0 ){ // suppressed with `@' operator return; } PLUG::clear_error_handlers();
php
{ "resource": "" }
q5427
PLUG.dump_errors
train
static function dump_errors( $emask = PLUG_ERROR_REPORTING ){ $errs = PLUGError::get_errors( $emask ); foreach( $errs as $Err ){ $s = $Err->__toString(). "\n";
php
{ "resource": "" }
q5428
PLUG.set_error_display
train
static function set_error_display( $handler ){ if( ! is_callable($handler) ){ trigger_error( 'Error
php
{ "resource": "" }
q5429
PLUG.set_error_logger
train
static function set_error_logger( $handler ){ if( ! is_callable($handler) ){ trigger_error( 'Error logging handler is not
php
{ "resource": "" }
q5430
PLUG.set_error_terminator
train
static function set_error_terminator( $handler ){ if( ! is_callable($handler) ){ trigger_error( 'Fatal error handler is not
php
{ "resource": "" }
q5431
UpdateLastActionFieldListener.onFirewallLogin
train
public function onFirewallLogin(OnFirewallAuthenticationEvent $event) {
php
{ "resource": "" }
q5432
UpdateLastActionFieldListener.doModify
train
private function doModify(AbstractUserEvent $event) { $this->classMetadata->modifyProperty( $event->getUser(),
php
{ "resource": "" }
q5433
Acl.setupAcl
train
public static function setupAcl() { $acl = new \Mmi\Security\Acl; $aclData = (new CmsAclQuery) ->join('cms_role')->on('cms_role_id') ->find(); foreach ($aclData as $aclRule) { /* @var $aclData \Cms\Orm\CmsAclRecord */ $resource = ''; if ($aclRule->module) { $resource .= $aclRule->module . ':'; } if ($aclRule->controller) { $resource .= $aclRule->controller . ':';
php
{ "resource": "" }
q5434
Log.create
train
public function create($userId=null, $eventLog=null, $eventData=null) { if(is_null($userId)) throw new \Exception('User ID is required.'); if(is_null($eventLog)) throw new \Exception('Event Log is required.'); if(!is_numeric($userId)) throw new \Exception("Invalid
php
{ "resource": "" }
q5435
AnnotatedRouteControllerLoader.configureRoute
train
protected function configureRoute(Route $route, \ReflectionClass $class, \ReflectionMethod $method, $annot) { parent::configureRoute($route, $class, $method, $annot);
php
{ "resource": "" }
q5436
PayPayWebservice.checkIntegrationState
train
public function checkIntegrationState() { $this->response = parent::checkIntegrationState($this->entity); /** * Checks the state of the platform integration. */
php
{ "resource": "" }
q5437
PayPayWebservice.subscribeToWebhook
train
public function subscribeToWebhook(Structure\RequestWebhook $requestWebhook) { $this->response = parent::subscribeToWebhook($this->entity, $requestWebhook); /** * Checks the state of the platform integration. */ if (Exception\IntegrationState::check($this->response->integrationState)) {
php
{ "resource": "" }
q5438
PayPayWebservice.createPaymentReference
train
public function createPaymentReference(Structure\RequestReferenceDetails $paymentData) { $this->response = parent::createPaymentReference($this->entity, $paymentData); /** * Checks the state of the platform integration. */ if (Exception\IntegrationState::check($this->response->integrationState)) {
php
{ "resource": "" }
q5439
PayPayWebservice.validatePaymentReference
train
public function validatePaymentReference(Structure\RequestReferenceDetails $paymentData) { $this->response = parent::validatePaymentReference($this->entity, $paymentData); /** * Checks the state of the platform integration. */ if (Exception\IntegrationState::check($this->response->integrationState)) {
php
{ "resource": "" }
q5440
PayPayWebservice.doWebPayment
train
public function doWebPayment($requestWebPayment) { $this->response = parent::doWebPayment($this->entity, $requestWebPayment); /** * Checks the state of the platform integration. */ if (Exception\IntegrationState::check($this->response->requestState)) {
php
{ "resource": "" }
q5441
PayPayWebservice.checkWebPayment
train
public function checkWebPayment($token, $transactionId) { $requestPayment = new Structure\RequestPaymentDetails($token, $transactionId); $this->response = parent::checkWebPayment($this->entity, $requestPayment); /** * Checks the state of the platform integration. */ if (Exception\IntegrationState::check($this->response->requestState)) { throw new Exception\IntegrationState($this->response->requestState);
php
{ "resource": "" }
q5442
PayPayWebservice.getEntityPayments
train
public function getEntityPayments($startDate, $endDate) { $requestInterval = new Structure\RequestInterval($startDate, $endDate); $this->response = parent::getEntityPayments($this->entity, $requestInterval); /** * Checks the state of the platform integration.
php
{ "resource": "" }
q5443
PayPayWebservice.checkEntityPayments
train
public function checkEntityPayments($payments = array()) { $requestReferenceDetails = new Structure\RequestEntityPayments(); if ($payments) { foreach ($payments as $key => $value) { $requestPayment = new Structure\RequestReferenceDetails($value); $requestReferenceDetails->addPayment($requestPayment); } } $this->response = parent::checkEntityPayments($this->entity, $requestReferenceDetails); /** * Checks the state of the platform integration. */ if (Exception\IntegrationState::check($this->response->state)) {
php
{ "resource": "" }
q5444
ZendFramework2Environnement.getDependence
train
public static function getDependence(FileManager $fileManager) { if (null === self::$serviceManager) { $config = self::findConfigFile($fileManager); try { self::$serviceManager = Application::init( $fileManager->includeFile($config) )->getServiceManager(); } catch(RuntimeException $e) { throw new EnvironnementResolverException($e->getMessage()); } catch (ExceptionInterface $e) { throw new EnvironnementResolverException(
php
{ "resource": "" }
q5445
LRStation.collect_non_deterministic
train
function collect_non_deterministic( Grammar $Grammar, $k ){ // avoid recursion by testing if already collected if ( isset($this->etransitions) ){ return; } $this->etransitions = array(); // get all rules with our non-terminal as left had side foreach( $Grammar->get_rules($this->nt) as $r => $rule ){ // create single Item for new state with pointer at start of rule $Item = LRItem::make( $r, $rule, 0 ); if( isset($this->la)
php
{ "resource": "" }
q5446
LRStation.collect_states
train
function collect_states( Grammar $Grammar ){ $states = array(); // start recursion $this->collect_states_recursive(
php
{ "resource": "" }
q5447
LRStation.make
train
static function make( $nt, $la = null ){ if( isset(self::$uindex[$nt][$la]) ){
php
{ "resource": "" }
q5448
LRStation.get
train
static function get( $nt, $la = null ){ if( isset(self::$uindex[$nt][$la]) ){
php
{ "resource": "" }
q5449
IncStatementNode.get_args
train
function get_args( array $consts, array $vars ){ $args = array(); // limit depth of search to avoid collecting nested func calls $argnodes = $this->get_nodes_by_symbol( NT_ARG, 3
php
{ "resource": "" }
q5450
HistoryFactory.getInstance
train
public static function getInstance(ContextInterface $context) { $fileManager = new FileManager(); $historyHydrator
php
{ "resource": "" }
q5451
GrammarBuilder.make
train
static function make( array $grammar, $class = __CLASS__ ){ $Me = new $class; foreach( $grammar as $nt => $rhss ){
php
{ "resource": "" }
q5452
GrammarBuilder.rule_signature
train
private static function rule_signature( $lhs, array $rhs ){
php
{ "resource": "" }
q5453
GrammarBuilder.make_rule
train
function make_rule( $nt, array $rhs ){ if( ! isset($this->uindex) || ! isset($this->ntindex) ){ $this->rebuild_index(); } // explicit goal rule ?? if( end($rhs) === P_EOF ){ // trigger_error("Do not specify P_EOF explicitly in grammar", E_USER_WARNING ); $this->goal = $nt; $this->rules[ -2 ] = array( P_GOAL, array( $nt ) ); $this->rebuild_index(); } // guess start symbol as first in grammar else if( is_null( $this->start_symbol() ) ){ $this->start_symbol( $nt ); } reset( $rhs ); $sig = self::rule_signature( $nt, $rhs ); // return existing if possible if( isset($this->uindex[$sig]) ){ return $this->rules[ $this->uindex[$sig] ]; } // else create new rule $rule = array( $nt, $rhs ); // register globally $this->rules[ $this->i ]
php
{ "resource": "" }
q5454
GrammarBuilder.remove_rules
train
function remove_rules( $nt ){ if( ! isset($this->ntindex) ){ $this->rebuild_index(); } // remove this non-terminal's rules if( isset($this->ntindex[$nt]) ){ foreach( $this->ntindex[$nt] as $i ){ $sig = self::rule_signature( $nt, $this->rules[$i][1] );
php
{ "resource": "" }
q5455
GrammarBuilder.build_first_sets
train
private function build_first_sets(){ $firsts = array(); do { $changes = 0; foreach( $this->rules as $rule ){ list( $nt, $rhs ) = $rule; $s = reset( $rhs ); // get any special rule processing for this non-terminal //$excludela = isset($this->excludela[$nt]) ? $this->excludela[$nt] : null; do { // add terminal to first set of $nt if( $this->is_terminal( $s ) ){ if( ! isset($firsts[$nt][$s]) ){ $firsts[$nt][$s] = $s; $changes++; } continue 2; } // else inherit from first set of this non-terminal if( ! isset($firsts[$s]) ){ // throw new Exception( sprintf("FIRST(%s) not defined", $s) ); $changes++; continue 2; } // collect all terminal symbols in this non-terminal's set // except the empty string which
php
{ "resource": "" }
q5456
GrammarBuilder.build_follow_sets
train
private function build_follow_sets(){ if( ! isset($this->firsts) ){ $this->firsts = $this->build_first_sets(); } // remember inhritance for error checking //$inherits = array(); // create default/dummy sets with special symbols $follows = array( P_GOAL => array(), P_EOF => array() ); do { $changes = 0; foreach( $this->rules as $rule ){ list( $s, $rhs ) = $rule; //echo "----\n"; //echo "$s -> ", implode(',', $rhs), "\n"; while( $a = current($rhs) ){ if( $a === P_EPSILON ){ next($rhs); continue; } //echo "\na = $a\n"; if( false === next($rhs) ){ // end of rule, inherit from LHS if( !isset($follows[$s]) ){ //echo "FOLLOW($s) not set, required by $a \n"; //$inherits[$s] = true; continue 2; } foreach( $follows[$s] as $t ){ if( !isset($follows[$a][$t]) ){ //echo "FOLLOW($a) []= $t \n"; $follows[$a][$t] = $t; $changes++; } } // next rule. continue 2; } $r = array_slice( $rhs, key($rhs) ); while( $b = current($r) ){ //echo "b = $b\n"; // merge first(b) into follow(a), // if it derives the empty string, continue to next in rhs $fs = $this->is_terminal($b) ? array($b) : $this->firsts[$b]; //echo "FOLLOW($a) []= FIRST($b) = ",implode(',', $fs),"\n"; foreach( $fs as $t ){
php
{ "resource": "" }
q5457
JsonHydrator.extract
train
public function extract(callable $callback = null) { $this->response = Di::getDefault()->get('response'); if ($callback === null) { $this->response->setContent(json_encode($this->result->toArray()));
php
{ "resource": "" }
q5458
IsEventSubscriberConstraint.matches
train
protected function matches($other): bool { $this->resetProblems(); if (!($other instanceof EventSubscriberInterface)) { $this->addProblem('Subscriber must implement \Symfony\Component\EventDispatcher\EventSubscriberInterface.'); return false; } $subscribedEvents = call_user_func(array(get_class($other), 'getSubscribedEvents')); if (!is_array($subscribedEvents)) { $this->addProblem('getSubscribedEvents() must return an array.');
php
{ "resource": "" }
q5459
IsEventSubscriberConstraint.checkListener
train
protected function checkListener(EventSubscriberInterface $subscriber, $event, $listener) { if (is_string($listener)) { // Add the default priority and use the default validation. $listener = array($listener, 0); } if (!is_array($listener)) { $this->addProblem(sprintf('Listener definition for event "%s" must be an array or a string.', $event)); return; } if ($this->containsSeveralSubscriptions($listener)) { foreach ($listener as $subListener) { $this->checkListener($subscriber, $event, $subListener); } return; } if (count($listener) === 1) { // Method without priority. $listener[] = 0; } if (count($listener) !== 2) {
php
{ "resource": "" }
q5460
IsEventSubscriberConstraint.checkMethod
train
protected function checkMethod($subscriber, $event, $method) { if (!is_string($method)) { $message = 'Listener definition for event "%s" contains an invalid method reference: %s'; $this->addProblem(sprintf($message, $event, $this->exporter->export($method))); return; } if (!method_exists($subscriber, $method)) { $message = 'Listener definition for event "%s" references method "%s", ' . 'but the method does not exist on subscriber.'; $this->addProblem(sprintf($message, $event, $method));
php
{ "resource": "" }
q5461
IsEventSubscriberConstraint.checkPriority
train
protected function checkPriority($event, $priority) { if (!is_int($priority)) { $message = 'Priority for event "%s" must be an integer, but received: %s';
php
{ "resource": "" }
q5462
ControllerPolicyMiddleware.isIgnoredDomain
train
public function isIgnoredDomain($domain) { if ($ignoreRegexes = $this->config()->get('ignore_domain_regexes')) {
php
{ "resource": "" }
q5463
ControllerPolicyMiddleware.process
train
public function process(HTTPRequest $request, callable $delegate) { /** @var HTTPResponse $response */ $response = $delegate($request); // Ignore by regexes. if ($this->shouldCheckHttpHost() && $this->isIgnoredDomain($_SERVER['HTTP_HOST'])) {
php
{ "resource": "" }
q5464
Direct._message
train
public function _message($type, $message) { $context = $this->_context; $cssClasses = isset($this->_cssClasses[$type]) ? $this->_cssClasses[$type] : '';
php
{ "resource": "" }
q5465
CategoryAclModel._updateAcl
train
protected function _updateAcl(\Cms\Orm\CmsCategoryAclRecord $aclRecord) { //iteracja po identyfikatorach kategorii foreach ($this->_getChildrenCategoryIds($aclRecord->cmsCategoryId) as $categoryId) { //dozwalanie lub zabranianie w ACL $aclRecord->access == 'allow' ?
php
{ "resource": "" }
q5466
PLUGTool.import_php
train
static function import_php( $package, $silent = false ){ $type = current( explode('.', $package) ); $paths = self::collect_package( $package, 'php', $silent, 'conf' ); if( !$silent && empty($paths) ){ trigger_error("Bad import `$package'", E_USER_ERROR ); } foreach( $paths as $cname => $path ){ // leniant inclusion if silent if( $silent ){ include_once $path; continue; } // path should already be validated by collect_package require_once $path; // Run checks according to type of import switch( $type ){ case 'conf': break; default: // Class or function import must
php
{ "resource": "" }
q5467
PLUGTool.collect_package
train
static function collect_package( $package, $ext, $silent, $confname ){ // get from cache for speed $cachekey = $package.'.'.$ext; if( isset(self::$dircache[$cachekey]) ){ return self::$dircache[$cachekey]; } $apath = explode( '.', $package ); $type = $apath[0]; // e.g. "PLUG" $cname = array_pop( $apath ); // e.g. "PLUGSession" // force special extensions, in certain cases switch( $type ){ case 'conf': $ext = 'conf.php'; break; } // special rules for types of import switch( $ext ){ case 'js': // Javascript under document root $dpath = PLUG_VIRTUAL_DIR.'/plug/js/'.implode( '/', $apath ); break; case 'conf.php': // replace with target conf dir $apath[0] = $confname; // fall through .... default: // regular PHP import from outside document root $dpath = PLUG_HOST_DIR .'/'. implode( '/', $apath ); } $incs = array(); switch( $cname ){ case '': case '*': // import all files under directory if( !$silent && !self::check_dir( $dpath ) ){ break; } $dhandle = opendir( $dpath ); while( $f = readdir($dhandle) ){ // skip dot files if( $f{0} === '.' ){ continue; } $i = strpos(
php
{ "resource": "" }
q5468
PLUGTool.collect_files
train
static function collect_files( $dpath, $r = false, $match = null, $ignore = null ){ $paths = array(); $dhandle = opendir( $dpath ); while( $f = readdir($dhandle) ){ if( $f === '.' || $f === '..' ){ continue; } // pattern tested only on file name // ignore pattern applies to directories as well as files if( isset($ignore) && preg_match($ignore, $f) ){ continue; } $path = $dpath.'/'.$f; if( is_dir($path) ){
php
{ "resource": "" }
q5469
PLUGTool.check_file
train
static function check_file( $path, $w = false, $isdir = false ){ $strtype = $isdir ? 'Directory' : 'File'; if( !file_exists($path) ){ trigger_error("$strtype not found; `$path'", E_USER_NOTICE ); return false; } if( $isdir && !is_dir($path) ){ trigger_error("Not a directory; `$path'", E_USER_NOTICE ); return false; } if( !$isdir && !is_file($path) ){ trigger_error("Not a file; `$path'", E_USER_NOTICE ); return false; } if(
php
{ "resource": "" }
q5470
PLUGTool.map_deployment_virtual
train
static function map_deployment_virtual( $path ){ // if path is outside document root move to special plug include dir if( strpos( $path, PLUG_VIRTUAL_DIR ) !== 0 ){ if( strpos( $path, PLUG_HOST_DIR ) === 0 ){ // is under host root $len = strlen(PLUG_HOST_DIR) + 1; $subpath = substr_replace( $path, '', 0, $len ); } else{ //
php
{ "resource": "" }
q5471
AttributeValueRelationModel.getRelationFiles
train
public function getRelationFiles() { $filesByObject = new \Mmi\Orm\RecordCollection; //wyszukiwanie wartości foreach ($this->getAttributeValues() as $record) { //pobieranie klucza atrybutu (w celu zgrupowania) if ($record->getJoined('cms_attribute_type')->uploader) { //dołączanie plików
php
{ "resource": "" }
q5472
ExportResponse.setCsv
train
public function setCsv(array &$data, $detectHead = true) { $handle = self::createMemoryHandle(); if($detectHead && count($data)> 0){ fputcsv($handle, array_keys($data[0]), $this->delimiter, $this->enclosure); } foreach ($data as $row) {
php
{ "resource": "" }
q5473
ExportResponse.setType
train
public function setType($type) { switch ($type) { case self::TYPE_CSV: $this->headers->add(array('Content-Type' => 'text/csv;charset=' . self::UTF_16_LE)); break; case self::TYPE_XLS:
php
{ "resource": "" }
q5474
ExportResponse.setFileName
train
public function setFileName($fileName) { $this->fileName = $fileName; $this->headers->add(array('Content-Disposition' =>
php
{ "resource": "" }
q5475
BNFRulesNode.collect_symbols
train
function collect_symbols(){ if( ! $this->length ){ return null; } $Rule = $this->reset(); do { if( $Rule->length !== 6 ){ // empty rule most likely continue; } // collect rule name - guaranteed to be nontermainal $Name = $Rule->get_child( 1 ); $n = $Name->evaluate(); $nts[ $n ] = $n; // assume first nt is start symbol if( is_null( $this->startsymbol ) ){ $this->startsymbol = $n; } $Expr = $Rule->get_child( 4 ); // lists in Expression $List = $Expr->reset(); do { // terms in list - may be terminal or nonterminal $Term = $List->reset(); do { $s = $Term->evaluate(); switch( $Term->length ){ case 1:
php
{ "resource": "" }
q5476
BNFRulesNode.make_lex
train
function make_lex( $i = 0 ){ $Lex = new LexBuilder( $i ); foreach( $this->collect_symbols() as $symbols ){ foreach( $symbols as $t => $s ){ if( preg_match('/^\W/', $s, $r
php
{ "resource": "" }
q5477
View.setVar
train
public function setVar($name, $value) { $context = $this->_context;
php
{ "resource": "" }
q5478
View.setVars
train
public function setVars($vars) { $context = $this->_context;
php
{ "resource": "" }
q5479
View.getVar
train
public function getVar($name = null) { $context = $this->_context; if ($name === null) { return $context->vars; } else {
php
{ "resource": "" }
q5480
View.render
train
public function render($template = null, $vars = null) { $context = $this->_context; if ($vars !== null) { $context->vars = $vars; } if (!$template) { $area = $this->dispatcher->getArea(); $controller = $this->dispatcher->getController(); if ($area) { $dir = "@app/Areas/$area/Views/$controller"; } else { $dir = "@views/$controller"; } if (!isset($this->_dirs[$dir])) {
php
{ "resource": "" }
q5481
JbConfigKnpMenuExtension.parseFile
train
public function parseFile($file) { $bundleConfig = Yaml::parse(file_get_contents(realpath($file))); if (!is_array($bundleConfig)) {
php
{ "resource": "" }
q5482
GeneratorFinderFactory.getInstance
train
public static function getInstance() { return new GeneratorFinderCache( new GeneratorFinder( TranstyperFactory::getInstance(),
php
{ "resource": "" }
q5483
Route._compilePattern
train
protected function _compilePattern($pattern) { if (strpos($pattern, '{') !== false) { $tr = [ '{area}' => '{area:[a-z]\w*}', '{controller}' => '{controller:[a-z]\w*}', '{action}' => '{action:[a-z]\w*}', '{params}' => '{params:.*}', '{id}' => '{id:[^/]+}', ':int' => ':\d+', ]; $pattern = strtr($pattern, $tr); } if (strpos($pattern, '{') !== false) { $need_restore_token = false; if (preg_match('#{\d#', $pattern) === 1) { $need_restore_token = true; $pattern = (string)preg_replace('#{([\d,]+)}#', '@\1@', $pattern); } $matches = []; if (preg_match_all('#{([A-Z].*)}#Ui', $pattern, $matches, PREG_SET_ORDER) > 0) { foreach ($matches as $match) { $parts = explode(':', $match[1], 2);
php
{ "resource": "" }
q5484
ClassMetadataPropertiesCacheWarmer.buildCacheData
train
private function buildCacheData() { $metadata = $this->driver->getMetadataForUser(); return serialize( array_map(function (\ReflectionProperty $property) {
php
{ "resource": "" }
q5485
Generator.addBuilder
train
public function addBuilder(BuilderInterface $builder) { $builder->setGenerator($this); $builder->setTemplateDirs($this->templateDirectories);
php
{ "resource": "" }
q5486
TextCat.createLM
train
public function createLM( $text, $maxNgrams ) { $ngram = []; foreach ( preg_split( "/[{$this->wordSeparator}]+/u", $text ) as $word ) { if ( empty( $word ) ) { continue; } $word = "_" . $word . "_"; $len = mb_strlen( $word, "UTF-8" ); for ( $i = 0; $i < $len; $i++ ) { $rlen = $len - $i; if ( $rlen > 4 ) { @$ngram[mb_substr( $word, $i, 5, "UTF-8" )]++; } if ( $rlen > 3 ) { @$ngram[mb_substr( $word, $i, 4, "UTF-8" )]++; } if ( $rlen > 2 ) { @$ngram[mb_substr( $word, $i, 3, "UTF-8" )]++; } if ( $rlen > 1 ) { @$ngram[mb_substr( $word, $i, 2, "UTF-8" )]++; } @$ngram[mb_substr( $word, $i, 1, "UTF-8" )]++;
php
{ "resource": "" }
q5487
TextCat.writeLanguageFile
train
public function writeLanguageFile( $ngrams, $outfile ) { $out = fopen( $outfile, "w" ); // write original array as "$ngrams" fwrite( $out, '<?php $ngrams = ' . var_export( $ngrams, true ) . ";\n" ); // write reduced array as "$ranks" $rank =
php
{ "resource": "" }
q5488
TextCat.classify
train
public function classify( $text, $candidates = null ) { $results = []; $this->resultStatus = ''; // strip non-word characters before checking for min length, don't assess empty strings $wordLength = mb_strlen( preg_replace( "/[{$this->wordSeparator}]+/", "", $text ) ); if ( $wordLength < $this->minInputLength || $wordLength == 0 ) { $this->resultStatus = self::STATUSTOOSHORT; return $results; } $inputgrams = array_keys( $this->createLM( $text, $this->maxNgrams ) ); if ( $candidates ) { // flip for more efficient lookups $candidates = array_flip( $candidates ); } foreach ( $this->langFiles as $language => $langFile ) { if ( $candidates && !isset( $candidates[$language] ) ) { continue; } $ngrams = $this->loadLanguageFile( $langFile ); $p = 0; foreach ( $inputgrams as $i => $ingram ) { if ( !empty( $ngrams[$ingram] ) ) { $p += abs( $ngrams[$ingram] - $i ); } else { $p += $this->maxNgrams; } } if ( isset( $this->boostedLangs[$language] ) ) { $p = round( $p * ( 1 - $this->langBoostScore ) ); } $results[$language] = $p; } asort( $results ); // ignore any item that scores higher than best * resultsRatio $max = reset( $results ) * $this->resultsRatio; $results = array_filter( $results, function ( $res ) use ( $max
php
{ "resource": "" }
q5489
AuthenticationPostListener.findAccessToken
train
private function findAccessToken(array $identity) { $config = $this->container->get('config'); foreach ($config['zf-oauth2-doctrine'] as $oauth2Config) { if (array_key_exists('object_manager', $oauth2Config)) { $objectManager = $this->container->get($oauth2Config['object_manager']); $accessTokenRepository = $objectManager ->getRepository($oauth2Config['mapping']['AccessToken']['entity']);
php
{ "resource": "" }
q5490
ProductControllerFeaturesExtension.GroupedFeatures
train
public function GroupedFeatures($showungrouped = false) { $features = $this->owner->Features() ->innerJoin("Feature","Feature.ID = ProductFeatureValue.FeatureID"); //figure out feature groups $groupids = FeatureGroup::get() ->innerJoin("Feature","Feature.GroupID = FeatureGroup.ID") ->innerJoin("ProductFeatureValue","Feature.ID = ProductFeatureValue.FeatureID") ->filter("ProductID",$this->owner->ID) ->getIDList(); //pack existin features into seperate lists $result = new ArrayList(); foreach($groupids as $groupid) { $group = FeatureGroup::get()->byID($groupid);
php
{ "resource": "" }
q5491
BNFParser.parse_string
train
static function parse_string( $s ){ if( $s == '' ){ throw new Exception('Cannot parse empty string'); } //
php
{ "resource": "" }
q5492
BNFParser.parse_file
train
static function parse_file( $f ){ $src = file_get_contents( $f, true ); if( $src === false ){ throw
php
{ "resource": "" }
q5493
Db.fetchOne
train
public function fetchOne($sql, $bind = [], $fetchMode = \PDO::FETCH_ASSOC, $useMaster = false) { return ($rs =
php
{ "resource": "" }
q5494
Db.fetchAll
train
public function fetchAll($sql, $bind = [], $fetchMode = \PDO::FETCH_ASSOC, $useMaster = false) { $context = $this->_context; $context->sql = $sql; $context->bind = $bind; $context->affected_rows = 0; $this->eventsManager->fireEvent('db:beforeQuery', $this); if ($context->connection) { $type = null; $connection = $context->connection; } else { $type = $this->_has_slave ? 'slave' : 'default';
php
{ "resource": "" }
q5495
Db.delete
train
public function delete($table, $conditions, $bind = []) { if (is_string($conditions)) { $conditions = [$conditions]; } $wheres = []; /** @noinspection ForeachSourceInspection */ foreach ($conditions as $k => $v) { if (is_int($k)) { $wheres[] = stripos($v, ' or ') ? "($v)" : $v; } else {
php
{ "resource": "" }
q5496
Db.getEmulatedSQL
train
public function getEmulatedSQL($preservedStrLength = -1) { $context = $this->_context; if (!$context->bind) { return (string)$context->sql; } $bind = $context->bind; if (isset($bind[0])) {
php
{ "resource": "" }
q5497
Db.begin
train
public function begin() { $context = $this->_context; $this->logger->info('transaction begin', 'db.transaction.begin'); if ($context->transaction_level === 0) { $this->eventsManager->fireEvent('db:beginTransaction', $this); try { $connection = $this->poolManager->pop($this, $this->_timeout); if (!$connection->beginTransaction()) { throw new DbException('beginTransaction failed.'); } $context->connection = $connection;
php
{ "resource": "" }
q5498
Db.rollback
train
public function rollback() { $context = $this->_context; if ($context->transaction_level > 0) { $this->logger->info('transaction rollback', 'db.transaction.rollback'); $context->transaction_level--; if ($context->transaction_level === 0) { $this->eventsManager->fireEvent('db:rollbackTransaction', $this);
php
{ "resource": "" }
q5499
CategoryModel.getCategoryTree
train
public function getCategoryTree($parentCategoryId = null) { //brak zdefiniowanej kategorii if ($parentCategoryId === null)
php
{ "resource": "" }