_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q240300
Regex.getMatches
train
public function getMatches($subject) { preg_match('/'.$this->pattern.'/',$subject,$matches); return count($matches) ? $matches : false; }
php
{ "resource": "" }
q240301
ModCombinationRepository.findByModNames
train
public function findByModNames(array $modNames): array { $result = []; if (count($modNames) > 0) { $queryBuilder = $this->entityManager->createQueryBuilder(); $queryBuilder->select(['mc', 'm']) ->from(ModCombination::class, 'mc') ->innerJoin('mc.mod', 'm') ->andWhere('m.name IN (:modNames)') ->addOrderBy('mc.order', 'ASC') ->setParameter('modNames', array_values($modNames)); $result = $queryBuilder->getQuery()->getResult(); } return $result; }
php
{ "resource": "" }
q240302
ModCombinationRepository.findModNamesByIds
train
public function findModNamesByIds(array $modCombinationIds): array { $result = []; if (count($modCombinationIds) > 0) { $queryBuilder = $this->entityManager->createQueryBuilder(); $queryBuilder->select('m.name') ->from(ModCombination::class, 'mc') ->innerJoin('mc.mod', 'm') ->andWhere('mc.id IN (:modCombinationIds)') ->addGroupBy('m.name') ->setParameter('modCombinationIds', array_values($modCombinationIds)); foreach ($queryBuilder->getQuery()->getResult() as $row) { $result[] = $row['name']; } } return $result; }
php
{ "resource": "" }
q240303
ModCombinationRepository.findAll
train
public function findAll(): array { $queryBuilder = $this->entityManager->createQueryBuilder(); $queryBuilder->select('mc') ->from(ModCombination::class, 'mc'); return $queryBuilder->getQuery()->getResult(); }
php
{ "resource": "" }
q240304
Site.process
train
public function process() { $pages = $this->pages; foreach ($this->plugins as $plugin) { $pages = $plugin($pages); } return $pages ?: []; }
php
{ "resource": "" }
q240305
StubsParser.condition
train
public function condition($name, callable $callback) { $this->conditions[$name] = $callback; // If $this->directive($name, function($expr) use ($name) { return $expr ? '<?php if ($__parser->check(\'' . $name . '\', $expr)): ?>' : '<?php if ($__parser->check(\'' . $name . '\')): ?>'; }); // elseif $this->directive('else' . $name, function($expr) use ($name) { return $expr ? '<?php elseif ($__parser->check(\'' . $name . '\', $expr)): ?>' : '<?php elseif ($__parser->check(\'' . $name . '\')): ?>'; }); // end $this->directive('end' . $name, function() { return '<?php endif; ?>'; }); }
php
{ "resource": "" }
q240306
StubsParser.check
train
public function check($name, $parameters) { $parameters = func_get_args(); // Remove $name array_shift($parameters); return call_user_func_array($this->conditions[$name], $parameters); }
php
{ "resource": "" }
q240307
BaseBlock.view
train
private function view() { if (isset(static::$view)) { return static::$view; } $classNamespace = $this->getModuleName(); $className = $this->getComponentName(); return "{$classNamespace}::blocks.{$className}"; }
php
{ "resource": "" }
q240308
AvatarExtension.buildAvatar
train
public function buildAvatar($size = 150) { $gravatar = new Gravatar(); $gravatar->setAvatarSize($size); $gravatar->enableSecureImages(); return $gravatar->buildGravatarURL($this->getUserEmail()); }
php
{ "resource": "" }
q240309
ErrorBox.updateErrorBox
train
public function updateErrorBox($form, $result, $errors) { if (($form->isSubmitted() && $result !== true) || count($errors) > 0) { if (is_string($result)) { $this->addError(new Error( Error::GENERAL_ERROR, $result )); } else if (count($errors) > 0) { foreach ($errors as $error) { $this->addError($error); } } else { $this->addError(new Error( Error::UNKNOWN_ERROR, '' )); } } }
php
{ "resource": "" }
q240310
AssetManager.sortFilesByDependencies
train
protected function sortFilesByDependencies($assets) { $sortedAssets = array(); foreach ($assets as $asset) { if ($asset->hasDependencies()) { $sortedAssets = $this->resolveDependencies($sortedAssets, $assets, $asset); } else { $sortedAssets[$asset->getAssetName()] = $asset; } } return $sortedAssets; }
php
{ "resource": "" }
q240311
AssetManager.resolveDependencies
train
protected function resolveDependencies($sortedAssets, $assets, $asset) { if ($asset->hasDependencies()) { foreach ($asset->getDependencies() as $dependency) { if (!isset($sortedAssets[$dependency]) && isset($assets[$dependency])) { $sortedAssets = $this->resolveDependencies($sortedAssets, $assets, $assets[$dependency]); } } } $sortedAssets[$asset->getAssetName()] = $asset; return $sortedAssets; }
php
{ "resource": "" }
q240312
AssetManager.getAssetFiles
train
public function getAssetFiles($type) { if (!isset($this->assets[$type])) { return false; } // Sort the files by dependnecies $files = $this->sortFilesByDependencies($this->assets[$type]); return $files; }
php
{ "resource": "" }
q240313
AssetManager.getAssetFile
train
public function getAssetFile($type, $assetName) { if (!$this->hasAsset($type, $assetName)) { return false; } // Sort the files by dependnecies $file = $this->assets[$type][$assetName]; return $file; }
php
{ "resource": "" }
q240314
AssetManager.isAbsolutePath
train
protected function isAbsolutePath($filePath) { if ($filePath === null || $filePath === '') { return false; } if ($filePath[0] === DIRECTORY_SEPARATOR || preg_match('~\A[A-Z]:(?![^/\\\\])~i', $filePath) > 0) { return true; } return false; }
php
{ "resource": "" }
q240315
Import.csv
train
public function csv(stdClass $variable) { (new Csv())->render($this->pdo, $this->info, $variable, $this->output); }
php
{ "resource": "" }
q240316
HierarchicalLoggerFactory.register
train
public function register ($name, LoggerInterface $logger) { $name = Util::normalizeName($name); $this->logs[$name] = $logger; }
php
{ "resource": "" }
q240317
HierarchicalLoggerFactory.getLogger
train
public function getLogger ($name) { if (!isset($this->logs[$name])) { $this->logs[$name] = $this->newLogger($name, $this->findParent($name)); } return $this->logs[$name]; }
php
{ "resource": "" }
q240318
Toolkit.doFlattenArray
train
private static function doFlattenArray(array &$values, array $subnode = null, $path = null): void { if (null === $subnode) { $subnode = &$values; } foreach ($subnode as $key => $value) { if (is_array($value)) { $nodePath = $path ? $path.'.'.$key : $key; static::doFlattenArray($values, $value, $nodePath); if (null === $path) { unset($values[$key]); } } elseif (null !== $path) { $values[$path.'.'.$key] = $value; } } }
php
{ "resource": "" }
q240319
Router.add
train
public static function add($path, $options = null, $prepend = false, $case_sensitive = null) { if (is_array($path)) { // Reverse to keep correct order in prepending $prepend and $path = array_reverse($path, true); foreach ($path as $p => $t) { static::add($p, $t, $prepend); } return; } elseif ($options instanceof Route) { static::$routes[$path] = $options; return; } $name = $path; if (is_array($options) and array_key_exists('name', $options)) { $name = $options['name']; unset($options['name']); if (count($options) == 1 and ! is_array($options[0])) { $options = $options[0]; } } if ($prepend) { \Arr::prepend(static::$routes, $name, new \Route($path, $options, $case_sensitive, $name)); return; } static::$routes[$name] = new \Route($path, $options, $case_sensitive, $name); }
php
{ "resource": "" }
q240320
Router.delete
train
public static function delete($path, $case_sensitive = null) { $case_sensitive ?: \Config::get('routing.case_sensitive', true); // support the usual route path placeholders $path = str_replace(array( ':any', ':alnum', ':num', ':alpha', ':segment', ), array( '.+', '[[:alnum:]]+', '[[:digit:]]+', '[[:alpha:]]+', '[^/]*', ), $path); foreach (static::$routes as $name => $route) { if ($case_sensitive) { if (preg_match('#^'.$path.'$#uD', $name)) { unset(static::$routes[$name]); } } else { if (preg_match('#^'.$path.'$#uiD', $name)) { unset(static::$routes[$name]); } } } }
php
{ "resource": "" }
q240321
Router.process
train
public static function process(\Request $request, $route = true) { $match = false; if ($route) { foreach (static::$routes as $route) { if ($match = $route->parse($request)) { break; } } } if ( ! $match) { // Since we didn't find a match, we will create a new route. $match = new Route(preg_quote($request->uri->get(), '#'), $request->uri->get()); $match->parse($request); } if ($match->callable !== null) { return $match; } return static::parse_match($match); }
php
{ "resource": "" }
q240322
Router.parse_match
train
protected static function parse_match($match) { $namespace = ''; $segments = $match->segments; $module = false; // First port of call: request for a module? if (\Module::exists($segments[0])) { // make the module known to the autoloader \Module::load($segments[0]); $match->module = array_shift($segments); $namespace .= ucfirst($match->module).'\\'; $module = $match->module; } if ($info = static::parse_segments($segments, $namespace, $module)) { $match->controller = $info['controller']; $match->action = $info['action']; $match->method_params = $info['method_params']; return $match; } else { return null; } }
php
{ "resource": "" }
q240323
Factory.createConfig
train
protected static function createConfig($file, $type = 'PHP', $namespace = '') { // Sanitize the namespace. $namespace = ucfirst((string) preg_replace('/[^A-Z_]/i', '', $namespace)); // Build the config name. $name = 'JConfig' . $namespace; if (!class_exists($name) && is_file($file)) { include_once $file; } // Create the registry with a default namespace of config $registry = new Registry; // Handle the PHP configuration type. if ($type == 'PHP' && class_exists($name)) { // Create the JConfig object $config = new $name; // Load the configuration values into the registry $registry->loadObject($config); } return $registry; }
php
{ "resource": "" }
q240324
AbstractServiceProvider.registerAdditionalProviders
train
protected function registerAdditionalProviders() { foreach ($this->providers as $provider) { if (class_exists($provider)) { $this->app->register($provider); } } }
php
{ "resource": "" }
q240325
AbstractServiceProvider.registerProvidersAliases
train
protected function registerProvidersAliases() { $loader = AliasLoader::getInstance(); foreach ($this->aliases as $alias => $provider) { if (class_exists($provider)) { $loader->alias( $alias, $provider ); } } }
php
{ "resource": "" }
q240326
Inflector.getPluginManager
train
public function getPluginManager() { if (!$this->pluginManager instanceof FilterPluginManager) { $this->setPluginManager(new FilterPluginManager(new ServiceManager())); } return $this->pluginManager; }
php
{ "resource": "" }
q240327
Inflector.addFilterRule
train
public function addFilterRule($spec, $ruleSet) { $spec = $this->_normalizeSpec($spec); if (!isset($this->rules[$spec])) { $this->rules[$spec] = []; } if (!is_array($ruleSet)) { $ruleSet = [$ruleSet]; } if (is_string($this->rules[$spec])) { $temp = $this->rules[$spec]; $this->rules[$spec] = []; $this->rules[$spec][] = $temp; } foreach ($ruleSet as $rule) { $this->rules[$spec][] = $this->_getRule($rule); } return $this; }
php
{ "resource": "" }
q240328
Inflector.setStaticRule
train
public function setStaticRule($name, $value) { $name = $this->_normalizeSpec($name); $this->rules[$name] = (string) $value; return $this; }
php
{ "resource": "" }
q240329
Inflector.setStaticRuleReference
train
public function setStaticRuleReference($name, &$reference) { $name = $this->_normalizeSpec($name); $this->rules[$name] =& $reference; return $this; }
php
{ "resource": "" }
q240330
Inflector._getRule
train
protected function _getRule($rule) { if ($rule instanceof FilterInterface) { return $rule; } $rule = (string) $rule; return $this->getPluginManager()->get($rule); }
php
{ "resource": "" }
q240331
RestApi.buildUrl
train
public function buildUrl(string $url): string { if (filter_var($url, FILTER_VALIDATE_URL)) { return $url; } return $this->endPoint . static::ENDPOINT_SUFFIX . $url; }
php
{ "resource": "" }
q240332
RestApi.buildRequest
train
protected function buildRequest(string $method, string $url, array $options = []): array { if ($this->forcedAcceptJson) { $this->headers['accept'] = 'application/json'; } if (count($this->headers) > 0) { if (!array_key_exists(RequestOptions::HEADERS, $options) || !is_array($options[RequestOptions::HEADERS])) { $options[RequestOptions::HEADERS] = []; } foreach ($this->headers as $headerName => $headerValue) { $options[RequestOptions::HEADERS][$headerName] = $headerValue; } } $options = $this->addAuthHeader($options); return [ self::OPTION_METHOD => $method, self::OPTION_URL => $this->buildUrl($url), self::OPTION_OPTIONS => $options ]; }
php
{ "resource": "" }
q240333
RestApi.buildGetRequestObject
train
public function buildGetRequestObject(string $url, array $data = null): Request { $requestOptions = [ RequestOptions::QUERY => $data ]; $options = $this->buildRequest(self::METHOD_GET, $url, $requestOptions); $headers = isset($options[self::OPTION_OPTIONS][RequestOptions::HEADERS]) ? $options[self::OPTION_OPTIONS][RequestOptions::HEADERS] : []; $body = isset($options[self::OPTION_OPTIONS][RequestOptions::BODY]) ? $options[self::OPTION_OPTIONS][RequestOptions::BODY] : null; $version = isset($options[self::OPTION_OPTIONS][RequestOptions::VERSION]) ? $options[self::OPTION_OPTIONS][RequestOptions::VERSION] : '1.1'; return new Request($options[self::OPTION_METHOD], $options[self::OPTION_URL], $headers, $body, $version); }
php
{ "resource": "" }
q240334
ViewFinderTrait.createSplFileInfoInstance
train
protected function createSplFileInfoInstance(string $directory, string $filename): SplFileInfo { return new SplFileInfo($directory.DIRECTORY_SEPARATOR.$filename, $directory, $filename); }
php
{ "resource": "" }
q240335
ViewFinderTrait.getView
train
public function getView(string $name): SplFileInfo { $viewFactory = app(Factory::class); $pattern = str_replace('.', DIRECTORY_SEPARATOR, $name); $path = $viewFactory->getFinder()->find($name); $pos = strpos($path, $pattern); $directory = substr($path, 0, $pos); $filename = substr($path, $pos); return $this->createSplFileInfoInstance($directory, $filename); }
php
{ "resource": "" }
q240336
CookiePool.add
train
public function add(Cookie $cookie) { if ($cookie instanceof MutableCookie) { $this->cookies[$cookie->getName()] = $cookie; } elseif ($cookie instanceof ResponseCookie) { $this[$cookie->getName()]->set($cookie->get()) ->setPath($cookie->getPath()) ->setDomain($cookie->getDomain()) ->setSecure($cookie->isSecure()) ->setHttpOnly($cookie->isHttpOnly()) ->expiresAt($cookie->getExpiration()); } else { $this->cookies[$cookie->getName()] = $this->setDefaults( new MutableCookie($cookie->getName(), $cookie->get()) ); } }
php
{ "resource": "" }
q240337
BaseController.getEntityName
train
public function getEntityName($_route = null) { if($_route == null) { $request = $this->get('request_stack')->getCurrentRequest(); $_route = $request->attributes->get('_route'); } $parts = explode('.', $_route); if(count($parts) == 2) { $namespace = $parts[0]; } $_route = end($parts); $parts = explode('_', $_route); if(count($parts) > 1) { $entity = $parts[count($parts)-2]; } else { $parts = explode(':', $_route); if(count($parts) == 2) { $entity = strtolower($parts[1]); } } //if((count($parts)-2) == -1) die(var_dump($_route)); //die(var_dump(count($parts))); //die(var_dump($entity)); return $entity; }
php
{ "resource": "" }
q240338
BaseController.getEntityClass
train
public function getEntityClass() { $entityClass = substr($this->getBundleName(), 0, 5) . '\\' . substr($this->getBundleName(), 5) .'\\Entity\\' . $this->getEntityNameUpper(); return $entityClass; }
php
{ "resource": "" }
q240339
InstanceManager.hasService
train
public function hasService($name) { if (!$this->serviceManager) { return false; } return $this->serviceManager->has($name, false); }
php
{ "resource": "" }
q240340
InstanceManager.getService
train
public function getService($name) { if (!$this->serviceManager) { throw new Exception\UndefinedReferenceException('Cannot get service without an service manager instance!'); } return $this->serviceManager->get($name); }
php
{ "resource": "" }
q240341
Mustache.addLocation
train
public function addLocation($location) { $loader = new \Mustache_Loader_FilesystemLoader($location); if ($this->mustache->getLoader() instanceof \Mustache_Loader_CascadingLoader) { $this->mustache->getLoader()->addLoader( $loader); } else { $loaders = [$this->mustache->getLoader(), $loader]; $this->mustache->setLoader(new \Mustache_Loader_CascadingLoader($loaders)); } return $this; }
php
{ "resource": "" }
q240342
Base.configureIntegerProperty
train
protected function configureIntegerProperty($property, OptionsResolver $resolver) { $resolver ->setAllowedTypes($property, ['integer', 'numeric']) ->setNormalizer($property, function (Options $options, $value) { return is_int($value) ? $value : intval($value); }); }
php
{ "resource": "" }
q240343
Base.configureBooleanProperty
train
protected function configureBooleanProperty($property, OptionsResolver $resolver) { $resolver ->setAllowedTypes($property, ['bool', 'string']) ->setAllowedValues($property, [true, false, 'true', 'false']) ->setNormalizer($property, function (Options $options, $value) { return is_bool($value) ? $value : ($value === 'true' ? true : false); }); }
php
{ "resource": "" }
q240344
Html.mobileCrop
train
public function mobileCrop($nbChars = self::CROP_AUTO) { $this->mobileCrop = $nbChars === null ? null : ($nbChars === self::CROP_AUTO ? self::CROP_AUTO : (int) $nbChars); return $this; }
php
{ "resource": "" }
q240345
Observer_Typing.typecast
train
public static function typecast($column, $value, $settings, $event_type = 'before') { // only on before_save, check if null is allowed if ($value === null) { // only on before_save if ($event_type == 'before') { if (array_key_exists('null', $settings) and $settings['null'] === false) { // if a default is defined, return that instead if (array_key_exists('default', $settings)) { return $settings['default']; } throw new InvalidContentType('The property "'.$column.'" cannot be NULL.'); } } return $value; } // no datatype given if (empty($settings['data_type'])) { return $value; } // get the data type for this column $data_type = $settings['data_type']; // is this a base data type? if ( ! isset(static::$type_methods[$data_type])) { // no, can we map it to one? if (isset(static::$type_mappings[$data_type])) { // yes, so swap it for a base data type $data_type = static::$type_mappings[$data_type]; } else { // can't be mapped, check the regexes foreach (static::$regex_methods as $match => $methods) { // fetch the method $method = ! empty($methods[$event_type]) ? $methods[$event_type] : false; if ($method) { if (preg_match_all($match, $data_type, $matches) > 0) { $value = call_user_func($method, $value, $settings, $matches); } } } return $value; } } // fetch the method $method = ! empty(static::$type_methods[$data_type][$event_type]) ? static::$type_methods[$data_type][$event_type] : false; // if one was found, call it if ($method) { $value = call_user_func($method, $value, $settings); } return $value; }
php
{ "resource": "" }
q240346
Observer_Typing.type_string
train
public static function type_string($var, array $settings) { if (is_array($var) or (is_object($var) and ! method_exists($var, '__toString'))) { throw new InvalidContentType('Array or object could not be converted to varchar.'); } $var = strval($var); if (array_key_exists('character_maximum_length', $settings)) { $length = intval($settings['character_maximum_length']); if ($length > 0 and strlen($var) > $length) { $var = substr($var, 0, $length); } } return $var; }
php
{ "resource": "" }
q240347
Observer_Typing.type_integer
train
public static function type_integer($var, array $settings) { if (is_array($var) or is_object($var)) { throw new InvalidContentType('Array or object could not be converted to integer.'); } if ((array_key_exists('min', $settings) and $var < intval($settings['min'])) or (array_key_exists('max', $settings) and $var > intval($settings['max']))) { throw new InvalidContentType('Integer value outside of range: '.$var); } return intval($var); }
php
{ "resource": "" }
q240348
Observer_Typing.type_float
train
public static function type_float($var) { if (is_array($var) or is_object($var)) { throw new InvalidContentType('Array or object could not be converted to float.'); } // deal with locale issues $locale_info = localeconv(); $var = str_replace($locale_info["mon_thousands_sep"] , "", $var); $var = str_replace($locale_info["mon_decimal_point"] , ".", $var); return floatval($var); }
php
{ "resource": "" }
q240349
Observer_Typing.type_decimal_after
train
public static function type_decimal_after($var, array $settings, array $matches) { if (is_array($var) or is_object($var)) { throw new InvalidContentType('Array or object could not be converted to decimal.'); } if ( ! is_numeric($var)) { throw new InvalidContentType('Value '.$var.' is not numeric and can not be converted to decimal.'); } $dec = empty($matches[2][0]) ? 2 : $matches[2][0]; return sprintf("%.".$dec."f", static::type_float($var)); }
php
{ "resource": "" }
q240350
Observer_Typing.type_set_before
train
public static function type_set_before($var, array $settings) { $var = is_array($var) ? implode(',', $var) : strval($var); $values = array_filter(explode(',', trim($var))); if ($settings['data_type'] == 'enum' and count($values) > 1) { throw new InvalidContentType('Enum cannot have more than 1 value.'); } foreach ($values as $val) { if ( ! in_array($val, $settings['options'])) { throw new InvalidContentType('Invalid value given for '.ucfirst($settings['data_type']). ', value "'.$var.'" not in available options: "'.implode(', ', $settings['options']).'".'); } } return $var; }
php
{ "resource": "" }
q240351
Observer_Typing.type_serialize
train
public static function type_serialize($var, array $settings) { $var = serialize($var); if (array_key_exists('character_maximum_length', $settings)) { $length = intval($settings['character_maximum_length']); if ($length > 0 and strlen($var) > $length) { throw new InvalidContentType('Value could not be serialized, exceeds max string length for field.'); } } return $var; }
php
{ "resource": "" }
q240352
Observer_Typing.type_json_encode
train
public static function type_json_encode($var, array $settings) { $var = json_encode($var); if (array_key_exists('character_maximum_length', $settings)) { $length = intval($settings['character_maximum_length']); if ($length > 0 and strlen($var) > $length) { throw new InvalidContentType('Value could not be JSON encoded, exceeds max string length for field.'); } } return $var; }
php
{ "resource": "" }
q240353
Observer_Typing.type_json_decode
train
public static function type_json_decode($var, $settings) { $assoc = false; if (array_key_exists('json_assoc', $settings)) { $assoc = (bool)$settings['json_assoc']; } return json_decode($var, $assoc); }
php
{ "resource": "" }
q240354
Observer_Typing.type_time_encode
train
public static function type_time_encode(\Fuel\Core\Date $var, array $settings) { if ( ! $var instanceof \Fuel\Core\Date) { throw new InvalidContentType('Value must be an instance of the Date class.'); } if ($settings['data_type'] == 'time_mysql') { return $var->format('mysql'); } return $var->get_timestamp(); }
php
{ "resource": "" }
q240355
Observer_Typing.type_time_decode
train
public static function type_time_decode($var, array $settings) { if ($settings['data_type'] == 'time_mysql') { // deal with a 'nulled' date, which according to MySQL is a valid enough to store? if ($var == '0000-00-00 00:00:00') { if (array_key_exists('null', $settings) and $settings['null'] === false) { throw new InvalidContentType('Value '.$var.' is not a valid date and can not be converted to a Date object.'); } return null; } return \Date::create_from_string($var, 'mysql'); } return \Date::forge($var); }
php
{ "resource": "" }
q240356
AttributesHelper.parse
train
public static function parse($string) { $attr = []; $list = []; preg_match_all('/([\w:-]+)[\s]?=[\s]?"([^"]*)"/i', $string, $attr); if ( is_array($attr) ){ $numPairs = count($attr[1]); for ($i = 0; $i < $numPairs; $i++){ $list[$attr[1][$i]] = $attr[2][$i]; } } return $list; }
php
{ "resource": "" }
q240357
AttributesHelper.merge
train
public static function merge(array $attrs=[]) { $attrs = (array)$attrs; $attributes=[]; foreach($attrs as $key => $value){ if ( $key === 'class' && is_array($value) ){ $value = array_unique($value); $value = implode(' ', $value); if ( empty($value) ){ continue; } } if ( true === $value ){ $value = 'true'; } elseif ( false === $value ){ $value = 'false'; } else { $value = trim($value); } // if ( '' === $value ){ // $value = $key; // } $attributes[] = $key.'="'.str_replace('"', '\"', trim($value)).'"'; } $attrs = implode(' ', $attributes); if ( $attrs !== '' ){ return ' '.$attrs; } return ''; }
php
{ "resource": "" }
q240358
Response.getReasonPhrase
train
public function getReasonPhrase() { $code = $this->getStatusCode(); if ($this->reasonPhrase === null && isset($this->phrases[$code])) { return $this->phrases[$code]; } return (string) $this->reasonPhrase; }
php
{ "resource": "" }
q240359
Response.sendHeaders
train
protected function sendHeaders() { if (headers_sent()) return false; header(sprintf( 'HTTP/%s %s %s', $this->getProtocolVersion(), $this->getStatusCode(), $this->getReasonPhrase() )); foreach ($this->getHeaderKeys() as $name) { header(sprintf('%s: %s', $name, $this->getHeaderLine($name)), true); } return true; }
php
{ "resource": "" }
q240360
Url.absolute
train
public function absolute($baseUrl) { $url = $this->url; $pos = strpos($url, '://'); if ($pos === false || $pos > 10) { $parsed = parse_url($baseUrl) + array( 'path' => '', ); if (!isset($parsed['scheme'], $parsed['host'])) throw new \Exception('Invalid base url "' . $baseUrl . '": scheme not found.'); if (empty($url)) return $baseUrl; if (strncmp($url, '//', 2) == 0) { return $parsed['scheme'] . ':' . $url; } $fullHost = $parsed['scheme'] . '://' . $parsed['host']; if (substr($url, 0, 1) == '?') { return $fullHost . $parsed['path'] . $url; } if (substr($url, 0, 1) == '/') { return $fullHost . $url; } $pathParts = explode('/', $parsed['path']); array_pop($pathParts); while (substr($url, 0, 3) == '../') { array_pop($pathParts); $url = substr($url, 3); } return $fullHost . implode('/', $pathParts) . '/' . $url; } return $url; }
php
{ "resource": "" }
q240361
Url.rootRelative
train
public function rootRelative($baseUrl) { $url = $this->url; $parsedBaseUrl = parse_url($baseUrl) + array( 'path' => '', ); if (!isset($parsedBaseUrl['scheme'], $parsedBaseUrl['host'])) { throw new \Exception('Invalid base url "' . $baseUrl . '": scheme not found.'); } if (empty($url)) { return $parsedBaseUrl['path'] . (isset($parsedBaseUrl['query']) ? '?' . $parsedBaseUrl['query'] : ''); } $parsedUrl = parse_url($url) + array( 'path' => '/', ); if (substr($url, 0, 1) == '?') { return $parsedBaseUrl['path'] . $url; } if (substr($url, 0, 3) == '../') { $pathParts = explode('/', $parsedBaseUrl['path']); array_pop($pathParts); while (substr($url, 0, 3) == '../') { array_pop($pathParts); $url = substr($url, 3); } return implode('/', $pathParts) . '/' . $url; } return $parsedUrl['path'] . (isset($parsedUrl['query']) ? '?' . $parsedUrl['query'] : ''); }
php
{ "resource": "" }
q240362
Url.addParams
train
public function addParams(array $addParams) { $parts = $this->split($this->url); parse_str($parts['query'], $params); $params = array_merge($params, $addParams); $parts['query'] = http_build_query($params); return $this->join($parts); }
php
{ "resource": "" }
q240363
Url.removeParams
train
public function removeParams(array $removeParams) { $parts = $this->split($this->url); parse_str($parts['query'], $params); $params = array_diff_key($params, array_flip($removeParams)); $parts['query'] = http_build_query($params); return $this->join($parts); }
php
{ "resource": "" }
q240364
Url.split
train
private function split($url) { $parts = parse_url($url) + array( 'scheme' => 'http', 'query' => '', 'path' => '', ); $parts['prefix'] = ''; if (isset($parts['host'])) { $parts['prefix'] = sprintf('%s://%s', $parts['scheme'], $parts['host']); } return $parts; }
php
{ "resource": "" }
q240365
ConfigContainer.get
train
public function get($name, $default = null) { if (!array_key_exists($name, $this->data)) { return $default; } return $this->data[$name]; }
php
{ "resource": "" }
q240366
ConfigContainer.merge
train
public function merge(ConfigContainer $other): ConfigContainer { if ($this->isFrozen()) { throw new FrozenContainerException('Container is frozen'); } if ($other->isFrozen()) { throw new FrozenContainerException('Container is frozen'); } foreach ($other as $name => $value) { if (!array_key_exists($name, $this->data)) { $this->data[$name] = $value; } else { if (is_int($name)) { $this->data[] = $value; } elseif ($value instanceof self && $this->data[$name] instanceof self) { $this->data[$name]->merge($value); } else { $this->data[$name] = $value; } } } return $this; }
php
{ "resource": "" }
q240367
ConfigContainer.freeze
train
public function freeze(): void { $this->frozen = true; foreach ($this->data as $value) { if ($value instanceof self) { $value->freeze(); } } }
php
{ "resource": "" }
q240368
ElementtypeStructureNode.isOptional
train
public function isOptional() { $min = (int) $this->getConfigurationValue('repeat_min'); $max = (int) $this->getConfigurationValue('repeat_max'); return $min === 0 && $max > 0; }
php
{ "resource": "" }
q240369
SimpleImage.create
train
function create($width, $height = null, $color = null) { $height = $height ? : $width; $this->width = $width; $this->height = $height; $this->image = imagecreatetruecolor($width, $height); $this->original_info = array( 'width' => $width, 'height' => $height, 'orientation' => $this->get_orientation(), 'exif' => null, 'format' => 'png', 'mime' => 'image/png' ); if ($color) { $this->fill($color); } return $this; }
php
{ "resource": "" }
q240370
SimpleImage.fill
train
function fill($color = '#000000') { $rgba = $this->normalize_color($color); $fill_color = imagecolorallocatealpha($this->image, $rgba['r'], $rgba['g'], $rgba['b'], $rgba['a']); imagealphablending($this->image, false); imagesavealpha($this->image, true); imagefilledrectangle($this->image, 0, 0, $this->width, $this->height, $fill_color); return $this; }
php
{ "resource": "" }
q240371
SimpleImage.get_orientation
train
function get_orientation() { if (imagesx($this->image) > imagesy($this->image)) { return 'landscape'; } if (imagesx($this->image) < imagesy($this->image)) { return 'portrait'; } return 'square'; }
php
{ "resource": "" }
q240372
SimpleImage.load_base64
train
function load_base64($base64string) { if (!extension_loaded('gd')) { throw new Exception('Required extension GD is not loaded.'); } //remove data URI scheme and spaces from base64 string then decode it $this->imagestring = base64_decode(str_replace(' ', '+', preg_replace('#^data:image/[^;]+;base64,#', '', $base64string))); $this->image = imagecreatefromstring($this->imagestring); return $this->get_meta_data(); }
php
{ "resource": "" }
q240373
SimpleImage.opacity
train
function opacity($opacity) { // Determine opacity $opacity = $this->keep_within($opacity, 0, 1) * 100; // Make a copy of the image $copy = imagecreatetruecolor($this->width, $this->height); imagealphablending($copy, false); imagesavealpha($copy, true); imagecopy($copy, $this->image, 0, 0, 0, 0, $this->width, $this->height); // Create transparent layer $this->create($this->width, $this->height, array(0, 0, 0, 127)); // Merge with specified opacity $this->imagecopymerge_alpha($this->image, $copy, 0, 0, 0, 0, $this->width, $this->height, $opacity); imagedestroy($copy); return $this; }
php
{ "resource": "" }
q240374
SimpleImage.output
train
function output($format = null, $quality = null) { // Determine quality $quality = $quality ? : $this->quality; // Determine mimetype switch (strtolower($format)) { case 'gif': $mimetype = 'image/gif'; break; case 'jpeg': case 'jpg': imageinterlace($this->image, true); $mimetype = 'image/jpeg'; break; case 'png': $mimetype = 'image/png'; break; default: $info = (empty($this->imagestring)) ? getimagesize($this->filename) : getimagesizefromstring($this->imagestring); $mimetype = $info['mime']; unset($info); break; } // Output the image header('Content-Type: ' . $mimetype); switch ($mimetype) { case 'image/gif': imagegif($this->image); break; case 'image/jpeg': imageinterlace($this->image, true); imagejpeg($this->image, null, round($quality)); break; case 'image/png': imagepng($this->image, null, round(9 * $quality / 100)); break; default: throw new Exception('Unsupported image format: ' . $this->filename); break; } }
php
{ "resource": "" }
q240375
SimpleImage.output_base64
train
function output_base64($format = null, $quality = null) { // Determine quality $quality = $quality ? : $this->quality; // Determine mimetype switch (strtolower($format)) { case 'gif': $mimetype = 'image/gif'; break; case 'jpeg': case 'jpg': imageinterlace($this->image, true); $mimetype = 'image/jpeg'; break; case 'png': $mimetype = 'image/png'; break; default: $info = getimagesize($this->filename); $mimetype = $info['mime']; unset($info); break; } // Output the image ob_start(); switch ($mimetype) { case 'image/gif': imagegif($this->image); break; case 'image/jpeg': imagejpeg($this->image, null, round($quality)); break; case 'image/png': imagepng($this->image, null, round(9 * $quality / 100)); break; default: throw new Exception('Unsupported image format: ' . $this->filename); break; } $image_data = ob_get_contents(); ob_end_clean(); // Returns formatted string for img src return 'data:' . $mimetype . ';base64,' . base64_encode($image_data); }
php
{ "resource": "" }
q240376
SimpleImage.get_meta_data
train
protected function get_meta_data() { //gather meta data if (empty($this->imagestring)) { $info = getimagesize($this->filename); switch ($info['mime']) { case 'image/gif': $this->image = imagecreatefromgif($this->filename); break; case 'image/jpeg': $this->image = imagecreatefromjpeg($this->filename); break; case 'image/png': $this->image = imagecreatefrompng($this->filename); break; default: throw new Exception('Invalid image: ' . $this->filename); break; } } elseif (function_exists('getimagesizefromstring')) { $info = getimagesizefromstring($this->imagestring); } else { throw new Exception('PHP 5.4 is required to use method getimagesizefromstring'); } $this->original_info = array( 'width' => $info[0], 'height' => $info[1], 'orientation' => $this->get_orientation(), 'exif' => function_exists('exif_read_data') && $info['mime'] === 'image/jpeg' && $this->imagestring === null ? $this->exif = @exif_read_data($this->filename) : null, 'format' => preg_replace('/^image\//', '', $info['mime']), 'mime' => $info['mime'] ); $this->width = $info[0]; $this->height = $info[1]; imagesavealpha($this->image, true); imagealphablending($this->image, true); return $this; }
php
{ "resource": "" }
q240377
Flash.get
train
public function get($key, $defaultValue = array()) { $this->populateFlash($key); if ($this->has($key)) { return $this->data[$key]; } return $defaultValue; }
php
{ "resource": "" }
q240378
TimeHelper.secondsToTime
train
public static function secondsToTime($seconds) { $dtF = new DateTime('@0'); $dtT = new DateTime("@$seconds"); $res = $dtF->diff($dtT); $days = $res->format('%a'); $hours = $res->format('%h'); $minutes = $res->format('%i'); $seconds = $res->format('%s'); $str = []; if ( intval($days) > 0 ){ $str[] = $days.' '.($days===1?'day':'days'); } if ( intval($hours) > 0 ){ $str[] = $hours.' '.($hours===1?'hour':'hours'); } if ( intval($minutes) > 0 ){ $str[] = $minutes.' '.($minutes===1?'minute':'minutes'); } if ( intval($seconds) > 0 ){ $str[] = $seconds.' '.($seconds===1?'second':'seconds'); } return implode(' ', $str); }
php
{ "resource": "" }
q240379
ResourceContainer.register
train
public function register($name, callable $factory) { $this->factories[$name] = $this->share($factory); unset($this->values[$name]); }
php
{ "resource": "" }
q240380
ResourceContainer.extend
train
public function extend($name, callable $extender) { if (! isset($this->factories[$name])) { throw new Exception( 'Trying to extend unknown resource "' . $name . '"', Exception::RESOURCE_NAME_UNKNOWN ); } $factory = $this->factories[$name]; $this->factories[$name] = $this->share( function ($container) use ($extender, $factory) { return $extender($factory, $container); } ); }
php
{ "resource": "" }
q240381
Pay.make
train
protected function make($gateway) { $app = new $gateway($this->config); if ($app instanceof GatewayApplicationInterface) { return $app; } throw new InvalidGatewayException("Gateway [$gateway] Must Be An Instance Of GatewayApplicationInterface"); }
php
{ "resource": "" }
q240382
Pay.registeLog
train
protected function registeLog() { $handler = new StreamHandler( $this->config->get('log.file'), $this->config->get('log.level', Logger::WARNING) ); $handler->setFormatter(new LineFormatter("%datetime% > %level_name% > %message% %context% %extra%\n\n")); $logger = new Logger('yansongda.pay'); $logger->pushHandler($handler); Log::setLogger($logger); }
php
{ "resource": "" }
q240383
AwsSesWrapper.factory
train
public static function factory($region, $profile, $configuration_set, $handler=null) { $config = [ 'region' => $region, 'profile' => $profile, 'http' => [ 'verify' => false//TODO: fix for production ], ]; if (!is_null($configuration_set)) $config['version'] = '2010-12-01'; if (!is_null($handler)) $config['handler'] = $handler; $client = SesClient::factory($config); return new AwsSesWrapper($client, $configuration_set); }
php
{ "resource": "" }
q240384
AwsSesWrapper.invokeMethod
train
public function invokeMethod($method, $request, $build=False) { if ($build) $request = $this->buildRequest($request); if ($this->debug) $this->_debug($request); return $this->ses_client->{$method.$this->asyncString}($request); }
php
{ "resource": "" }
q240385
AwsSesWrapper.sendEmail
train
public function sendEmail($dest, $subject, $html, $text) { $mail = [ 'Destination' => $this->buildDestination($dest), //'FromArn' => '<string>', 'Message' => [ // REQUIRED 'Body' => [ // REQUIRED 'Html' => ['Charset' => $this->charset,'Data' => $html], 'Text' => ['Charset' => $this->charset,'Data' => $text], ], 'Subject' => ['Charset' => $this->charset,'Data' => $subject], ], //'ReplyToAddresses' => [], //'ReturnPath' => '', //'ReturnPathArn' => '<string>', 'Source' => $this->from, // REQUIRED //'SourceArn' => '<string>', ]; if ($this->tags) $mail['Tags'] = $this->buildTags(); return $this->invokeMethod("sendEmail", $mail, true); }
php
{ "resource": "" }
q240386
AwsSesWrapper.sendRawEmail
train
public function sendRawEmail($raw_data, $dest=[]) { //force base64 encoding on v2 Api if ($this->isVersion2() && base64_decode($raw_data, true)===false) $raw_data = base64_encode($raw_data); $mail = [ //'FromArn' => '<string>', 'Source' => $this->from, // REQUIRED //'SourceArn' => '<string>', 'RawMessage' => ['Data' => $raw_data], //'ReturnPathArn' => '<string>', ]; // override destinations if ($dest) $mail['Destinations'] = $dest; if ($this->tags) $mail['Tags'] = $this->buildTags(); return $this->invokeMethod("sendRawEmail", $mail, true); }
php
{ "resource": "" }
q240387
AwsSesWrapper.buildDestination
train
private function buildDestination($emails) { $ret = ['ToAddresses' => isset($emails['to']) ? $emails['to'] : array_values($emails)]; if (isset($emails['cc']) && $emails['cc']) $ret['CcAddresses'] = $emails['cc']; if (isset($emails['bcc']) && $emails['cc']) $ret['BccAddresses'] = $emails['bcc']; return $ret; }
php
{ "resource": "" }
q240388
AwsSesWrapper.buildDestinations
train
private function buildDestinations($destinations) { $ret = array(); foreach ($destinations as $dest) { $d = [ "Destination" => $this->buildDestination($dest["dest"]), "ReplacementTemplateData" => $this->buildReplacements($dest["data"]) ]; if (isset($dest["tags"]) && $dest["tags"]) $d['ReplacementTags'] = $this->buildTags($dest["tags"]); $ret[] = $d; } return $ret; }
php
{ "resource": "" }
q240389
MString.codeUnit
train
public function codeUnit(){ $result = \unpack('N', \mb_convert_encoding( $this->_Value, 'UCS-4BE', 'UTF-8')); if(\is_array($result)){ return $result[1]; } return \ord($this->_Value); //$code = 0; //$l = \strlen($this->_Value); //$byte = $l - 1; // //for($i = 0; $i < $l; ++$i, --$byte){ // $code += \ord($this->_Value[$i]) << $byte * 8; //} // //return $code; }
php
{ "resource": "" }
q240390
MString.compareTo
train
public function compareTo($obj) { if(!($obj instanceof static)){ throw new \InvalidArgumentException('$obj is not a comparable instance'); } $coll = new \Collator(''); return $coll->compare($this->_Value, $obj->_Value); }
php
{ "resource": "" }
q240391
MString.convertEncoding
train
public function convertEncoding($newEncoding){ if(!\is_string($newEncoding)){ throw new \InvalidArgumentException('$newEncoding must be a string'); } $newEncoding = \strtoupper($newEncoding); return new static(\mb_convert_encoding($this->_Value, $newEncoding, $this->_Encoding), $newEncoding); }
php
{ "resource": "" }
q240392
MString.fromCodeUnit
train
public static function fromCodeUnit($unit){ if(!\is_numeric($unit)){ throw new \InvalidArgumentException('$unit must be a number'); } $str = \mb_convert_encoding( \sprintf('&#%s;', $unit), static::ENCODING, 'HTML-ENTITIES'); return new static($str, static::ENCODING); }
php
{ "resource": "" }
q240393
MString.fromString
train
public static function fromString($str, $encoding = self::ENCODING){ if(!\is_string($str)){ throw new \InvalidArgumentException('$str must be a PHP string'); } if(!\is_string($encoding)){ throw new \InvalidArgumentException('$encoding must be a string'); } return new static($str, $encoding); }
php
{ "resource": "" }
q240394
MString.indexOf
train
public function indexOf(self $str, $offset = 0, MStringComparison $cmp = null){ if(!$this->offsetExists($offset)){ throw new \OutOfRangeException('$offset is invalid'); } if($cmp === null || $cmp->Value === MStringComparison::CASE_SENSITIVE){ $index = \mb_strpos($this->_Value, $str->_Value, $offset, $this->_Encoding); } else{ $index = \mb_stripos($this->_Value, $str->_Value, $offset, $this->_Encoding); } return $index !== false ? $index : static::NO_INDEX; }
php
{ "resource": "" }
q240395
MString.insert
train
public function insert($index, self $str){ if(!$this->offsetExists($index)){ throw new \OutOfRangeException('$index is invalid'); } return new static( $this->substring(0, $index) . $str->_Value . $this->substring($index), $this->_Encoding); }
php
{ "resource": "" }
q240396
MString.lastIndexOf
train
public function lastIndexOf(self $str, $offset = 0, MStringComparison $cmp = null){ if(!$this->offsetExists($offset)){ throw new \OutOfRangeException('$offset is invalid'); } if($cmp === null || $cmp->Value === MStringComparison::CASE_SENSITIVE){ $index = \mb_strrpos($this->_Value, $str->_Value, $offset, $this->_Encoding); } else{ $index = \mb_strripos($this->_Value, $str->_Value, $offset, $this->_Encoding); } return $index !== false ? $index : static::NO_INDEX; }
php
{ "resource": "" }
q240397
MString.lcfirst
train
public function lcfirst(){ if($this->isNullOrWhitespace()){ return clone $this; } else if($this->count() === 1){ return new static(\mb_strtolower($this->_Value, $this->_Encoding), $this->_Encoding); } $str = $this[0]->lcfirst() . $this->substring(1); return new static($str, $this->_Encoding); }
php
{ "resource": "" }
q240398
MString.slowEquals
train
public function slowEquals(self $str){ $l1 = \strlen($this->_Value); $l2 = \strlen($str->_Value); $diff = $l1 ^ $l2; for($i = 0; $i < $l1 && $i < $l2; ++$i){ $diff |= \ord($this->_Value[$i]) ^ \ord($str->_Encoding[$i]); } return $diff === 0; }
php
{ "resource": "" }
q240399
MString.substring
train
public function substring($start, $length = null){ if(!$this->offsetExists($start)){ throw new \OutOfRangeException('$start is an invalid index'); } if($length !== null && !\is_numeric($length) || $length < 0){ throw new \InvalidArgumentException('$length is invalid'); } return new static(\mb_substr($this->_Value, $start, $length, $this->_Encoding), $this->_Encoding); }
php
{ "resource": "" }