_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q200
Term.getOneWhere
train
public static function getOneWhere($args = array()) { $args['number'] = 1; $result = static::getWhere($args); return (count($result)) ? current($result) : null; }
php
{ "resource": "" }
q201
Term.find
train
public static function find($term_id) { $instance = Post\Factory::create(get_called_class()); $instance->load($term_id); return $instance; }
php
{ "resource": "" }
q202
Loader.loadAll
train
public static function loadAll() { global $taxonomies_infos; // Classes $subclasses = self::getSubclasses(); foreach ($subclasses as $class) { $instance = new $class; $taxonomies_infos = array_merge( $taxonomies_infos, $instance->getTaxonomiesInfo() ); self::load($class); } }
php
{ "resource": "" }
q203
Loader.load
train
public static function load($class) { $instance = new $class; $post_type = $instance->getPostType(); // WordPress has a limit of 20 characters per if (strlen($post_type) > 20) { throw new \Exception('Post Type name exceeds maximum 20 characters: '.$post_type); } // This might happen if you're introducing a middle class between your post type and TacoPost // Ex: Foo extends \ClientTacoPost extends Taco\Post if (!$post_type) { return false; } //add_action('init', array($instance, 'registerPostType')); $instance->registerPostType(); add_action('save_post', array($instance, 'addSaveHooks')); if (is_admin()) { // If we're in the edit screen, we want the post loaded // so that TacoPost::getFields knows which post it's working with. // This helps if you want TacoPost::getFields to use conditional logic // based on which post is currently being edited. $is_edit_screen = ( is_array($_SERVER) && preg_match('/post.php\?post=[\d]{1,}/i', $_SERVER['REQUEST_URI']) && !Arr::iterable($_POST) ); $is_edit_save = ( preg_match('/post.php/i', $_SERVER['REQUEST_URI']) && Arr::iterable($_POST) ); $post = null; if ($is_edit_screen && array_key_exists('post', $_GET)) { $post = get_post($_GET['post']); } elseif ($is_edit_save) { $post = get_post($_POST['post_ID']); } if ($post && $post->post_type === $instance->getPostType()) { $instance->load($post); } add_action('admin_menu', array($instance, 'addMetaBoxes')); add_action(sprintf('manage_%s_posts_columns', $post_type), array($instance, 'addAdminColumns'), 10, 2); add_action(sprintf('manage_%s_posts_custom_column', $post_type), array($instance, 'renderAdminColumn'), 10, 2); add_filter(sprintf('manage_edit-%s_sortable_columns', $post_type), array($instance, 'makeAdminColumnsSortable')); add_filter('request', array($instance, 'sortAdminColumns')); add_filter('posts_clauses', array($instance, 'makeAdminTaxonomyColumnsSortable'), 10, 2); // Hide the title column in the browse view of the admin UI $is_browsing_index = ( is_array($_SERVER) && preg_match('/edit.php\?post_type='.$post_type.'$/i', $_SERVER['REQUEST_URI']) ); if ($is_browsing_index && $instance->getHideTitleFromAdminColumns()) { add_action('admin_init', function () { wp_register_style('hide_title_column_css', plugins_url('taco/base/hide_title_column.css')); wp_enqueue_style('hide_title_column_css'); }); } } }
php
{ "resource": "" }
q204
Loader.getSubclasses
train
public static function getSubclasses() { $subclasses = array(); foreach (get_declared_classes() as $class) { if (method_exists($class, 'isLoadable') && $class::isLoadable() === false) { continue; } if (is_subclass_of($class, 'Taco\Post')) { $subclasses[] = $class; } } return $subclasses; }
php
{ "resource": "" }
q205
Haversine.calculate
train
public function calculate(N\LatLong $point1, N\LatLong $point2) { $celestialBody = $this->getCelestialBody(); $deltaLat = $point2->getLatitude()->get() - $point1->getLatitude()->get(); $deltaLong = $point2->getLongitude()->get() - $point1->getLongitude()->get(); $a = sin($deltaLat / 2) * sin($deltaLat / 2) + cos($point1->getLatitude()->get()) * cos($point2->getLatitude()->get()) * sin($deltaLong / 2) * sin($deltaLong / 2); $c = 2 * atan2(sqrt($a), sqrt(1 - $a)); $d = $celestialBody->volumetricMeanRadius * $c * 1000; return $d; }
php
{ "resource": "" }
q206
Participant.update
train
public function update($params = []) { $response = Guzzle::put("tournaments/{$this->tournament_slug}/participants/{$this->id}", $params); return $this->updateModel($response->participant); }
php
{ "resource": "" }
q207
Transformer.transform
train
public function transform($object) { if (($collection = $this->normalize($object)) instanceof Collection) { return $this->transformCollection($collection); } // If there are relations setup, transform it along with the object. if ($this->relatedCount) { return $this->transformWithRelated($object); } // If another transformation method was requested, use that instead. if (is_callable($this->transformationMethod)) { return $this->getAlternateTransformation($object); } return $this->getTransformation($object); }
php
{ "resource": "" }
q208
Transformer.normalize
train
protected function normalize($object) { // If its a paginator instance, create a collection with its items. if ($object instanceof Paginator) { return collect($object->items()); } elseif (is_array($object)) { // If its an array, package it in a collection. return collect($object); } return $object; }
php
{ "resource": "" }
q209
Transformer.transformWithRelated
train
public function transformWithRelated($item) { $transformedItem = $this->getTransformation($item); return $this->transformRelated($transformedItem, $item); }
php
{ "resource": "" }
q210
Transformer.with
train
public function with($relation) { $this->reset(); if (func_num_args() > 1) { return $this->with(func_get_args()); } if (is_array($relation)) { $this->related = array_merge($this->related, $relation); } else { $this->related[] = $relation; } $this->relatedCount = count($this->related); return $this; }
php
{ "resource": "" }
q211
Transformer.setTransformation
train
public function setTransformation($transformation) { if (is_callable($transformation)) { $this->transformationMethod = $transformation; return $this; } // replace just to avoid wrongly passing the name containing "Transformation". $methodName = str_replace('Transformation', '', $transformation) . "Transformation"; if (! method_exists($this, $methodName)) { throw new TransformerException("No such transformation as $methodName defined."); } $this->transformationMethod = [$this, $methodName]; return $this; }
php
{ "resource": "" }
q212
Transformer.transformRelated
train
protected function transformRelated($itemTransformation, $item) { foreach ($this->related as $relation) { // get direct relation name. $relationName = explode('.', $relation, 2)[0]; $itemTransformation[$relationName] = $this->getRelatedTransformation($item, $relation); } return $itemTransformation; }
php
{ "resource": "" }
q213
Transformer.getRelatedTransformation
train
protected function getRelatedTransformation($item, $relation) { // get nested relations separated by the dot notation. // we only get one relation at a time because recursion handles the remaining relations. $nestedRelations = explode('.', $relation, 2); $relation = $nestedRelations[0]; $result = $item->{$relation}; $related = $result; $transformer = null; if (! is_object($related)) { return $related; } // if its a collection switch the object to the first item. if ($related instanceof Collection) { if ($related->count()) { $result = $result[0]; } else { return []; } } $transformer = $this->resolveTransformer($result); // If no transformer was resolved. if (! $transformer) { return $related->toArray(); } // if it has nested relations (equal to or more than 2 levels) if (count($nestedRelations) == 2) { // configure the remaining nested relations to the transformer. $transformer->with($nestedRelations[1]); } return $transformer->transform($related); }
php
{ "resource": "" }
q214
GreatCircle.calculate
train
public function calculate(N\LatLong $point1, N\LatLong $point2) { $celestialBody = $this->getCelestialBody(); $degrees = acos(sin($point1->getLatitude()->get()) * sin($point2->getLatitude()->get()) + cos($point1->getLatitude()->get()) * cos($point2->getLatitude()->get()) * cos($point2->getLongitude()->get() - $point1->getLongitude()->get())); $d = $degrees * $celestialBody->volumetricMeanRadius; return $d * 1000; }
php
{ "resource": "" }
q215
Gravatar.image
train
public static function image($sEmail, $iSize = null, $sDefaultImage = null, $sRating = null, $sExtension = null, $bForceDefault = false) { $gravatarImage = (new Image()) ->setEmail($sEmail) ->setSize($iSize) ->setDefaultImage($sDefaultImage, $bForceDefault) ->setMaxRating($sRating) ->setExtension($sExtension); return $gravatarImage; }
php
{ "resource": "" }
q216
Gravatar.images
train
public static function images(array $aEmail, $iSize = null, $sDefaultImage = null, $sRating = null, $sExtension = null, $bForceDefault = false) { $aImages = []; foreach ($aEmail as $sEmail) { $gravatarImage = (new Image()) ->setEmail($sEmail) ->setSize($iSize) ->setDefaultImage($sDefaultImage, $bForceDefault) ->setMaxRating($sRating) ->setExtension($sExtension); $aImages[$sEmail] = $gravatarImage; } return $aImages; }
php
{ "resource": "" }
q217
Gravatar.profiles
train
public static function profiles(array $aEmail, $sFormat = null) { $aProfils = []; foreach ($aEmail as $sEmail) { $gravatarProfil = (new Profile()) ->setEmail($sEmail) ->setFormat($sFormat); $aProfils[$sEmail] = $gravatarProfil; } return $aProfils; }
php
{ "resource": "" }
q218
Gravatar.email
train
public function email($sEmail = null) { if (null === $sEmail) { return $this->getEmail(); } return $this->setEmail($sEmail); }
php
{ "resource": "" }
q219
Factory.create
train
public static function create($post, $load_terms = true) { // Ex: Taco\Post\Factory::create('Video') if (is_string($post) && class_exists($post)) { return new $post; } $original_post = $post; if (!is_object($post)) { $post = get_post($post); } if (!is_object($post)) { throw new \Exception(sprintf('Post %s not found in the database', json_encode($original_post))); } // TODO Refactor how this works to be more explicit and less guess $class = str_replace(' ', '', ucwords(str_replace(Base::SEPARATOR, ' ', $post->post_type))); if (!class_exists($class)) { $class = str_replace(' ', '\\', ucwords(str_replace(Base::SEPARATOR, ' ', $post->post_type))); } $instance = new $class; $instance->load($post, $load_terms); return $instance; }
php
{ "resource": "" }
q220
Factory.createMultiple
train
public static function createMultiple($posts, $load_terms = true) { if (!Arr::iterable($posts)) { return $posts; } $out = array(); foreach ($posts as $k => $post) { if (!get_post_status($post)) { continue; } $record = self::create($post, $load_terms); $out[$k] = $record; } return $out; }
php
{ "resource": "" }
q221
Dm_Image.draw
train
public function draw(Dm_Image $image,$x=0,$y=0,$width=null,$height=null) { $srcImageResource = $image->getImageResource(); if (is_null($width)) $width = $image->getWidth(); if (is_null($height)) $height = $image->getHeight(); return imagecopy( $this->getImageResource(), $srcImageResource, $x, $y, 0, 0, $width, $height ); }
php
{ "resource": "" }
q222
Dm_Image.saveTo
train
public function saveTo($path , $type='png', $quality=null) { if (!$path) return false; return $this->outputTo($path, $type, $quality); }
php
{ "resource": "" }
q223
Dm_Image.destroy
train
public function destroy() { imagedestroy($this->_imageResource); $this->graphics->destroy(); $this->graphics = null; $this->textGraphics->destroy(); $this->textGraphics = null; }
php
{ "resource": "" }
q224
Dm_Image.toDataSchemeURI
train
public function toDataSchemeURI() { $md5 = md5(microtime(1).rand(10000, 99999)); $filePath = $this->tempDirPath() . DIRECTORY_SEPARATOR . "temp".$md5.".png"; $this->saveTo($filePath); $uri = 'data:' . mime_content_type($filePath) . ';base64,'; $uri .= base64_encode(file_get_contents($filePath)); unlink($filePath); return $uri; }
php
{ "resource": "" }
q225
Server.serve
train
public function serve($salt = '') { $protocol = isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0'; if ($input = $this->findInput()) { $output = $this->cacheName($salt . $input); $etag = $noneMatch = trim($this->getIfNoneMatchHeader(), '"'); if ($this->needsCompile($output, $etag)) { try { list($css, $etag) = $this->compile($input, $output); $lastModified = gmdate('D, d M Y H:i:s', filemtime($output)) . ' GMT'; header('Last-Modified: ' . $lastModified); header('Content-type: text/css'); header('ETag: "' . $etag . '"'); echo $css; } catch (\Exception $e) { if ($this->showErrorsAsCSS) { header('Content-type: text/css'); echo $this->createErrorCSS($e); } else { header($protocol . ' 500 Internal Server Error'); header('Content-type: text/plain'); echo 'Parse error: ' . $e->getMessage() . "\n"; } } return; } header('X-SCSS-Cache: true'); header('Content-type: text/css'); header('ETag: "' . $etag . '"'); if ($etag === $noneMatch) { header($protocol . ' 304 Not Modified'); return; } $modifiedSince = $this->getIfModifiedSinceHeader(); $mtime = filemtime($output); if (strtotime($modifiedSince) === $mtime) { header($protocol . ' 304 Not Modified'); return; } $lastModified = gmdate('D, d M Y H:i:s', $mtime) . ' GMT'; header('Last-Modified: ' . $lastModified); echo file_get_contents($output); return; } header($protocol . ' 404 Not Found'); header('Content-type: text/plain'); $v = Version::VERSION; echo "/* INPUT NOT FOUND scss $v */\n"; }
php
{ "resource": "" }
q226
Base.getPrefixGroupedMetaBoxes
train
public function getPrefixGroupedMetaBoxes() { $fields = $this->getFields(); // Just group by the field key prefix // Ex: home_foo would go in the Home section by default $groups = array(); foreach ($fields as $k => $field) { $prefix = current(explode('_', $k)); if (!array_key_exists($prefix, $groups)) { $groups[$prefix] = array(); } $groups[$prefix][] = $k; } return $groups; }
php
{ "resource": "" }
q227
Base.replaceMetaBoxGroupMatches
train
public function replaceMetaBoxGroupMatches($meta_boxes) { if (!Arr::iterable($meta_boxes)) { return $meta_boxes; } foreach ($meta_boxes as $k => $group) { $group = (is_array($group)) ? $group : array($group); if (array_key_exists('fields', $group)) { continue; } $fields = $this->getFields(); $new_group = array(); foreach ($group as $pattern_key => $pattern) { if (!preg_match('/\*$/', $pattern)) { $new_group[] = $pattern; continue; } $prefix = preg_replace('/\*$/', '', $pattern); $regex = sprintf('/^%s/', $prefix); foreach ($fields as $field_key => $field) { if (!preg_match($regex, $field_key)) { continue; } $new_group[] = $field_key; } } $meta_boxes[$k] = $new_group; } return $meta_boxes; }
php
{ "resource": "" }
q228
Base.getMetaBoxConfig
train
public function getMetaBoxConfig($config, $key = null) { // allow shorthand if (!array_key_exists('fields', $config)) { $fields = array(); foreach ($config as $field) { // Arbitrary HTML is allowed if (preg_match('/^\</', $field) && preg_match('/\>$/', $field)) { $fields[md5(mt_rand())] = array( 'type'=>'html', 'label'=>null, 'value'=>$field, ); continue; } $fields[$field] = $this->getField($field); } $config = array('fields'=>$fields); } if (Arr::iterable($config['fields'])) { $fields = array(); foreach ($config['fields'] as $k => $v) { if (is_array($v)) { $fields[$k] = $v; } else { $fields[$v] = $this->getField($v); } } $config['fields'] = $fields; } // defaults $config['title'] = (array_key_exists('title', $config)) ? $config['title'] : $this->getMetaBoxTitle($key); $config['context'] = (array_key_exists('context', $config)) ? $config['context'] : 'normal'; $config['priority'] = (array_key_exists('priority', $config)) ? $config['priority'] : 'high'; return $config; }
php
{ "resource": "" }
q229
Base.assign
train
public function assign($vals) { if (count($vals) === 0) { return 0; } $n = 0; foreach ($vals as $k => $v) { if ($this->set($k, $v)) { $n++; } } return $n; }
php
{ "resource": "" }
q230
Base.isValid
train
public function isValid($vals) { $fields = $this->getFields(); if (!Arr::iterable($fields)) { return true; } $result = true; // validate each field foreach ($fields as $k => $field) { // check if required if ($this->isRequired($field)) { if (!array_key_exists($k, $vals) || is_null($vals[$k]) || $vals[$k] === '' || $vals[$k] === false || ($field['type'] === 'checkbox' && empty($vals[$k])) ) { $result = false; $this->_messages[$k] = $this->getFieldRequiredMessage($k); continue; } } // check maxlength if (array_key_exists('maxlength', $field)) { if (strlen($vals[$k]) > $field['maxlength']) { $result = false; $this->_messages[$k] = 'Value too long'; continue; } } // after this point, we're only checking values based on type if (!array_key_exists($k, $vals)) { continue; } if (!array_key_exists('type', $field)) { continue; } // Select if ($field['type'] === 'select') { if (!array_key_exists($vals[$k], $field['options'])) { $result = false; $this->_messages[$k] = 'Invalid option'; } continue; } // Email if ($field['type'] === 'email') { if (!filter_var($vals[$k], FILTER_VALIDATE_EMAIL)) { $result = false; $this->_messages[$k] = 'Invalid email address'; } continue; } // URL if ($field['type'] === 'url') { if (!filter_var($vals[$k], FILTER_VALIDATE_URL)) { $result = false; $this->_messages[$k] = 'Invalid URL'; } continue; } // Color // http://www.w3.org/TR/html-markup/input.color.html#input.color.attrs.value if ($field['type'] === 'color') { if (!preg_match('/^#[0-9a-f]{6}$/i', $vals[$k])) { $result = false; $this->_messages[$k] = 'Invalid color'; } continue; } } return $result; }
php
{ "resource": "" }
q231
Base.getMetaBoxTitle
train
public function getMetaBoxTitle($key = null) { return ($key) ? Str::human($key) : sprintf('%s', $this->getSingular()); }
php
{ "resource": "" }
q232
Base.scrubAttributes
train
private static function scrubAttributes($field, $type = null) { $invalid_keys = [ 'default', 'description', 'label', 'options', ]; if ($type && $type ==='textarea') { $invalid_keys[] = 'value'; } foreach ($invalid_keys as $invalid_key) { if (array_key_exists($invalid_key, $field)) { unset($field[$invalid_key]); } } return $field; }
php
{ "resource": "" }
q233
Base.getCheckboxDisplay
train
public function getCheckboxDisplay($column_name) { $displays = $this->getCheckboxDisplays(); if (array_key_exists($column_name, $displays)) { return $displays[$column_name]; } if (array_key_exists('default', $displays)) { return $displays['default']; } return array('Yes', 'No'); }
php
{ "resource": "" }
q234
Base.renderAdminColumn
train
public function renderAdminColumn($column_name, $item_id) { $columns = $this->getAdminColumns(); if (!in_array($column_name, $columns)) { return; } $field = $this->getField($column_name); if (is_array($field)) { $class = get_called_class(); $entry = new $class; $entry->load($item_id); $out = $entry->get($column_name); if (isset($field['type'])) { switch ($field['type']) { case 'checkbox': $checkbox_display = $entry->getCheckboxDisplay($column_name); $out = ($entry->get($column_name)) ? reset($checkbox_display) : end($checkbox_display); break; case 'image': $out = Html::image($entry->get($column_name), $entry->get($column_name), array('class'=>'thumbnail')); break; case 'select': $out = array_key_exists($entry->get($column_name), $field['options']) ? $field['options'][$entry->get($column_name)] : null; break; } } // Hide the title field if necessary. // But since the title field is the link to the edit page // we are instead going to link the first custom field column. if (method_exists($this, 'getHideTitleFromAdminColumns') && $this->getHideTitleFromAdminColumns() && method_exists($this, 'getEditPermalink') && array_search($column_name, array_values($columns)) === 0 ) { $out = sprintf('<a href="%s">%s</a>', $this->getEditPermalink(), $out); } echo $out; return; } if (Arr::iterable($this->getTaxonomies())) { $taxonomy_key = $this->getTaxonomyKey($column_name); if ($taxonomy_key) { echo get_the_term_list($item_id, $taxonomy_key, null, ', '); return; } } }
php
{ "resource": "" }
q235
Base.makeAdminColumnsSortable
train
public function makeAdminColumnsSortable($columns) { $admin_columns = $this->getAdminColumns(); if (!Arr::iterable($admin_columns)) { return $columns; } foreach ($admin_columns as $k) { $columns[$k] = $k; } return $columns; }
php
{ "resource": "" }
q236
Base.getPlural
train
public function getPlural() { $singular = $this->getSingular(); if (preg_match('/y$/', $singular)) { return preg_replace('/y$/', 'ies', $singular); } return (is_null($this->plural)) ? Str::human($singular) . 's' : $this->plural; }
php
{ "resource": "" }
q237
Base.getThe
train
public function getThe($key, $convert_value = false, $return_wrapped = true) { if ($return_wrapped) { return apply_filters('the_content', $this->get($key, $convert_value)); } // Apply the_content filter without wrapping lines in <p> tags remove_filter('the_content', 'wpautop'); $value = apply_filters('the_content', $this->get($key, $convert_value)); add_filter('the_content', 'wpautop'); return $value; }
php
{ "resource": "" }
q238
Base.getLabelText
train
public function getLabelText($field_key) { $field = $this->getField($field_key); if (!is_array($field)) { return null; } return (array_key_exists('label', $field)) ? $field['label'] : Str::human(str_replace('-', ' ', preg_replace('/_id$/i', '', $field_key))); }
php
{ "resource": "" }
q239
Base.getRenderLabel
train
public function getRenderLabel($field_key, $required_mark = ' <span class="required">*</span>') { return sprintf( '<label for="%s">%s%s</label>', $field_key, $this->getLabelText($field_key), ($required_mark && $this->isRequired($field_key)) ? $required_mark : null ); }
php
{ "resource": "" }
q240
Base.isRequired
train
public function isRequired($field_key) { $field = (is_array($field_key)) ? $field_key : $this->getField($field_key); return (is_array($field) && array_key_exists('required', $field) && $field['required']); }
php
{ "resource": "" }
q241
DmsParser.parse
train
public function parse($coord) { $coordinate = null; $matches = array(); preg_match($this->input_format, $coord, $matches); if (count($matches) == 5) { $degrees = $matches[1]; $minutes = $matches[2] * (1 / 60); $seconds = $matches[3] * (1 / 60 * 1 / 60); $coordinate = ''; if (isset($matches[4])) { if ($matches[4] == 'S' or $matches[4] == 'W') { $coordinate = '-'; } } $coordinate .= $degrees + $minutes + $seconds; } if (is_numeric($coordinate)) { return deg2rad((float) $coordinate); } throw new E\InvalidCoordinateFormatException('The format of "' . $coord . '" cannot be parsed'); }
php
{ "resource": "" }
q242
DmsParser.get
train
public function get($coord) { $coord = rad2deg($coord); $degrees = (integer) $coord; $compass = ''; if ($this->direction == N::LAT) { if ($degrees < 0) $compass = 'S'; elseif ($degrees > 0) $compass = 'N'; }elseif ($this->direction == N::LONG) { if ($degrees < 0) $compass = 'W'; elseif ($degrees > 0) $compass = 'E'; } $minutes = $coord - $degrees; if ($minutes < 0) $minutes -= (2 * $minutes); if ($degrees < 0) $degrees -= (2 * $degrees); $minutes = $minutes * 60; $seconds = $minutes - (integer) $minutes; $minutes = (integer) $minutes; $seconds = (float) $seconds * 60; $coordinate = sprintf($this->output_format, $degrees, $minutes, $seconds, $compass); return $coordinate; }
php
{ "resource": "" }
q243
SqlTable.convertRow
train
protected function convertRow(array $row, Connection $connection, Table $table) { $result = []; foreach ($row as $key => $value) { $type = $table->getColumn($key)->getType(); $val = $type->convertToPHPValue($value, $connection->getDatabasePlatform()); if ($type instanceof Types\DateTimeType) { $val = $val->format(\DateTime::RFC3339); } elseif ($type instanceof Types\DateTimeTzType) { $val = $val->format(\DateTime::RFC3339_EXTENDED); } elseif ($type instanceof Types\TimeType) { $val = $val->format('H:i:s'); } elseif ($type instanceof Types\BinaryType || $type instanceof Types\BlobType) { $val = base64_encode(stream_get_contents($val)); } $result[$key] = $val; } return $result; }
php
{ "resource": "" }
q244
LoadRegisterViewHelper.renderStatic
train
public static function renderStatic(array $arguments, \Closure $renderChildrenClosure, RenderingContextInterface $renderingContext): string { $key = $arguments['key']; $value = $arguments['value']; array_push($GLOBALS['TSFE']->registerStack, $GLOBALS['TSFE']->register); $GLOBALS['TSFE']->register[$key] = $value; $content = $renderChildrenClosure(); if ($content) { // Restore register when content was rendered $GLOBALS['TSFE']->register = array_pop($GLOBALS['TSFE']->registerStack); return $content; } return ''; }
php
{ "resource": "" }
q245
Coordinate.guessParser
train
public function guessParser($coord) { if (!is_numeric($coord) and !is_null($coord)) { return new C\DmsParser; } return new C\DecimalParser; }
php
{ "resource": "" }
q246
TranslatableUtility.Master
train
public function Master() { if (Translatable::get_current_locale() != Translatable::default_locale()) { if ($master = $this->owner->getTranslation(Translatable::default_locale())) { return $master; } } return $this->owner; }
php
{ "resource": "" }
q247
Factory.create
train
public static function create($term, $taxonomy = null) { // Ex: Taco\Term\Factory::create('Keyword') if (is_string($term) && class_exists($term)) { return new $term; } if (!is_object($term)) { $term = get_term($term, $taxonomy); } // TODO Refactor how this works to be more explicit and less guess $class = str_replace(' ', '', ucwords(str_replace(Base::SEPARATOR, ' ', $term->taxonomy))); if (!class_exists($class)) { $class = str_replace(' ', '\\', ucwords(str_replace(Base::SEPARATOR, ' ', $term->taxonomy))); } $instance = new $class; $instance->load($term->term_id); return $instance; }
php
{ "resource": "" }
q248
Factory.createMultiple
train
public static function createMultiple($terms, $taxonomy = null) { if (!Arr::iterable($terms)) { return $terms; } $out = array(); foreach ($terms as $term) { $instance = self::create($term, $taxonomy); $out[$instance->get('term_id')] = $instance; } return $out; }
php
{ "resource": "" }
q249
RegistersUsers.signupUpdate
train
public function signupUpdate(Request $request) { $this->middleware('auth:api'); $data = $request->all(); $validator = Validator::make($data, [ 'firstname' => 'sometimes|required|max:255', 'surname' => 'sometimes|required|max:255', 'email' => 'sometimes|required|email|max:255|unique:users', 'mobile_number' => 'sometimes|min:10|unique:signup_data', 'password' => 'sometimes|required|min:6', 'gender' => 'sometimes|required', 'user_id' => 'required|integer', ]); if (!empty($validator->errors()->messages())) { return new Response([ 'status' => 'FAIL', 'message' => 'Fail to update user signup data', 'Errors' => $validator->errors() ], 500); } else { try { unset($data['_method']); $signupModel = Signup::find($data['user_id']); foreach ($data as $k => $ln) { $signupModel->$k = $ln; } $signupModel->save(); return new Response([ 'status' => 'OK', 'message' => 'User signup data updated', ], 201); } catch (\Illuminate\Database\QueryException $ex) { return new Response([ 'status' => 'Fail', 'message' => 'Fail updating', 'Errors ' => $ex->getMessage() ]); } } }
php
{ "resource": "" }
q250
JSON.encode
train
public static function encode($value, $options = 0, $depth = 512) { // multi-characters supported by default $options |= JSON_UNESCAPED_UNICODE; $data = version_compare(PHP_VERSION, '5.5.0', '>=') ? json_encode($value, $options, $depth) : json_encode($value, $options); if (JSON_ERROR_NONE !== json_last_error()) { return $data; } return version_compare(PHP_VERSION, '5.4.0', '>=') ? $data : preg_replace_callback("/\\\\u([0-9a-f]{2})([0-9a-f]{2})/iu", function ($pipe) { return iconv( strncasecmp(PHP_OS, 'WIN', 3) ? 'UCS-2BE' : 'UCS-2', 'UTF-8', chr(hexdec($pipe[1])) . chr(hexdec($pipe[2])) ); }, $data); }
php
{ "resource": "" }
q251
ConfigurationUtility.getExtensionConfig
train
public static function getExtensionConfig(): array { $supportedMimeTypes = self::DEFAULT_SUPPORTED_MIME_TYPES; $desktopWidth = self::DEFAULT_DESKTOP_WIDTH; $tabletWidth = self::DEFAULT_TABLET_WIDTH; $smartphoneWidth = self::DEFAULT_SMARTPHONE_WIDTH; if (isset($GLOBALS['TYPO3_CONF_VARS']['EXTENSIONS']['responsive_images'])) { $supportedMimeTypes = $GLOBALS['TYPO3_CONF_VARS']['EXTENSIONS']['responsive_images']['supportedMimeTypes'] ?? self::DEFAULT_SUPPORTED_MIME_TYPES; $desktopWidth = (int)$GLOBALS['TYPO3_CONF_VARS']['EXTENSIONS']['responsive_images']['maxDesktopImageWidth'] ?? self::DEFAULT_DESKTOP_WIDTH; $tabletWidth = (int)$GLOBALS['TYPO3_CONF_VARS']['EXTENSIONS']['responsive_images']['maxTabletImageWidth'] ?? self::DEFAULT_TABLET_WIDTH; $smartphoneWidth = (int)$GLOBALS['TYPO3_CONF_VARS']['EXTENSIONS']['responsive_images']['maxSmartphoneImageWidth'] ?? self::DEFAULT_SMARTPHONE_WIDTH; } elseif (isset($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']['responsive_images'])) { try { $extConfig = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']['responsive_images']); if (!empty($extConfig['supportedMimeTypes'])) { $supportedMimeTypes = $extConfig['supportedMimeTypes']; } if (isset($extConfig['maxDesktopImageWidth']) && is_numeric($extConfig['maxDesktopImageWidth'])) { $desktopWidth = (int)$extConfig['maxDesktopImageWidth']; } if (isset($extConfig['maxTabletImageWidth']) && is_numeric($extConfig['maxTabletImageWidth'])) { $tabletWidth = (int)$extConfig['maxTabletImageWidth']; } if (isset($extConfig['maxSmartphoneImageWidth']) && is_numeric($extConfig['maxSmartphoneImageWidth'])) { $smartphoneWidth = (int)$extConfig['maxSmartphoneImageWidth']; } } catch (\Exception $e) { } } return [ 'supportedMimeTypes' => $supportedMimeTypes, 'maxDesktopImageWidth' => $desktopWidth, 'maxTabletImageWidth' => $tabletWidth, 'maxSmartphoneImageWidth' => $smartphoneWidth, ]; }
php
{ "resource": "" }
q252
Loader.load
train
public static function load($class) { $instance = new $class; $taxonomy_key = $instance->getTaxonomyKey(); if (is_admin()) { add_action(sprintf('created_%s', $taxonomy_key), array($instance, 'addSaveHooks')); add_action(sprintf('edited_%s', $taxonomy_key), array($instance, 'addSaveHooks')); add_action(sprintf('%s_add_form_fields', $taxonomy_key), array($instance, 'addMetaBoxes')); add_action(sprintf('%s_edit_form_fields', $taxonomy_key), array($instance, 'addMetaBoxes')); add_action(sprintf('manage_edit-%s_columns', $taxonomy_key), array($instance, 'addAdminColumns'), 10, 3); add_action(sprintf('manage_%s_custom_column', $taxonomy_key), array($instance, 'renderAdminColumn'), 10, 3); // TODO add sorting //add_filter(sprintf('manage_edit-%s_sortable_columns', $taxonomy_key), array($instance, 'makeAdminColumnsSortable')); //add_filter('request', array($instance, 'sortAdminColumns')); } }
php
{ "resource": "" }
q253
CompletePurchaseResponse.calculateHash
train
private function calculateHash() { $hashType = $this->getHashType(); if ($hashType == 'sign') { throw new InvalidResponseException('Control sign forming method "SIGN" is not supported'); } elseif ($hashType == null) { throw new InvalidResponseException('Invalid signature type'); } return strtoupper(hash( $hashType, $this->data['LMI_PAYEE_PURSE']. $this->data['LMI_PAYMENT_AMOUNT']. $this->data['LMI_PAYMENT_NO']. $this->data['LMI_MODE']. $this->data['LMI_SYS_INVS_NO']. $this->data['LMI_SYS_TRANS_NO']. $this->data['LMI_SYS_TRANS_DATE']. $this->request->getSecretkey(). $this->data['LMI_PAYER_PURSE']. $this->data['LMI_PAYER_WM'] )); }
php
{ "resource": "" }
q254
Post.load
train
public function load($id, $load_terms = true) { $info = (is_object($id)) ? $id : get_post($id); if (!is_object($info)) { return false; } // Handle how WordPress converts special chars out of the DB // b/c even when you pass 'raw' as the 3rd partam to get_post, // WordPress will still encode the values. if (isset($info->post_title) && preg_match('/[&]{1,}/', $info->post_title)) { $info->post_title = html_entity_decode($info->post_title); } $this->_info = (array) $info; // meta $meta = get_post_meta($this->_info[self::ID]); if (Arr::iterable($meta)) { foreach ($meta as $k => $v) { $this->set($k, current($v)); } } // terms if (!$load_terms) { return true; } $this->loadTerms(); return true; }
php
{ "resource": "" }
q255
Post.loadTerms
train
public function loadTerms() { $taxonomy_keys = $this->getTaxonomyKeys(); if (!Arr::iterable($taxonomy_keys)) { return false; } // TODO Move this to somewhere more efficient // Check if this should be an instance of TacoTerm. // If not, the object will just be a default WP object from wp_get_post_terms below. $taxonomies_subclasses = array(); $subclasses = Term\Loader::getSubclasses(); foreach ($subclasses as $subclass) { $term_instance = new $subclass; $term_instance_taxonomy_key = $term_instance->getKey(); foreach ($taxonomy_keys as $taxonomy_key) { if (array_key_exists($taxonomy_key, $taxonomies_subclasses)) { continue; } if ($term_instance_taxonomy_key !== $taxonomy_key) { continue; } $taxonomies_subclasses[$taxonomy_key] = $subclass; break; } } foreach ($taxonomy_keys as $taxonomy_key) { $terms = wp_get_post_terms($this->get(self::ID), $taxonomy_key); if (!Arr::iterable($terms)) { continue; } $terms = array_combine( array_map('intval', Collection::pluck($terms, 'term_id')), $terms ); // Load Taco\Term if applicable if (array_key_exists($taxonomy_key, $taxonomies_subclasses)) { $terms = Term\Factory::createMultiple($terms, $taxonomy_key); } $this->_terms[$taxonomy_key] = $terms; } return true; }
php
{ "resource": "" }
q256
Post.getDefaults
train
public function getDefaults() { global $user; return array( 'post_type' => $this->getPostType(), 'post_author' => (is_object($user)) ? $user->ID : null, 'post_date' => current_time('mysql'), 'post_category' => array(0), 'post_status' => 'publish' ); }
php
{ "resource": "" }
q257
Post.registerPostType
train
public function registerPostType() { $config = $this->getPostTypeConfig(); if (empty($config)) { return; } register_post_type($this->getPostType(), $config); }
php
{ "resource": "" }
q258
Post.getTaxonomy
train
public function getTaxonomy($key) { $taxonomies = $this->getTaxonomies(); if (!Arr::iterable($taxonomies)) { return false; } $taxonomy = (array_key_exists($key, $taxonomies)) ? $taxonomies[$key] : false; if (!$taxonomy) { return false; } // Handle all of these: // return array('one', 'two', 'three'); // return array('one'=>'One Category', 'two', 'three'); // return array( // 'one'=>array('label'=>'One Category'), // 'two'=>array('rewrite'=>array('slug'=>'foobar')), // 'three' // ); if (is_string($taxonomy)) { $taxonomy = (is_numeric($key)) ? array('label'=>self::getGeneratedTaxonomyLabel($taxonomy)) : array('label'=>$taxonomy); } elseif (is_array($taxonomy) && !array_key_exists('label', $taxonomy)) { $taxonomy['label'] = self::getGeneratedTaxonomyLabel($key); } // Unlike WordPress default, we'll default to hierarchical=true // That's just more common for us if (!array_key_exists('hierarchical', $taxonomy)) { $taxonomy['hierarchical'] = true; } return $taxonomy; }
php
{ "resource": "" }
q259
Post.getTaxonomyKeys
train
public function getTaxonomyKeys() { $taxonomies = $this->getTaxonomies(); if (!Arr::iterable($taxonomies)) { return array(); } $out = array(); foreach ($taxonomies as $k => $taxonomy) { $taxonomy = $this->getTaxonomy($k); $out[] = $this->getTaxonomyKey($k, $taxonomy); } return $out; }
php
{ "resource": "" }
q260
Post.getTaxonomyKey
train
public function getTaxonomyKey($key, $taxonomy = array()) { if (is_string($key)) { return $key; } if (is_array($taxonomy) && array_key_exists('label', $taxonomy)) { return Str::machine($taxonomy['label'], Base::SEPARATOR); } return $key; }
php
{ "resource": "" }
q261
Post.getTaxonomiesInfo
train
public function getTaxonomiesInfo() { $taxonomies = $this->getTaxonomies(); if (!Arr::iterable($taxonomies)) { return array(); } $out = array(); foreach ($taxonomies as $k => $taxonomy) { $taxonomy = $this->getTaxonomy($k); $key = $this->getTaxonomyKey($k, $taxonomy); $out[] = array( 'key' => $key, 'post_type' => $this->getPostType(), 'config' => $taxonomy ); } return $out; }
php
{ "resource": "" }
q262
Post.getPostTypeConfig
train
public function getPostTypeConfig() { if (in_array($this->getPostType(), array('post', 'page'))) { return null; } return array( 'labels' => array( 'name' => _x($this->getPlural(), 'post type general name'), 'singular_name' => _x($this->getSingular(), 'post type singular name'), 'add_new' => _x('Add New', $this->getSingular()), 'add_new_item' => __(sprintf('Add New %s', $this->getSingular())), 'edit_item' => __(sprintf('Edit %s', $this->getSingular())), 'new_item' => __(sprintf('New %s', $this->getPlural())), 'view_item' => __(sprintf('View %s', $this->getSingular())), 'search_items' => __(sprintf('Search %s', $this->getPlural())), 'not_found' => __(sprintf('No %s found', $this->getPlural())), 'not_found_in_trash'=> __(sprintf('No %s found in Trash', $this->getPlural())), 'parent_item_colon' => '' ), 'hierarchical' => $this->getHierarchical(), 'public' => $this->getPublic(), 'supports' => $this->getSupports(), 'show_in_menu' => $this->getShowInMenu(), 'show_in_admin_bar' => $this->getShowInAdminBar(), 'menu_icon' => $this->getMenuIcon(), 'menu_position' => $this->getMenuPosition(), 'exclude_from_search' => $this->getExcludeFromSearch(), 'has_archive' => $this->getHasArchive(), 'rewrite' => $this->getRewrite(), 'publicly_queryable' => $this->getPubliclyQueryable(), ); }
php
{ "resource": "" }
q263
Post.getMenuIcon
train
public function getMenuIcon() { // Look for these files by default // If your plugin directory contains an [post-type].png file, that will by default be the icon // Ex: hot-sauce.png $reflector = new \ReflectionClass(get_called_class()); $dir = basename(dirname($reflector->getFileName())); $post_type = $this->getPostType(); $fnames = array( $post_type.'.png', $post_type.'.gif', $post_type.'.jpg' ); foreach ($fnames as $fname) { $fpath = sprintf('%s/%s/%s', WP_PLUGIN_DIR, $dir, $fname); if (!file_exists($fpath)) { continue; } return sprintf('%s/%s/%s', WP_PLUGIN_URL, $dir, $fname); } return ''; }
php
{ "resource": "" }
q264
Post.sortAdminColumns
train
public function sortAdminColumns($vars) { if (!isset($vars['orderby'])) { return $vars; } $admin_columns = $this->getAdminColumns(); if (!Arr::iterable($admin_columns)) { return $vars; } foreach ($admin_columns as $k) { if ($vars['orderby'] !== $k) { continue; } $vars = array_merge($vars, array( 'meta_key'=> $k, 'orderby' => 'meta_value' )); break; } return $vars; }
php
{ "resource": "" }
q265
Post.makeAdminTaxonomyColumnsSortable
train
public function makeAdminTaxonomyColumnsSortable($clauses, $wp_query) { global $wpdb; // Not sorting at all? Get out. if (!array_key_exists('orderby', $wp_query->query)) { return $clauses; } if ($wp_query->query['orderby'] !== 'meta_value') { return $clauses; } if (!array_key_exists('meta_key', $wp_query->query)) { return $clauses; } // No taxonomies defined? Get out. $taxonomies = $this->getTaxonomies(); if (!Arr::iterable($taxonomies)) { return $clauses; } // Not sorting by a taxonomy? Get out. $sortable_taxonomy_key = null; foreach ($taxonomies as $taxonomy_key => $taxonomy) { $taxonomy_key = (is_int($taxonomy_key)) ? $taxonomy : $taxonomy_key; if ($wp_query->query['meta_key'] !== $taxonomy_key) { continue; } $sortable_taxonomy_key = $taxonomy_key; break; } if (!$sortable_taxonomy_key) { return $clauses; } if ($wp_query->query['meta_key'] !== $sortable_taxonomy_key) { return $clauses; } // Now we know which taxonomy the user is sorting by // but WordPress will think we're sorting by a meta_key. // Correct for this bad assumption by WordPress. $clauses['where'] = str_replace( array( "AND ({$wpdb->postmeta}.meta_key = '".$taxonomy."' )", "AND ( \n {$wpdb->postmeta}.meta_key = '".$taxonomy."'\n)" ), '', $clauses['where'] ); // This is how we find the posts $clauses['join'] .= " LEFT OUTER JOIN {$wpdb->term_relationships} ON {$wpdb->posts}.ID={$wpdb->term_relationships}.object_id LEFT OUTER JOIN {$wpdb->term_taxonomy} USING (term_taxonomy_id) LEFT OUTER JOIN {$wpdb->terms} USING (term_id) "; $clauses['where'] .= "AND (taxonomy = '".$taxonomy."' OR taxonomy IS NULL)"; $clauses['groupby'] = "object_id"; $clauses['orderby'] = "GROUP_CONCAT({$wpdb->terms}.name ORDER BY name ASC)"; $clauses['orderby'] .= (strtoupper($wp_query->get('order')) == 'ASC') ? 'ASC' : 'DESC'; return $clauses; }
php
{ "resource": "" }
q266
Post.getHideTitleFromAdminColumns
train
public function getHideTitleFromAdminColumns() { if (in_array('title', $this->getAdminColumns())) { return false; } $supports = $this->getSupports(); if (is_array($supports) && in_array('title', $supports)) { return false; } return true; }
php
{ "resource": "" }
q267
Post.getPostType
train
public function getPostType() { $called_class_segments = explode('\\', get_called_class()); $class_name = end($called_class_segments); return (is_null($this->post_type)) ? Str::machine(Str::camelToHuman($class_name), Base::SEPARATOR) : $this->post_type; }
php
{ "resource": "" }
q268
Post.getPairs
train
public static function getPairs($args = array()) { $called_class = get_called_class(); $instance = Post\Factory::create($called_class); // Optimize the query if no args // Unfortunately, WP doesn't provide a clean way to specify which columns to select // If WP allowed that, this custom SQL wouldn't be necessary if (!Arr::iterable($args)) { global $wpdb; $sql = sprintf( "SELECT p.ID, p.post_title FROM $wpdb->posts p WHERE p.post_type = '%s' AND (p.post_status = 'publish') ORDER BY p.post_title ASC", $instance->getPostType() ); $results = $wpdb->get_results($sql); if (!Arr::iterable($results)) { return array(); } return array_combine( Collection::pluck($results, 'ID'), Collection::pluck($results, 'post_title') ); } // Custom args provided $default_args = array( 'post_type' => $instance->getPostType(), 'numberposts'=> -1, 'order' => 'ASC', 'orderby' => 'title', ); $args = (Arr::iterable($args)) ? $args : $default_args; if (!array_key_exists('post_type', $args)) { $args['post_type'] = $instance->getPostType(); } $all = get_posts($args); if (!Arr::iterable($all)) { return array(); } return array_combine( Collection::pluck($all, self::ID), Collection::pluck($all, 'post_title') ); }
php
{ "resource": "" }
q269
Post.getWhere
train
public static function getWhere($args = array(), $load_terms = true) { $instance = Post\Factory::create(get_called_class()); // Allow sorting both by core fields and custom fields // See: http://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters $default_orderby = $instance->getDefaultOrderBy(); $default_order = $instance->getDefaultOrder(); $default_args = array( 'post_type' => $instance->getPostType(), 'numberposts'=> -1, 'orderby' => $default_orderby, 'order' => $default_order, ); // Sometimes you will specify a default orderby using getDefaultOrderBy if ($default_orderby !== 'menu_order') { $fields = $instance->getFields(); if (array_key_exists($default_orderby, $fields)) { $default_args['meta_key'] = $default_orderby; // Number fields should be sorted numerically, not alphabetically // Of course, this currently requires you to use type=number to achieve numeric sorting $default_args['orderby'] = ($fields[$default_orderby]['type'] === 'number') ? 'meta_value_num' : 'meta_value'; } } // But other times, you'll just pass in orderby via $args, // e.g. if you call getBy or getWhere with the $args param if (array_key_exists('orderby', $args)) { $fields = $instance->getFields(); if (array_key_exists($args['orderby'], $fields)) { $args['meta_key'] = $args['orderby']; // Number fields should be sorted numerically, not alphabetically // Of course, this currently requires you to use type=number to achieve numeric sorting $args['orderby'] = ($fields[$args['orderby']]['type'] === 'number') ? 'meta_value_num' : 'meta_value'; } } $criteria = array_merge($default_args, $args); return Post\Factory::createMultiple(get_posts($criteria), $load_terms); }
php
{ "resource": "" }
q270
Post.getByTerm
train
public static function getByTerm($taxonomy, $terms, $field = 'slug', $args = array(), $load_terms = true) { $args = array_merge($args, array( 'tax_query'=>array( array( 'taxonomy'=>$taxonomy, 'terms'=>$terms, 'field'=>$field ) ), )); return static::getWhere($args, $load_terms); }
php
{ "resource": "" }
q271
Post.getOneByTerm
train
public static function getOneByTerm($taxonomy, $terms, $field = 'slug', $args = array(), $load_terms = true) { $args['numberposts'] = 1; $result = static::getByTerm($taxonomy, $terms, $field, $args, $load_terms); return (count($result)) ? current($result) : null; }
php
{ "resource": "" }
q272
Post.getPage
train
public static function getPage($page = 1, $args = array(), $load_terms = true) { $instance = Post\Factory::create(get_called_class()); $criteria = array( 'post_type' => $instance->getPostType(), 'orderby' => 'date', 'order' => 'DESC', 'posts_per_page' => $instance->getPostsPerPage(), 'offset' => ($page - 1) * $instance->getPostsPerPage() ); $criteria = array_merge($criteria, $args); return Post\Factory::createMultiple(get_posts($criteria), $load_terms); }
php
{ "resource": "" }
q273
Post.setTerms
train
public function setTerms($term_ids, $taxonomy = null, $append = false) { $taxonomy = ($taxonomy) ? $taxonomy : 'post_tag'; if (!is_array($this->_terms)) { $this->_terms = array(); } if (!array_key_exists($taxonomy, $this->_terms)) { $this->_terms[$taxonomy] = array(); } $this->_terms[$taxonomy] = ($append) ? array_merge($this->_terms[$taxonomy], $term_ids) : $term_ids; return $this->_terms[$taxonomy]; }
php
{ "resource": "" }
q274
Post.getTerms
train
public function getTerms($taxonomy = null) { if ($taxonomy) { return (array_key_exists($taxonomy, $this->_terms)) ? $this->_terms[$taxonomy] : array(); } return $this->_terms; }
php
{ "resource": "" }
q275
Post.hasTerm
train
public function hasTerm($term_id) { $taxonomy_terms = $this->getTerms(); if (!Arr::iterable($taxonomy_terms)) { return false; } foreach ($taxonomy_terms as $taxonomy_key => $terms) { if (!Arr::iterable($terms)) { continue; } foreach ($terms as $term) { if ((int) $term->term_id === (int) $term_id) { return true; } } } return false; }
php
{ "resource": "" }
q276
Post.getPostAttachment
train
public function getPostAttachment($size = 'full', $property = null) { $post_id = $this->get('ID'); if (!has_post_thumbnail($post_id)) { return false; } $attachment_id = get_post_thumbnail_id($post_id); $image_properties = array( 'url', 'width', 'height', 'is_resized' ); $image_array = array_combine( $image_properties, array_values(wp_get_attachment_image_src($attachment_id, $size)) ); if (in_array($property, $image_properties)) { return $image_array[$property]; } return $image_array; }
php
{ "resource": "" }
q277
Post.getRenderPublicField
train
public function getRenderPublicField($key, $field = null, $load_value = true) { $class = get_called_class(); if ($key === self::KEY_CLASS) { $attribs = array('type'=>'hidden', 'name'=>$key, 'value'=>$class); return Html::tag('input', null, $attribs); } if ($key === self::KEY_NONCE) { $attribs = array('type'=>'hidden', 'name'=>$key, 'value'=>wp_create_nonce($this->getNonceAction())); return Html::tag('input', null, $attribs); } if ($load_value) { if (!is_array($field)) { $field = self::getField($key); } if (!array_key_exists('value', $field)) { $field['value'] = $this->$key; } } return self::getRenderMetaBoxField($key, $field); }
php
{ "resource": "" }
q278
Post.getPublicFormKey
train
public function getPublicFormKey($suffix = null) { $val = sprintf('%s_public_form', $this->getPostType()); return ($suffix) ? sprintf('%s_%s', $val, $suffix) : $val; }
php
{ "resource": "" }
q279
Post.find
train
public static function find($post_id, $load_terms = true) { $instance = Post\Factory::create(get_called_class()); $instance->load($post_id, $load_terms); return $instance; }
php
{ "resource": "" }
q280
Post.getLinkURL
train
public function getLinkURL($field) { $link_attr = self::decodeLinkObject($this->get($field)); if(!is_object($link_attr)) { return $this->get($field); } if(!(strlen($link_attr->href) && strlen($link_attr->title) && strlen($link_attr->target))) { $field_attribs = $this->getField($field); if (array_key_exists('default', $field_attribs)) return $field_attribs['default']; } return $link_attr->href; }
php
{ "resource": "" }
q281
Post.linkAttribsToHTMLString
train
public function linkAttribsToHTMLString($link_attr, $body = '', $classes = '', $id = '', $styles = '') { $link_text = null; if (strlen($link_attr->title)) { $link_text = $link_attr->title; } elseif (strlen($body)) { $link_text = $body; } else { $link_text = $link_attr->href; } return Html::link( $link_attr->href, $link_text, array( 'title' => $link_attr->title, 'target' => $link_attr->target, 'class' => $classes, 'id' => $id, 'style' => $styles ) ); }
php
{ "resource": "" }
q282
Post.getLinkHTMLFromObject
train
public static function getLinkHTMLFromObject($object_string, $body = '', $classes = '', $id = '', $styles = '') { return self::linkAttribsToHTMLString( self::decodeLinkObject($object_string), $body, $classes, $id, $styles ); }
php
{ "resource": "" }
q283
Passwordless.generateToken
train
public function generateToken($save = false) { $attributes = [ 'token' => str_random(16), 'is_used' => false, 'user_id' => $this->id, 'created_at' => time() ]; $token = App::make(Token::class); $token->fill($attributes); if ($save) { $token->save(); } return $token; }
php
{ "resource": "" }
q284
QueryBuilderVisitor.enterExpression
train
public function enterExpression(Expression $expr) { $hash = spl_object_hash($expr); if ($expr instanceof Key) { if (!count($this->hashes)) { $this->qb->andWhere($this->toExpr($expr)); } else { $lastHash = end($this->hashes); $this->map[$lastHash][] = $this->toExpr($expr); } } elseif ($expr instanceof OrX) { $this->hashes[] = $hash; $this->map[$hash] = []; } elseif ($expr instanceof AndX) { $this->hashes[] = $hash; $this->map[$hash] = []; } return $expr; }
php
{ "resource": "" }
q285
QueryBuilderVisitor.leaveExpression
train
public function leaveExpression(Expression $expr) { if ($expr instanceof OrX || $expr instanceof AndX) { $hash = spl_object_hash($expr); if ($expr instanceof OrX) { $composite = $this->qb->expr()->orX(); $composite->addMultiple($this->map[$hash]); } else { $composite = $this->qb->expr()->andX(); $composite->addMultiple($this->map[$hash]); } unset($this->hashes[array_search($hash, $this->hashes)]); if (!count($this->hashes)) { $this->qb->andWhere($composite); } else { $lastHash = end($this->hashes); $this->map[$lastHash][] = $composite; } } return $expr; }
php
{ "resource": "" }
q286
QueryBuilderVisitor.shouldJoin
train
public function shouldJoin($key, $prefix = null) { $parts = explode('.', $key); if (!$prefix) { $prefix = $this->getRootAlias(); } if (!in_array($parts[0], $this->qb->getAllAliases())) { $this->qb->leftJoin($prefix.'.'.$parts[0], $parts[0]); } // If the key consists of multiple . parts, we also need to add joins for the other parts if (count($parts) > 2) { $prefix = array_shift($parts); $leftover = implode('.', $parts); $key = $this->shouldJoin($leftover, $prefix); } return $key; }
php
{ "resource": "" }
q287
Rsa.validateKey
train
private function validateKey($key) { $details = openssl_pkey_get_details($key); if (!isset($details['key']) || $details['type'] !== OPENSSL_KEYTYPE_RSA) { throw new \InvalidArgumentException('This key is not compatible with RSA signatures'); } }
php
{ "resource": "" }
q288
DownloadsBlockService.downloadMediaAction
train
public function downloadMediaAction($filename) { $media = $this->mediaManager->getRepository()->findOneByReference($filename); $provider = $this->container->get('opifer.media.provider.pool')->getProvider($media->getProvider()); $mediaUrl = $provider->getUrl($media); $fileSystem = $provider->getFileSystem(); $file = $fileSystem->read($media->getReference()); $response = new Response(); $response->headers->set('Content-type', $media->getContentType()); $response->headers->set('Content-Disposition', sprintf('attachment; filename="%s"', basename($mediaUrl))); $response->setContent($file); return $response; }
php
{ "resource": "" }
q289
DisplayLogicType.getDisplayLogicPrototypes
train
protected function getDisplayLogicPrototypes(BlockInterface $block) { $collection = new PrototypeCollection([ new OrXPrototype(), new AndXPrototype(), new EventPrototype('click_event', 'Click Event', 'event.type.click'), new TextPrototype('dom_node_id', 'DOM Node Id', 'node.id') ]); $owner = $block->getOwner(); if ($owner) { // Avoid trying to add display logic for blocks when the current block has no owner (e.g. shared blocks) $blockChoices = []; foreach ($owner->getBlocks() as $member) { try { $properties = $member->getProperties(); if ($member instanceof ChoiceFieldBlock) { if (empty($member->getName())) { continue; } if (!isset($properties['options'])) { continue; } $choices = []; foreach ($properties['options'] as $option) { if (empty($option['key'])) { continue; } $choices[] = new Choice($option['key'], $option['value']); } $collection->add(new SelectPrototype($member->getName(), $properties['label'], $member->getName(), $choices)); } elseif ($member instanceof NumberFieldBlock || $member instanceof RangeFieldBlock) { if (empty($member->getName())) { continue; } $collection->add(new NumberPrototype($member->getName(), $properties['label'], $member->getName())); } if (!empty($member->getName())) { $blockChoices[] = new Choice($member->getName(), $member->getName()); } } catch (\Exception $e) { // Avoid throwing exceptions here for now, since e.g. duplicate namesthis will cause all blocks to be uneditable. } } $collection->add(new SelectPrototype('block_name', 'Block Name', 'block.name', $blockChoices)); } return $collection->all(); }
php
{ "resource": "" }
q290
AuthenticationSuccessHandler.onAuthenticationSuccess
train
public function onAuthenticationSuccess(Request $request, TokenInterface $token) { if ($user = $token->getUser()) { if (!$user->getFirstName() || !$user->getLastName()) { return new RedirectResponse($this->router->generate('opifer_cms_user_profile')); } } return parent::onAuthenticationSuccess($request, $token); }
php
{ "resource": "" }
q291
Deserializer.fromBase64URL
train
public function fromBase64URL($data) { if ($remainder = strlen($data) % 4) { $data .= str_repeat('=', 4 - $remainder); } return base64_decode(strtr($data, '-_', '+/')); }
php
{ "resource": "" }
q292
MailPlusProvider.synchronise
train
public function synchronise(Subscription $subscription) { try { $contact = [ 'update' => true, 'purge' => false, 'contact' => [ 'externalId' => $subscription->getId(), 'properties' => [ 'email' => $subscription->getEmail(), ], ], ]; $response = $this->post('contact', $contact); if ($response->getStatusCode() == '204') { //Contact added successfully status code $this->subscriptionManager->updateStatus($subscription, Subscription::STATUS_SYNCED); return true; } else { $this->subscriptionManager->updateStatus($subscription, Subscription::STATUS_FAILED); return false; } } catch (\Exception $e) { $this->subscriptionManager->updateStatus($subscription, Subscription::STATUS_FAILED); return true; } }
php
{ "resource": "" }
q293
Token.getHeader
train
public function getHeader($name, $default = null) { if ($this->hasHeader($name)) { return $this->getHeaderValue($name); } if ($default === null) { throw new \OutOfBoundsException('Requested header is not configured'); } return $default; }
php
{ "resource": "" }
q294
Token.getHeaderValue
train
private function getHeaderValue($name) { $header = $this->headers[$name]; if ($header instanceof Claim) { return $header->getValue(); } return $header; }
php
{ "resource": "" }
q295
Token.getClaim
train
public function getClaim($name, $default = null) { if ($this->hasClaim($name)) { return $this->claims[$name]->getValue(); } if ($default === null) { throw new \OutOfBoundsException('Requested claim is not configured'); } return $default; }
php
{ "resource": "" }
q296
Token.verify
train
public function verify(Signer $signer, $key) { if ($this->signature === null) { throw new \BadMethodCallException('This token is not signed'); } if ($this->headers['alg'] !== $signer->getAlgorithmId()) { return false; } return $this->signature->verify($signer, $this->getPayload(), $key); }
php
{ "resource": "" }
q297
Token.validate
train
public function validate(ValidationData $data) { foreach ($this->getValidatableClaims() as $claim) { if (!$claim->validate($data)) { return false; } } return true; }
php
{ "resource": "" }
q298
Token.getValidatableClaims
train
private function getValidatableClaims() { $claims = array(); foreach ($this->claims as $claim) { if ($claim instanceof Validatable) { $cliams[] = $claim; } } return $claims; }
php
{ "resource": "" }
q299
Issue.create
train
public function create($projectKey, $issueTypeName) { $fieldsMetadata = $this->getCreateMetadataFields($projectKey, $issueTypeName); $fluentIssueCreate = new FluentIssueCreate($this->client, $fieldsMetadata); return $fluentIssueCreate->field(Field::PROJECT, $projectKey) ->field(Field::ISSUE_TYPE, $issueTypeName); }
php
{ "resource": "" }