_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q0
BreadcrumbCollection.addOne
train
public function addOne($title, $url, array $data = []) { return $this->addBreadcrumb( BreadcrumbItem::make($title, $url, $data) ); }
php
{ "resource": "" }
q1
BreadcrumbCollection.order
train
private function order() { $count = $this->count(); $this->map(function (BreadcrumbItem $crumb, $key) use ($count) { $crumb->resetPosition(); if ($key === 0) $crumb->setFirst(); if ($key === ($count - 1)) $crumb->setLast(); return $crumb; }); return $this; }
php
{ "resource": "" }
q2
ParsedownExtraLaravel.parse
train
public function parse($text = '', $options = []) { // Extend default options $options = array_merge([ 'config' => [], 'purifier' => true ], $options); // Parsedown Extra $markdown = parent::text($text); // HTML Purifier if (config('parsedownextra.purifier.enabled') && $options['purifier']) { $purifier = app(HTMLPurifierLaravel::class); // Filter HTML $markdown = $purifier->purify($markdown, $options['config']); } return $markdown; }
php
{ "resource": "" }
q3
Query.makeQuery
train
private function makeQuery($pageNumber = 1) { $params = array( 'page_size' => $this->pageSize, 'page' => $pageNumber ); $params = array_merge($params, $this->filter); $params = array_merge($params, $this->order); $response = $this->api->get($this->typeClass->url(), $params); $this->countCached = $response->meta->total_count; return $response; }
php
{ "resource": "" }
q4
Query.count
train
public function count() { if ($this->countCached === null) { $pageSize = $this->pageSize; $this->pageSize = 1; $this->makeQuery(1); $this->pageSize = $pageSize; } return $this->countCached; }
php
{ "resource": "" }
q5
Query.makeFilter
train
public function makeFilter( $filterType = null, $filterField = null, $filterValue = null ) { if ($filterType === null && $filterField === null && $filterValue === null) $this->filter = array(); else $this->filter = array( 'filter_type' => $filterType, 'filter_field' => $filterField, 'filter_value' => $filterValue ); return $this; }
php
{ "resource": "" }
q6
Query.getPage
train
public function getPage($pageNumber) { $response = $this->makeQuery($pageNumber); $className = $this->typeClass->objectClass; $objects = array(); if (!isset($response->data) || !$response->data) return array(); foreach ($response->data as $object) { $objects[] = new $className($this->api, $this->typeClass, $object); } return $objects; }
php
{ "resource": "" }
q7
SessionManager.initSession
train
private function initSession() { $transport = $this->transportRegistry->getTransport($this->profile->get('transport', 'name')); $repository = $transport->getRepository($this->profile->get('transport')); $credentials = new SimpleCredentials( $this->profile->get('phpcr', 'username'), $this->profile->get('phpcr', 'password') ); $session = $repository->login($credentials, $this->profile->get('phpcr', 'workspace')); // if you are wondering wtf here -- we wrap the PhpcrSession if (!$this->session) { $this->session = new PhpcrSession($session); } else { $this->session->setPhpcrSession($session); } }
php
{ "resource": "" }
q8
SessionManager.changeWorkspace
train
public function changeWorkspace($workspaceName) { $this->init(); $this->session->logout(); $this->profile->set('phpcr', 'workspace', $workspaceName); $this->initSession($this->profile); }
php
{ "resource": "" }
q9
TomlFileLoader.loadFile
train
protected function loadFile($file) { if (!stream_is_local($file)) { throw new InvalidArgumentException(sprintf('This is not a local file "%s".', $file)); } if (!file_exists($file)) { throw new InvalidArgumentException(sprintf('The service file "%s" is not valid.', $file)); } return Toml::Parse($file); }
php
{ "resource": "" }
q10
ColorpaletteHelper.get_palette
train
public static function get_palette($numColors = 50, $type='hsv') { //overwriting with the palette from the calendar settings $s = CalendarConfig::subpackage_settings('colors'); $arr = $s['basepalette']; return $arr; if ($type == 'hsv') { $s = 1; $v = 1; $arr = array(); for ($i = 0; $i <= $numColors; $i++) { $c = new Color(); $h = $i / $numColors; $hex = $c->fromHSV($h, $s, $v)->toHexString(); $arr[$hex] = $hex; } return $arr; } elseif ($type == 'websafe') { //websafe colors $cs = array('00', '33', '66', '99', 'CC', 'FF'); $arr = array(); for ($i = 0; $i < 6; $i++) { for ($j = 0; $j < 6; $j++) { for ($k = 0; $k < 6; $k++) { $c = $cs[$i] . $cs[$j] . $cs[$k]; $arr["$c"] = "#$c"; } } } return $arr; } }
php
{ "resource": "" }
q11
Child.sendSignal
train
protected function sendSignal($signalNumber) { if (! $this->context->isRunning || ! $this->context->processId) { return false; } $result = $this->control->signal()->send($signalNumber, $this->context->processId); if (in_array($signalNumber, [SIGTERM, SIGKILL])) { $this->context->isRunning = false; $this->context->processId = null; } return $result; }
php
{ "resource": "" }
q12
Child.setHandlerAlarm
train
protected function setHandlerAlarm() { $handler = new SignalAlarm($this->control, $this->action, $this->context); $this->control->signal()->setHandler('alarm', $handler); $this->control->signal()->alarm($this->context->timeout); }
php
{ "resource": "" }
q13
Child.silentRunActionTrigger
train
protected function silentRunActionTrigger($event) { try { $this->action->trigger($event, $this->control, $this->context); } catch (Exception $exception) { // Pokémon Exception Handling } }
php
{ "resource": "" }
q14
Child.run
train
protected function run() { $this->silentRunActionTrigger(Action::EVENT_START); try { $event = $this->action->execute($this->control, $this->context) ?: Action::EVENT_SUCCESS; $this->context->exitCode = 0; } catch (ErrorException $errorException) { $event = Action::EVENT_ERROR; $this->context->exception = $errorException; $this->context->exitCode = 2; } catch (Exception $exception) { $event = Action::EVENT_FAILURE; $this->context->exception = $exception; $this->context->exitCode = 1; } $this->context->finishTime = time(); $this->silentRunActionTrigger($event); $this->silentRunActionTrigger(Action::EVENT_FINISH); }
php
{ "resource": "" }
q15
UpdateParser.doParse
train
private function doParse($sql2) { $this->implicitSelectorName = null; $this->sql2 = $sql2; $source = null; $constraint = null; $updates = []; $applies = []; while ($this->scanner->lookupNextToken() !== '') { switch (strtoupper($this->scanner->lookupNextToken())) { case 'UPDATE': $this->scanner->expectToken('UPDATE'); $source = $this->parseSource(); break; case 'SET': $this->scanner->expectToken('SET'); $updates = $this->parseUpdates(); break; case 'APPLY': $this->scanner->expectToken('APPLY'); $applies = $this->parseApply(); break; case 'WHERE': $this->scanner->expectToken('WHERE'); $constraint = $this->parseConstraint(); break; default: throw new InvalidQueryException('Expected end of query, got "'.$this->scanner->lookupNextToken().'" in '.$this->sql2); } } if (!$source instanceof SourceInterface) { throw new InvalidQueryException('Invalid query, source could not be determined: '.$sql2); } $query = $this->factory->createQuery($source, $constraint); $res = new \ArrayObject([$query, $updates, $constraint, $applies]); return $res; }
php
{ "resource": "" }
q16
AliasSubscriber.handleAlias
train
public function handleAlias(CommandPreRunEvent $event) { $input = $event->getInput(); $commandName = $input->getFirstArgument(); $aliasConfig = $this->configManager->getConfig('alias'); if (!isset($aliasConfig[$commandName])) { return; } $command = $aliasConfig[$commandName]; $command = $command .= substr($input->getRawCommand(), strlen($commandName)); $newInput = new StringInput($command); $event->setInput($newInput); return $command; }
php
{ "resource": "" }
q17
Comment.getStateLabel
train
public function getStateLabel() { $list = self::getStateList(); return isset($list[$this->getState()]) ? $list[$this->getState()] : null; }
php
{ "resource": "" }
q18
GridHelper.tag
train
public function tag($tag, $content, array $attributes = []) { return $this->htmlBuilder->tag($tag, $content, $attributes); }
php
{ "resource": "" }
q19
Context.normalize
train
protected function normalize($value) { if ($value instanceof Exception) { $value = [ 'class' => get_class($value), 'message' => $value->getMessage(), 'code' => $value->getCode(), 'file' => $value->getFile(), 'line' => $value->getLine(), ]; } return $value; }
php
{ "resource": "" }
q20
ShellApplication.configureFormatter
train
private function configureFormatter(OutputFormatter $formatter) { $style = new OutputFormatterStyle('yellow', null, ['bold']); $formatter->setStyle('pathbold', $style); $style = new OutputFormatterStyle('green'); $formatter->setStyle('localname', $style); $style = new OutputFormatterStyle(null, null, ['bold']); $formatter->setStyle('node', $style); $style = new OutputFormatterStyle('blue', null, ['bold']); $formatter->setStyle('templatenode', $style); $style = new OutputFormatterStyle('blue', null, []); $formatter->setStyle('templateproperty', $style); $style = new OutputFormatterStyle(null, null, []); $formatter->setStyle('property', $style); $style = new OutputFormatterStyle('magenta', null, ['bold']); $formatter->setStyle('node-type', $style); $style = new OutputFormatterStyle('magenta', null, []); $formatter->setStyle('property-type', $style); $style = new OutputFormatterStyle(null, null, []); $formatter->setStyle('property-value', $style); $style = new OutputFormatterStyle(null, 'red', []); $formatter->setStyle('exception', $style); }
php
{ "resource": "" }
q21
ShellApplication.add
train
public function add(Command $command) { if ($command instanceof ContainerAwareInterface) { $command->setContainer($this->container); } if ($command instanceof BasePhpcrCommand) { if ($this->showUnsupported || $command->isSupported()) { parent::add($command); } } else { parent::add($command); } }
php
{ "resource": "" }
q22
KickStarterService.prepareSettings
train
protected function prepareSettings( $mass, $makeResources, $makeMountPoint, $extensionKey, $author, $title, $description, $useVhs, $useFluidcontentCore, $pages, $content, $backend, $controllers ) { return [ $mass, (boolean) $makeResources, (boolean) $makeMountPoint, false === is_null($extensionKey) ? $extensionKey : self::DEFAULT_EXTENSION_KEY, $this->getAuthor($author), false === empty($title) ? $title : self::DEFAULT_EXTENSION_TITLE, false === empty($description) ? $description : self::DEFAULT_EXTENSION_DESCRIPTION, (boolean) $useVhs, (boolean) $useFluidcontentCore, (boolean) $pages, (boolean) $content, (boolean) $backend, (boolean) $controllers ]; }
php
{ "resource": "" }
q23
KickStarterService.gatherInformation
train
private function gatherInformation() { /** @var \TYPO3\CMS\Extbase\Object\ObjectManagerInterface $objectManager */ $objectManager = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(ObjectManager::class); /** @var ListUtility $service */ $service = $objectManager->get('TYPO3\\CMS\\Extensionmanager\\Utility\\ListUtility'); $extensionInformation = $service->getAvailableExtensions(); foreach ($extensionInformation as $extensionKey => $info) { if (true === array_key_exists($extensionKey, $GLOBALS['TYPO3_LOADED_EXT'])) { $extensionInformation[$extensionKey]['installed'] = 1; } else { $extensionInformation[$extensionKey]['installed'] = 0; } } return $extensionInformation; }
php
{ "resource": "" }
q24
Color.fromHexString
train
public static function fromHexString($color) { $color = rtrim($color, '#'); preg_match_all('([0-9a-f][0-9a-f])', $color, $rgb); $c = new self(); list($c->r, $c->g, $c->b) = array_map('hexdec', $rgb[0]); return $c; }
php
{ "resource": "" }
q25
Color.fromRGBString
train
public static function fromRGBString($color) { $color = rtrim($color, "rgb (\t)"); $rgb = preg_split('\s+,\s+', $color); $c = new self(); list($c->r, $c->g, $c->b) = array_map('intval', $rgb); return $c; }
php
{ "resource": "" }
q26
Color.toHexString
train
public function toHexString() { return '#' . $this->decToHex($this->r) . $this->decToHex($this->g) . $this->decToHex($this->b); }
php
{ "resource": "" }
q27
Color.fromHSL
train
public static function fromHSL($h, $s, $l) { // theta plus 360 degrees $h -= floor($h); $c = new self(); if ($s == 0) { $c->r = $c->g = $c->b = $l * 255; return $c; } $chroma = floatval(1 - abs(2*$l - 1)) * $s; // Divide $h by 60 degrees i.e by (60 / 360) $h_ = $h * 6; // intermediate $k = intval($h_); $h_mod2 = $k % 2 + $h_ - floor($h_); $x = $chroma * abs(1 - abs($h_mod2 - 1)); $r = $g = $b = 0.0; switch ($k) { case 0: case 6: $r = $chroma; $g = $x; break; case 1: $r = $x; $g = $chroma; break; case 2: $g = $chroma; $b = $x; break; case 3: $g = $x; $b = $chroma; break; case 4: $r = $x; $b = $chroma; break; case 5: $r = $chroma; $b = $x; break; } $m = $l - 0.5 * $chroma; $c->r = (($r + $m) * 255); $c->g = (($g + $m) * 255); $c->b = (($b + $m) * 255); return $c; }
php
{ "resource": "" }
q28
Color.fromHSV
train
public static function fromHSV($h, $s, $v) { $h -= floor($h); $c = new self(); if ($s == 0) { $c->r = $c->g = $c->b = $v * 255; return $c; } $chroma = $v * $s; // Divide $h by 60 degrees i.e by (60 / 360) $h_ = $h * 6; // intermediate $k = intval($h_); $h_mod2 = $k % 2 + $h_ - floor($h_); $x = $chroma * abs(1 - abs($h_mod2 - 1)); $r = $g = $b = 0.0; switch ($k) { case 0: case 6: $r = $chroma; $g = $x; break; case 1: $r = $x; $g = $chroma; break; case 2: $g = $chroma; $b = $x; break; case 3: $g = $x; $b = $chroma; break; case 4: $r = $x; $b = $chroma; break; case 5: $r = $chroma; $b = $x; break; } $m = $v - $chroma; $c->r = (($r + $m) * 255); $c->g = (($g + $m) * 255); $c->b = (($b + $m) * 255); return $c; }
php
{ "resource": "" }
q29
Color.darken
train
public function darken($fraction=0.1) { $hsl = $this->toHSL(); $l = $hsl[2]; // so that 100% darker = black $dl = -$l * $fraction; return $this->changeHSL(0, 0, $dl); }
php
{ "resource": "" }
q30
Color.lighten
train
public function lighten($fraction=0.1) { $hsl = $this->toHSL(); $l = $hsl[2]; // so that 100% lighter = white $dl = (1 - $l) * $fraction; return $this->changeHSL(0, 0, $dl); }
php
{ "resource": "" }
q31
Color.changeHSL
train
public function changeHSL($dh=0, $ds=0, $dl=0) { list($h, $s, $l) = $this->toHSL(); $h += $dh; $s += $ds; $l += $dl; $c = self::fromHSL($h, $s, $l); $this->r = $c->r; $this->g = $c->g; $this->b = $c->b; return $this; }
php
{ "resource": "" }
q32
Color.toHSL
train
public function toHSL() { // r, g, b as fractions of 1 $r = $this->r / 255.0; $g = $this->g / 255.0; $b = $this->b / 255.0; // most prominent primary color $max = max($r, $g, $b); // least prominent primary color $min = min($r, $g, $b); // maximum delta $dmax = $max - $min; // intensity = (r + g + b) / 3 // lightness = (r + g + b - (non-extreme color)) / 2 $l = ($min + $max) / 2; if ($dmax == 0) { // This means R=G=B, so: $h = 0; $s = 0; } else { // remember ligtness = (min+max) / 2 $s = ($l < 0.5) ? $dmax / ($l * 2) : $dmax / ((1 - $l) * 2); $dr = ((($max - $r) / 6) + ($dmax / 2)) / $dmax; $dg = ((($max - $g) / 6) + ($dmax / 2)) / $dmax; $db = ((($max - $b) / 6) + ($dmax / 2)) / $dmax; if ($r == $max) { $h = (0.0 / 3) + $db - $dg; } elseif ($g == $max) { $h = (1.0 / 3) + $dr - $db; } elseif ($b == $max) { $h = (2.0 / 3) + $dg - $dr; } // the case of less than 0 radians if ($h < 0) { $h += 1; } if ($h > 1) { $h -= 1; } } return array($h, $s, $l); }
php
{ "resource": "" }
q33
Color.toHSV
train
public function toHSV() { // r, g, b as fractions of 1 $r = $this->r / 255.0; $g = $this->g / 255.0; $b = $this->b / 255.0; // most prominent primary color $max = max($r, $g, $b); // least prominent primary color $min = min($r, $g, $b); // maximum delta $dmax = $max - $min; // value is just the fraction of // the most prominent primary color $v = $max; if ($dmax == 0) { // This means R=G=B, so: $h = 0; $s = 0; } else { $s = $dmax / $max; $dr = ((($max - $r) / 6) + ($dmax / 2)) / $dmax; $dg = ((($max - $g) / 6) + ($dmax / 2)) / $dmax; $db = ((($max - $b) / 6) + ($dmax / 2)) / $dmax; if ($r == $max) { $h = (0.0 / 3) + $db - $dg; } elseif ($g == $max) { $h = (1.0 / 3) + $dr - $db; } elseif ($b == $max) { $h = (2.0 / 3) + $dg - $dr; } // the case of less than 0 radians if ($h < 0) { $h += 1; } if ($h > 1) { $h -= 1; } } return array($h, $s, $v); }
php
{ "resource": "" }
q34
PhpcrSession.getAbsTargetPath
train
public function getAbsTargetPath($srcPath, $targetPath) { $targetPath = $this->getAbsPath($targetPath); try { $this->getNode($targetPath); } catch (PathNotFoundException $e) { return $targetPath; } $basename = basename($this->getAbsPath($srcPath)); return $this->getAbsPath(sprintf('%s/%s', $targetPath, $basename)); }
php
{ "resource": "" }
q35
PhpcrSession.getNodeByPathOrIdentifier
train
public function getNodeByPathOrIdentifier($pathOrId) { if (true === UUIDHelper::isUUID($pathOrId)) { return $this->getNodeByIdentifier($pathOrId); } $pathOrId = $this->getAbsPath($pathOrId); return $this->getNode($pathOrId); }
php
{ "resource": "" }
q36
TokenStream.normalizeTokens
train
private function normalizeTokens(array $tokens) { $nTokens = array(); for ($i=0,$c=count($tokens); $i<$c; $i++) { $token = $tokens[$i]; if (is_string($token)) { $nTokens[] = new LiteralToken($token, end($nTokens)->getEndLine()); continue; } switch ($token[0]) { case T_WHITESPACE: $lines = explode("\n", $token[1]); for ($j=0,$k=count($lines); $j<$k; $j++) { $line = $lines[$j].($j+1 === $k ? '' : "\n"); if ($j+1 === $k && '' === $line) { break; } $nTokens[] = new PhpToken(array(T_WHITESPACE, $line, $token[2] + $j)); } break; default: // remove any trailing whitespace of the token if (preg_match('/^(.*?)(\s+)$/', $token[1], $match)) { $nTokens[] = new PhpToken(array($token[0], $match[1], $token[2])); // if the next token is whitespace, change it if (isset($tokens[$i+1]) && !is_string($tokens[$i+1]) && T_WHITESPACE === $tokens[$i+1][0]) { $tokens[$i+1][1] = $match[2].$tokens[$i+1][1]; $tokens[$i+1][2] = $token[2]; } else { $nTokens[] = new PhpToken(array(T_WHITESPACE, $match[2], $token[2])); } } else { $nTokens[] = new PhpToken($token); } } } return $nTokens; }
php
{ "resource": "" }
q37
TokenStream.insertBefore
train
public function insertBefore(AbstractToken $token, $type, $value = null) { $this->insertAllTokensBefore($token, array(array($type, $value, $token->getLine()))); }
php
{ "resource": "" }
q38
Api.httpRequest
train
private function httpRequest( $url, $request, $data = array(), $sendHeaders = array(), $timeout = 10 ) { $streamParams = array( 'http' => array( 'method' => $request, 'ignore_errors' => true, 'timeout' => $timeout, 'header' => "User-Agent: " . $this->userAgent . "\r\n" ) ); foreach ($sendHeaders as $header => $value) { $streamParams['http']['header'] .= $header . ': ' . $value . "\r\n"; } foreach ($this->extraHeaders as $header => $value) { $streamParams['http']['header'] .= $header . ': ' . $value . "\r\n"; } if (is_array($data)) { if (in_array($request, array('POST', 'PUT'))) $streamParams['http']['content'] = http_build_query($data); elseif ($data && count($data)) $url .= '?' . http_build_query($data); } elseif ($data !== null) { if (in_array($request, array('POST', 'PUT'))) $streamParams['http']['content'] = $data; } $streamParams['cURL'] = $streamParams['http']; $context = stream_context_create($streamParams); $fp = @fopen($url, 'rb', false, $context); if (!$fp) $content = false; else $content = stream_get_contents($fp); $status = null; $statusCode = null; $headers = array(); if ($content !== false) { $metadata = stream_get_meta_data($fp); if (isset($metadata['wrapper_data']['headers'])) $headerMetadata = $metadata['wrapper_data']['headers']; else $headerMetadata = $metadata['wrapper_data']; foreach ($headerMetadata as $row) { if (preg_match('/^HTTP\/1\.[01] (\d{3})\s*(.*)/', $row, $m)) { $statusCode = $m[1]; $status = $m[2]; } elseif (preg_match('/^([^:]+):\s*(.*)$/', $row, $m)) { $headers[mb_strtolower($m[1])] = $m[2]; } } } return (object) array( 'ok' => $statusCode == 200, 'statusCode' => $statusCode, 'status' => $status, 'content' => $content, 'headers' => $headers ); }
php
{ "resource": "" }
q39
Api.get
train
public function get($objectUrl, $data = null, $expectContentType = null) { $url = $this->apiBase . '/' . $objectUrl; return $this->checkApiResponse( $this->httpRequest($url, 'GET', $data, $this->authHeader()), $expectContentType ); }
php
{ "resource": "" }
q40
Api.put
train
public function put($objectUrl, $data) { $url = $this->apiBase . '/' . $objectUrl; return $this->checkApiResponse( $this->httpRequest( $url, 'PUT', json_encode($data), array_merge( $this->authHeader(), array('Content-type' => 'application/json') ) ) ); }
php
{ "resource": "" }
q41
Api.delete
train
public function delete($objectUrl) { $url = $this->apiBase . '/' . $objectUrl; return $this->checkApiResponse( $this->httpRequest( $url, 'DELETE', null, $this->authHeader() ) ); }
php
{ "resource": "" }
q42
pakeGlobToRegex.glob_to_regex
train
public static function glob_to_regex($glob) { $first_byte = true; $escaping = false; $in_curlies = 0; $regex = ''; for ($i = 0; $i < strlen($glob); $i++) { $car = $glob[$i]; if ($first_byte) { if (self::$strict_leading_dot && $car != '.') { $regex .= '(?=[^\.])'; } $first_byte = false; } if ($car == '/') { $first_byte = true; } if ($car == '.' || $car == '(' || $car == ')' || $car == '|' || $car == '+' || $car == '^' || $car == '$') { $regex .= "\\$car"; } else if ($car == '*') { $regex .= ($escaping ? "\\*" : (self::$strict_wildcard_slash ? "[^/]*" : ".*")); } else if ($car == '?') { $regex .= ($escaping ? "\\?" : (self::$strict_wildcard_slash ? "[^/]" : ".")); } else if ($car == '{') { $regex .= ($escaping ? "\\{" : "("); if (!$escaping) ++$in_curlies; } else if ($car == '}' && $in_curlies) { $regex .= ($escaping ? "}" : ")"); if (!$escaping) --$in_curlies; } else if ($car == ',' && $in_curlies) { $regex .= ($escaping ? "," : "|"); } else if ($car == "\\") { if ($escaping) { $regex .= "\\\\"; $escaping = false; } else { $escaping = true; } continue; } else { $regex .= $car; $escaping = false; } $escaping = false; } return "#^$regex$#"; }
php
{ "resource": "" }
q43
Builder.call
train
public function call($name, array $params = []) { $this->checkName($name); array_unshift($params, $this); call_user_func_array($this->callbacks[$name], $params); return $this; }
php
{ "resource": "" }
q44
Builder.push
train
public function push($title, $url = null, array $data = []) { $this->breadcrumbs->addOne($title, $url, $data); return $this; }
php
{ "resource": "" }
q45
Signal.handle
train
protected function handle($signal, $handler, $placement) { declare (ticks = 1); $signalNumber = $this->translateSignal($signal); if (is_int($handler) && in_array($handler, [SIG_IGN, SIG_DFL])) { unset($this->handlers[$signalNumber]); $this->registerHandler($signalNumber, $handler); return; } $this->placeHandler($signalNumber, $handler, $placement); }
php
{ "resource": "" }
q46
Signal.placeHandler
train
protected function placeHandler($signalNumber, callable $handler, $placement) { if (! isset($this->handlers[$signalNumber])) { $this->handlers[$signalNumber] = []; $this->registerHandler($signalNumber, $this); } switch ($placement) { case 'set': $this->handlers[$signalNumber] = [$handler]; break; case 'append': array_push($this->handlers[$signalNumber], $handler); break; case 'prepend': array_unshift($this->handlers[$signalNumber], $handler); break; } }
php
{ "resource": "" }
q47
Signal.getHandlers
train
public function getHandlers($signal) { $signalNumber = $this->translateSignal($signal); $handlers = []; if (isset($this->handlers[$signalNumber])) { $handlers = $this->handlers[$signalNumber]; } return $handlers; }
php
{ "resource": "" }
q48
Signal.send
train
public function send($signal, $processId = null) { if (null === $processId) { $processId = posix_getpid(); } return posix_kill($processId, $this->translateSignal($signal)); }
php
{ "resource": "" }
q49
Signal.translateSignal
train
protected function translateSignal($signal) { if (isset($this->signals[$signal])) { $signal = $this->signals[$signal]; } elseif (defined($signal)) { $signal = constant($signal); } if (! is_int($signal)) { throw new InvalidArgumentException('The given value is not a valid signal'); } return $signal; }
php
{ "resource": "" }
q50
SessionManager.createHandlerByConfig
train
public function createHandlerByConfig(): \SessionHandlerInterface { if (!isset($this->getConfig()['driver'])) { throw new \InvalidArgumentException('Session driver required'); } $handler = $this->getHandler($this->getConfig()['driver']); $handler instanceof LifetimeInterface && $handler->setLifetime($this->getConfig()['lifetime']); return $handler; }
php
{ "resource": "" }
q51
SessionManager.getHandler
train
public function getHandler(string $name): \SessionHandlerInterface { $name = strtolower($name); $this->isValidate($name); return App::getBean($this->handlers[$name]); }
php
{ "resource": "" }
q52
Application.buildContainer
train
private function buildContainer(InputInterface $input, OutputInterface $output) { $nonContainerCommands = ['blocks-install', 'blocks-update', 'blocks-dumpautoload', 'help']; if (in_array($input->getFirstArgument(), $nonContainerCommands)) { return; } $this->container = new ContainerBuilder($this, $input, $output); $this->container->compile(); }
php
{ "resource": "" }
q53
Application.find
train
public function find($name) { try { return parent::find($name); } catch (\InvalidArgumentException $e) { $this->shortcut = true; return parent::find('run'); } }
php
{ "resource": "" }
q54
WatchTask.getJobs
train
private function getJobs() { if ($this->hasParameter('profile')) { $this->fetchJobs($this->getParameter('profile')); return; } $this->buildJobs([$this->getParameter('job')]); }
php
{ "resource": "" }
q55
Event.setEnd
train
public function setEnd($end, $write=true) { $e = $this; if ($e->TimeFrameType == 'DateTime') { $e->EndDateTime = $end; } elseif ($e->TimeFrameType == 'Duration') { $duration = $this->calcDurationBasedOnEndDateTime($end); if ($duration) { $e->Duration = $duration; } else { //if duration is more than 1 day, make the time frame "DateTime" $e->TimeFrameType = 'DateTime'; $e->EndDateTime = $end; } } if ($write) { $e->write(); } }
php
{ "resource": "" }
q56
Event.calcEndDateTimeBasedOnDuration
train
public function calcEndDateTimeBasedOnDuration() { $duration = $this->Duration; $secs = (substr($duration, 0, 2) * 3600) + (substr($duration, 3, 2) * 60); $startDate = strtotime($this->StartDateTime); $endDate = $startDate + $secs; $formatDate = date("Y-m-d H:i:s", $endDate); return $formatDate; }
php
{ "resource": "" }
q57
Event.calcDurationBasedOnEndDateTime
train
public function calcDurationBasedOnEndDateTime($end) { $startDate = strtotime($this->StartDateTime); $endDate = strtotime($end); $duration = $endDate - $startDate; $secsInDay = 60 * 60 * 24; if ($duration > $secsInDay) { //Duration cannot be more than 24h return false; } //info on this calculation here: //http://stackoverflow.com/questions/3856293/how-to-convert-seconds-to-time-format $formatDate = gmdate("H:i", $duration); return $formatDate; }
php
{ "resource": "" }
q58
Event.isAllDay
train
public function isAllDay() { if ($this->AllDay) { return true; } $secsInDay = 60 * 60 * 24; $startTime = strtotime($this->StartDateTime); $endTime = strtotime($this->EndDateTime); if (($endTime - $startTime) > $secsInDay) { return true; } }
php
{ "resource": "" }
q59
Event.getFrontEndFields
train
public function getFrontEndFields($params = null) { //parent::getFrontEndFields($params); $timeFrameHeaderText = 'Time Frame'; if (!CalendarConfig::subpackage_setting('events', 'force_end')) { $timeFrameHeaderText = 'End Date / Time (optional)'; } $fields = FieldList::create( TextField::create('Title') ->setAttribute('placeholder', 'Enter a title'), CheckboxField::create('AllDay', 'All-day'), $startDateTime = DatetimeField::create('StartDateTime', 'Start'), //NoEnd field - will only be shown if end dates are not enforced - see below CheckboxField::create('NoEnd', 'Open End'), HeaderField::create('TimeFrameHeader', $timeFrameHeaderText, 5), //LiteralField::create('TimeFrameText','<em class="TimeFrameText">Choose the type of time frame you\'d like to enter</em>'), SelectionGroup::create('TimeFrameType', array( "Duration//Duration" => TimeField::create('Duration', '')->setRightTitle('up to 24h') ->setAttribute('placeholder', 'Enter duration'), "DateTime//Date/Time" => $endDateTime = DateTimeField::create('EndDateTime', '') ) ), LiteralField::create('Clear', '<div class="clear"></div>') ); //Date field settings $timeExpl = 'Time, e.g. 11:15am or 15:30'; //$startDateTime->setConfig('datavalueformat', 'YYYY-MM-dd HH:mm'); //$endDateTime->setConfig('datavalueformat', 'YYYY-MM-dd HH:mm'); $startDateTime->getDateField() ->setConfig('showcalendar', 1) //->setRightTitle('Date') ->setAttribute('placeholder', 'Enter date') ->setAttribute('readonly', 'true'); //we only want input through the datepicker $startDateTime->getTimeField() //->setRightTitle($timeExpl) //->setConfig('timeformat', 'h:mm') //this is the default, that seems to be giving some troubles: h:mm:ss a ->setConfig('timeformat', 'HH:mm') //24h format ->setAttribute('placeholder', 'Enter time'); $endDateTime->getDateField() ->setConfig('showcalendar', 1) //->setRightTitle('Date') ->setAttribute('placeholder', 'Enter date') ->setAttribute('readonly', 'true'); //we only want input through the datepicker $endDateTime->getTimeField() //->setRightTitle($timeExpl) ->setConfig('timeformat', 'HH:mm') //24h fromat ->setAttribute('placeholder', 'Enter time'); //removing AllDay checkbox if allday events are disabled if (!CalendarConfig::subpackage_setting('events', 'enable_allday_events')) { $fields->removeByName('AllDay'); } //removing NoEnd checkbox if end dates are enforced if (CalendarConfig::subpackage_setting('events', 'force_end')) { $fields->removeByName('NoEnd'); } else { //we don't want the NoEnd checkbox when creating new events if (!$this->ID) { //$fields->removeByName('NoEnd'); } } $this->extend('updateFrontEndFields', $fields); return $fields; }
php
{ "resource": "" }
q60
FullcalendarController.publicevents
train
public function publicevents($request, $json=true, $calendars=null, $offset=30) { $calendarsSupplied = false; if ($calendars) { $calendarsSupplied = true; } $events = PublicEvent::get() ->filter(array( 'StartDateTime:GreaterThan' => $this->eventlistOffsetDate('start', $request->postVar('start'), $offset), 'EndDateTime:LessThan' => $this->eventlistOffsetDate('end', $request->postVar('end'), $offset), )); //If shaded events are enabled we need to filter shaded calendars out //note that this only takes effect when no calendars have been supplied //if calendars are supplied, this needs to be taken care of from that method $sC = CalendarConfig::subpackage_settings('calendars'); if ($sC['shading']) { if (!$calendars) { $calendars = PublicCalendar::get(); $calendars = $calendars->filter(array( 'shaded' => false )); } } if ($calendars) { $calIDList = $calendars->getIdList(); //adding in 0 to allow for showing events without a calendar if (!$calendarsSupplied) { $calIDList[0] = 0; } //Debug::dump($calIDList); $events = $events->filter('CalendarID', $calIDList); } $result = array(); if ($events) { foreach ($events as $event) { $calendar = $event->Calendar(); $bgColor = '#999'; //default $textColor = '#FFF'; //default $borderColor = '#555'; if ($calendar->exists()) { $bgColor = $calendar->getColorWithHash(); $textColor = '#FFF'; $borderColor = $calendar->getColorWithHash(); } $resultArr = self::format_event_for_fullcalendar($event); $resultArr = array_merge($resultArr, array( 'backgroundColor' => $bgColor, 'textColor' => '#FFF', 'borderColor' => $borderColor, )); $result[] = $resultArr; } } if ($json) { $response = new SS_HTTPResponse(Convert::array2json($result)); $response->addHeader('Content-Type', 'application/json'); return $response; } else { return $result; } }
php
{ "resource": "" }
q61
FullcalendarController.shadedevents
train
public function shadedevents($request, $json=true, $calendars = null, $offset=3000) { if (!$calendars) { $calendars = PublicCalendar::get(); } $calendars = $calendars->filter(array( 'shaded' => true )); return $this->publicevents($request, $json, $calendars, $offset); }
php
{ "resource": "" }
q62
FullcalendarController.handleJsonResponse
train
public function handleJsonResponse($success = false, $retVars = null) { $result = array(); if ($success) { $result = array( 'success' => $success ); } if ($retVars) { $result = array_merge($retVars, $result); } $response = new SS_HTTPResponse(json_encode($result)); $response->addHeader('Content-Type', 'application/json'); return $response; }
php
{ "resource": "" }
q63
FullcalendarController.format_event_for_fullcalendar
train
public static function format_event_for_fullcalendar($event) { $bgColor = '#999'; //default $textColor = '#FFF'; //default $borderColor = '#555'; $arr = array( 'id' => $event->ID, 'title' => $event->Title, 'start' => self::format_datetime_for_fullcalendar($event->StartDateTime), 'end' => self::format_datetime_for_fullcalendar($event->EndDateTime), 'allDay' => $event->isAllDay(), 'className' => $event->ClassName, //event calendar 'backgroundColor' => $bgColor, 'textColor' => '#FFFFFF', 'borderColor' => $borderColor, ); return $arr; }
php
{ "resource": "" }
q64
CommentType.buildForm
train
public function buildForm(FormBuilderInterface $builder, array $options) { if ($options['add_author']) { $builder->add('authorName', TextType::class, ['required' => true]); $this->vars['add_author'] = $options['add_author']; } if ($options['show_note']) { $builder->add('note', ChoiceType::class, [ 'required' => false, 'choices' => $this->noteProvider->getValues(), ]); } $builder ->add('website', UrlType::class, ['required' => false]) ->add('email', EmailType::class, ['required' => false]) ; }
php
{ "resource": "" }
q65
pakePHPDoc.getDescriptions
train
public static function getDescriptions($function_name) { if (is_string($function_name)) $reflection = new ReflectionFunction($function_name); elseif (is_array($function_name)) $reflection = new ReflectionMethod($function_name[0], $function_name[1]); else throw new LogicException(); $comment = $reflection->getDocComment(); $lines = explode("\n", $comment); $obj = new self($lines); return array(trim($obj->short_desc), trim($obj->long_desc)); }
php
{ "resource": "" }
q66
HTMLPurifierLaravel.purify
train
public function purify($html = '', $config = []) { return $this->purifier->purify( $html, $this->getConfig($config) ); }
php
{ "resource": "" }
q67
HTMLPurifierLaravel.getConfig
train
protected function getConfig($data = []) { // HTMLPurifier configuration $config = HTMLPurifier_Config::createDefault(); $config->autofinalize = false; // Set default settings, 'default' key must exist if (empty($data)) { $data = 'default'; } // If string given, get the config array if (is_string($data)) { $data = config(sprintf( 'parsedownextra.purifier.settings.%s', $data )); } // Merge both global and default settings $data = array_replace_recursive( (array) config('parsedownextra.purifier.settings.global'), (array) $data ); // At this point $data should be an array if (is_array($data)) { $config->loadArray($data); } return $config; }
php
{ "resource": "" }
q68
EventRegistrationExtension.getRegisterLink
train
public function getRegisterLink() { $o = $this->owner; //$link = $o->getInternalLink() . "/register"; //return $link; $detailStr = 'register/' . $o->ID; $calendarPage = CalendarPage::get()->First(); return $calendarPage->Link() . $detailStr; }
php
{ "resource": "" }
q69
Pool.attach
train
public function attach(Process $process) { if ($this->stopped) { throw new RuntimeException('Could not attach child to non-running pool'); } $firstProcess = $this->getFirstProcess(); if ($this->isRunning() && $firstProcess instanceof Process && $this->count() >= $this->processLimit) { $firstProcess->wait(); $this->detach($firstProcess); } $this->process->attach($process); if ($this->isRunning()) { $process->start(); } }
php
{ "resource": "" }
q70
Pool.getFirstProcess
train
public function getFirstProcess() { $firstProcess = null; foreach ($this->process as $process) { if ($this->isRunning() && ! $process->isRunning()) { $this->detach($process); continue; } if (null !== $firstProcess) { continue; } $firstProcess = $process; } return $firstProcess; }
php
{ "resource": "" }
q71
Callback.getHandlers
train
public function getHandlers() { $handlers = []; foreach ($this->handlers as $key => $handler) { $handlers[$key] = $handler->getCallable(); } return $handlers; }
php
{ "resource": "" }
q72
EventService.create
train
public function create($owner, $email, array $data) { $data = self::mergeData($data, [ 'owner' => $owner, 'email' => $email, ]); return $this->client->doPost('contact/addContactExtEvent', $data); }
php
{ "resource": "" }
q73
EventService.update
train
public function update($owner, $eventId, array $data) { $data = self::mergeData($data, [ 'owner' => $owner, 'contactEvent' => [ 'eventId' => $eventId, ], ]); return $this->client->doPost('contact/updateContactExtEvent', $data); }
php
{ "resource": "" }
q74
Grid.isFilterable
train
public function isFilterable() { $hasFilters = false; foreach ($this->columns as $column) { if ($column->isFilterable()) { $hasFilters = true; break; } } return $hasFilters; }
php
{ "resource": "" }
q75
Control.execute
train
public function execute($path, array $args = [], array $envs = []) { if (false === @pcntl_exec($path, $args, $envs)) { throw new RuntimeException('Error when executing command'); } }
php
{ "resource": "" }
q76
Control.flush
train
public function flush($seconds = 0) { if (! (is_float($seconds) || is_int($seconds)) || $seconds < 0) { throw new InvalidArgumentException('Seconds must be a number greater than or equal to 0'); } if (is_int($seconds)) { sleep($seconds); } else { usleep($seconds * 1000000); } clearstatcache(); gc_collect_cycles(); }
php
{ "resource": "" }
q77
Info.setUserName
train
public function setUserName($userName) { $user = posix_getpwnam($userName); if (! isset($user['uid'])) { throw new InvalidArgumentException(sprintf('"%s" is not a valid user name', $userName)); } $this->setUserId($user['uid']); }
php
{ "resource": "" }
q78
Info.setGroupName
train
public function setGroupName($groupName) { $group = posix_getgrnam($groupName); if (! isset($group['gid'])) { throw new InvalidArgumentException(sprintf('"%s" is not a valid group name', $groupName)); } $this->setGroupId($group['gid']); }
php
{ "resource": "" }
q79
ServerRequestFactory.fromGlobals
train
public static function fromGlobals(array $server = null, array $query = null, array $body = null, array $cookies = null, array $files = null) : ServerRequestInterface { $server = $server ?? $_SERVER ?? []; $query = $query ?? $_GET ?? []; $body = $body ?? $_POST ?? []; $cookies = $cookies ?? $_COOKIE ?? []; $files = $files ?? $_FILES ?? []; $request = (new ServerRequest) ->withProtocolVersion(request_http_version($server)) ->withBody(request_body()) ->withMethod(request_method($server)) ->withUri(request_uri($server)) ->withServerParams($server) ->withCookieParams($cookies) ->withQueryParams($query) ->withUploadedFiles(request_files($files)) ->withParsedBody($body); foreach (request_headers($server) as $name => $value) { $request = $request->withHeader($name, $value); } return $request; }
php
{ "resource": "" }
q80
ErrorHandlerController.catchAll
train
public function catchAll(...$args) : object { $title = " | Anax"; $pages = [ "403" => [ "Anax 403: Forbidden", "You are not permitted to do this." ], "404" => [ "Anax 404: Not Found", "The page you are looking for is not here." ], "500" => [ "Anax 500: Internal Server Error", "An unexpected condition was encountered." ], ]; $path = $this->di->get("router")->getMatchedPath(); if (!array_key_exists($path, $pages)) { throw new NotFoundException("Internal route for '$path' is not found."); } $page = $this->di->get("page"); $page->add( "anax/v2/error/default", [ "header" => $pages[$path][0], "text" => $pages[$path][1], ] ); return $page->render([ "title" => $pages[$path][0] . $title ], $path); }
php
{ "resource": "" }
q81
BackgroundTask.startProcess
train
private function startProcess(OutputInterface $output) { $arguments = $this->resolveProcessArgs(); $name = sha1(serialize($arguments)); if ($this->background->hasProcess($name)) { throw new \RuntimeException("Service is already running."); } $builder = new ProcessBuilder($arguments); if ($this->hasParameter('cwd')) { $builder->setWorkingDirectory($this->getParameter('cwd')); } $process = $builder->getProcess(); if ($output->getVerbosity() === OutputInterface::VERBOSITY_VERBOSE) { $output->writeln($process->getCommandLine()); } if ($this->hasParameter('output')) { $append = $this->hasParameter('append') && $this->getParameter('append') ? 'a' : 'w'; $stream = fopen($this->getParameter('output'), $append); $output = new StreamOutput($stream, StreamOutput::VERBOSITY_NORMAL, true); } $process->start( function ($type, $buffer) use ($output) { $output->write($buffer); } ); $this->background->addProcess($name, $process); if (!in_array($process->getExitCode(), $this->getParameter('successCodes'))) { throw new TaskRuntimeException($this->getName(), $process->getErrorOutput()); } }
php
{ "resource": "" }
q82
BackgroundTask.endProcess
train
private function endProcess() { $arguments = $this->resolveProcessArgs(); $name = sha1(serialize($arguments)); if ($this->background->hasProcess($name)) { $this->background->getProcess($name)->stop(); $this->background->removeProcess($name); } }
php
{ "resource": "" }
q83
FinderAwareTrait.getFiles
train
protected function getFiles(array $source) { $fileSet = []; foreach ($source as $set) { if (!array_key_exists('files', $set)) { throw new \Exception("`src` must have a `files` option"); } if (!array_key_exists('path', $set)) { $set['path'] = getcwd(); } if (!array_key_exists('recursive', $set)) { $set['recursive'] = false; } $paths = is_array($set['path']) ? $set['path'] : [$set['path']]; $files = is_array($set['files']) ? $set['files'] : [$set['files']]; foreach ($paths as $path) { foreach ($files as $file) { $finder = new Finder(); $finder->files()->in($path)->name($file); if (!$set['recursive']) { $finder->depth('== 0'); } $fileSet = $this->appendFileSet($finder, $fileSet); } } } return $fileSet; }
php
{ "resource": "" }
q84
pakeHttp.matchRequest
train
public static function matchRequest($regexp, $method, $url, $query_data = null, $body = null, array $headers = array(), array $options = array()) { $response = self::request($method, $url, $query_data, $body, $headers, $options); $result = preg_match($regexp, $response); if (false === $result) { throw new pakeException("There's some error with this regular expression: ".$regexp); } if (0 === $result) { throw new pakeException("HTTP Response didn't match against regular expression: ".$regexp); } pake_echo_comment('HTTP response matched against '.$regexp); }
php
{ "resource": "" }
q85
pakeHttp.get
train
public static function get($url, $query_data = null, array $headers = array(), array $options = array()) { return self::request('GET', $url, $query_data, null, $headers, $options); }
php
{ "resource": "" }
q86
Pidfile.setApplicationName
train
protected function setApplicationName($applicationName) { if ($applicationName != strtolower($applicationName)) { throw new InvalidArgumentException('Application name should be lowercase'); } if (preg_match('/[^a-z0-9]/', $applicationName)) { throw new InvalidArgumentException('Application name should contains only alphanumeric chars'); } if (strlen($applicationName) > 16) { $message = 'Application name should be no longer than 16 characters'; throw new InvalidArgumentException($message); } $this->applicationName = $applicationName; }
php
{ "resource": "" }
q87
Pidfile.setLockDirectory
train
protected function setLockDirectory($lockDirectory) { if (! is_dir($lockDirectory)) { throw new InvalidArgumentException(sprintf('"%s" is not a valid directory', $lockDirectory)); } if (! is_writable($lockDirectory)) { throw new InvalidArgumentException(sprintf('"%s" is not a writable directory', $lockDirectory)); } $this->lockDirectory = $lockDirectory; }
php
{ "resource": "" }
q88
Pidfile.getFileName
train
protected function getFileName() { if (null === $this->fileName) { $this->fileName = $this->lockDirectory.'/'.$this->applicationName.'.pid'; } return $this->fileName; }
php
{ "resource": "" }
q89
Pidfile.getFileResource
train
protected function getFileResource() { if (null === $this->fileResource) { $fileResource = @fopen($this->getFileName(), 'a+'); if (! $fileResource) { throw new RuntimeException('Could not open pidfile'); } $this->fileResource = $fileResource; } return $this->fileResource; }
php
{ "resource": "" }
q90
Pidfile.isActive
train
public function isActive() { $pid = $this->getProcessId(); if (null === $pid) { return false; } return $this->control->signal()->send(0, $pid); }
php
{ "resource": "" }
q91
Pidfile.getProcessId
train
public function getProcessId() { if (null === $this->processId) { $content = fgets($this->getFileResource()); $pieces = explode(PHP_EOL, trim($content)); $this->processId = reset($pieces) ?: 0; } return $this->processId ?: null; }
php
{ "resource": "" }
q92
Pidfile.initialize
train
public function initialize() { if ($this->isActive()) { throw new RuntimeException('Process is already active'); } $handle = $this->getFileResource(); if (! @flock($handle, (LOCK_EX | LOCK_NB))) { throw new RuntimeException('Could not lock pidfile'); } if (-1 === @fseek($handle, 0)) { throw new RuntimeException('Could not seek pidfile cursor'); } if (! @ftruncate($handle, 0)) { throw new RuntimeException('Could not truncate pidfile'); } if (! @fwrite($handle, $this->control->info()->getId().PHP_EOL)) { throw new RuntimeException('Could not write on pidfile'); } }
php
{ "resource": "" }
q93
Pidfile.finalize
train
public function finalize() { @flock($this->getFileResource(), LOCK_UN); @fclose($this->getFileResource()); @unlink($this->getFileName()); }
php
{ "resource": "" }
q94
ConfigManager.getConfigDir
train
public function getConfigDir() { $home = getenv('PHPCRSH_HOME'); if ($home) { return $home; } // handle windows .. if (defined('PHP_WINDOWS_VERSION_MAJOR')) { if (!getenv('APPDATA')) { throw new \RuntimeException( 'The APPDATA or phpcrsh_HOME environment variable must be set for phpcrsh to run correctly' ); } $home = strtr(getenv('APPDATA'), '\\', '/').'/phpcrsh'; return $home; } if (!getenv('HOME')) { throw new \RuntimeException( 'The HOME or phpcrsh_HOME environment variable must be set for phpcrsh to run correctly' ); } $home = rtrim(getenv('HOME'), '/').'/.phpcrsh'; return $home; }
php
{ "resource": "" }
q95
ConfigManager.initConfig
train
public function initConfig(OutputInterface $output = null) { $log = function ($message) use ($output) { if ($output) { $output->writeln($message); } }; if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { throw new \RuntimeException('This feature is currently only supported on Linux and OSX (maybe). Please submit a PR to support it on windows.'); } $configDir = $this->getConfigDir(); $distDir = $this->getDistConfigDir(); if (!$this->filesystem->exists($configDir)) { $log('<info>[+] Creating directory:</info> '.$configDir); $this->filesystem->mkdir($configDir); } $configFilenames = [ 'alias.yml', 'phpcrsh.yml', ]; foreach ($configFilenames as $configFilename) { $srcFile = $distDir.'/'.$configFilename; $destFile = $configDir.'/'.$configFilename; if (!$this->filesystem->exists($srcFile)) { throw new \Exception('Dist (source) file "'.$srcFile.'" does not exist.'); } if ($this->filesystem->exists($destFile)) { $log(sprintf('<info>File</info> %s <info> already exists, not overwriting.', $destFile)); return; } $this->filesystem->copy($srcFile, $destFile); $log('<info>[+] Creating file:</info> '.$destFile); } }
php
{ "resource": "" }
q96
SonataCommentExtension.hasBundle
train
protected function hasBundle($name, ContainerBuilder $container) { $bundles = $container->getParameter('kernel.bundles'); return isset($bundles[$name]); }
php
{ "resource": "" }
q97
TagsRepository.getRecentMedia
train
public function getRecentMedia($tag, $count = null, $minTagId = null, $maxTagId = null) { $params = ['query' => [ 'count' => $count, 'min_tag_id' => $minTagId, 'max_tag_id' => $maxTagId, ]]; return $this->client->request('GET', "tags/$tag/media/recent", $params); }
php
{ "resource": "" }
q98
RedirectLoginHelper.getLoginUrl
train
public function getLoginUrl(array $options = []) { $url = $this->provider->getAuthorizationUrl($options); $this->store->set('oauth2state', $this->provider->getState()); return $url; }
php
{ "resource": "" }
q99
RedirectLoginHelper.getAccessToken
train
public function getAccessToken($code, $grant = 'authorization_code') { $this->validateCsrf(); return $this->provider->getAccessToken($grant, ['code' => $code]); }
php
{ "resource": "" }