sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public function retrieveMostPopular($max)
{
$query = $this->createQueryBuilder('s')
->orderBy('s.searchCount', 'DESC')
->setMaxResults($max)
->getQuery();
return $query->getResult();
} | @param int $max
@return DoctrineCollection|null | entailment |
public function translate($message, array $params = array())
{
// Update the current message with the domain translation, if we have one.
if (isset($this->messages[$message]) && ! empty($this->messages[$message])) {
$message = $this->messages[$message];
}
if (empty($params)) {
return $message;
}
$formatter = new MessageFormatter();
return $formatter->format($message, $params, $this->locale);
} | Translate a message with optional formatting
@param string $message Original message.
@param array $params Optional params for formatting.
@return string | entailment |
public function handle($request, Closure $next, $maxAttempts = 60, $decayMinutes = 1)
{
$key = $this->resolveRequestSignature($request);
if ($this->limiter->tooManyAttempts($key, $maxAttempts, $decayMinutes)) {
return $this->buildResponse($key, $maxAttempts);
}
$this->limiter->hit($key, $decayMinutes);
$response = $next($request);
return $this->addHeaders(
$response, $maxAttempts,
$this->calculateRemainingAttempts($key, $maxAttempts)
);
} | Handle an incoming request.
@param \Nova\Http\Request $request
@param \Closure $next
@param int $maxAttempts
@param int $decayMinutes
@return mixed | entailment |
protected function buildResponse($key, $maxAttempts)
{
$response = new Response('Too Many Attempts.', 429);
$retryAfter = $this->limiter->availableIn($key);
return $this->addHeaders(
$response, $maxAttempts,
$this->calculateRemainingAttempts($key, $maxAttempts, $retryAfter),
$retryAfter
);
} | Create a 'too many attempts' response.
@param string $key
@param int $maxAttempts
@return \Nova\Http\Response | entailment |
public function dispatch($event, $payload = array(), $halt = false)
{
$responses = array();
// When the given "event" is actually an object we will assume it is an event
// object and use the class as the event name and this event itself as the
// payload to the handler, which makes object based events quite simple.
if (is_object($event)) {
list($payload, $event) = array(array($event), get_class($event));
}
// If an array is not given to us as the payload, we will turn it into one so
// we can easily use call_user_func_array on the listeners, passing in the
// payload to each of them so that they receive each of these arguments.
else if (! is_array($payload)) {
$payload = array($payload);
}
$this->dispatching[] = $event;
if (isset($payload[0]) && ($payload[0] instanceof ShouldBroadcastInterface)) {
$this->broadcastEvent($payload[0]);
}
foreach ($this->getListeners($event) as $listener) {
$response = call_user_func_array($listener, $payload);
// If a response is returned from the listener and event halting is enabled
// we will just return this response, and not call the rest of the event
// listeners. Otherwise we will add the response on the response list.
if (! is_null($response) && $halt) {
array_pop($this->dispatching);
return $response;
}
// If a boolean false is returned from a listener, we will stop propagating
// the event to any further listeners down in the chain, else we keep on
// looping through the listeners and dispatching every one in our sequence.
if ($response === false) {
break;
}
$responses[] = $response;
}
array_pop($this->dispatching);
if (! $halt) {
return $responses;
}
} | Dispatch an event and call the listeners.
@param string $event
@param mixed $payload
@param bool $halt
@return array|null | entailment |
protected function broadcastEvent($event)
{
$connection = ($event instanceof ShouldBroadcastNowInterface) ? 'sync' : null;
$queue = method_exists($event, 'onQueue') ? $event->onQueue() : null;
$this->resolveQueue()->connection($connection)->pushOn($queue, 'Nova\Broadcasting\BroadcastEvent', array(
'event' => serialize(clone $event),
));
} | Broadcast the given event class.
@param \Nova\Broadcasting\ShouldBroadcastInterface $event
@return void | entailment |
public function getListeners($eventName)
{
$wildcards = $this->getWildcardListeners($eventName);
if (! isset($this->sorted[$eventName])) {
$this->sortListeners($eventName);
}
return array_merge($this->sorted[$eventName], $wildcards);
} | Get all of the listeners for a given event name.
@param string $eventName
@return array | entailment |
public function createClassListener($listener)
{
return function() use ($listener)
{
$callable = $this->createClassCallable($listener);
// We will make a callable of the listener instance and a method that should
// be called on that instance, then we will pass in the arguments that we
// received in this method into this listener class instance's methods.
$data = func_get_args();
return call_user_func_array($callable, $data);
};
} | Create a class based listener using the IoC container.
@param mixed $listener
@return \Closure | entailment |
protected function createQueuedHandlerCallable($className, $method)
{
return function () use ($className, $method)
{
// Clone the given arguments for queueing.
$arguments = array_map(function ($a)
{
return is_object($a) ? clone $a : $a;
}, func_get_args());
if (method_exists($className, 'queue')) {
$this->callQueueMethodOnHandler($className, $method, $arguments);
} else {
$this->resolveQueue()->push('Nova\Events\CallQueuedHandler@call', array(
'class' => $className,
'method' => $method,
'data' => serialize($arguments),
));
}
};
} | Create a callable for putting an event handler on the queue.
@param string $className
@param string $method
@return \Closure | entailment |
public function register()
{
$this->app->singleton('Nova\Broadcasting\BroadcastManager', function ($app)
{
return new BroadcastManager($app);
});
$this->app->singleton('Nova\Broadcasting\BroadcasterInterface', function ($app)
{
return $app->make('Nova\Broadcasting\BroadcastManager')->connection();
});
$this->app->alias(
'Nova\Broadcasting\BroadcastManager', 'Nova\Broadcasting\FactoryInterface'
);
} | Register the service provider.
@return void | entailment |
public function pop($queue = null)
{
$queue = $this->getQueue($queue);
$response = $this->sqs->receiveMessage(
array('QueueUrl' => $queue, 'AttributeNames' => array('ApproximateReceiveCount'))
);
if (count($response['Messages']) > 0)
{
return new SqsJob($this->container, $this->sqs, $queue, $response['Messages'][0]);
}
} | Pop the next job off of the queue.
@param string $queue
@return \Nova\Queue\Jobs\Job|null | entailment |
protected function addToActionList($action, $route)
{
$controller = $action['controller'];
if (! isset($this->actionList[$controller])) {
$this->actionList[$controller] = $route;
}
} | Add a route to the controller action dictionary.
@param array $action
@param \Nova\Routing\Route $route
@return void | entailment |
public function match(Request $request)
{
$routes = $this->get($request->getMethod());
// First, we will see if we can find a matching route for this current request
// method. If we can, great, we can just return it so that it can be called
// by the consumer. Otherwise we will check for routes with another verb.
if (! is_null($route = $this->fastCheck($routes, $request))) {
// A route was found in the fast way.
} else {
$route = $this->check($routes, $request);
}
if (! is_null($route)) {
return $route->bind($request);
}
// If no route was found, we will check if a matching route is specified on
// another HTTP verb. If it is we will need to throw a MethodNotAllowed and
// inform the user agent of which HTTP verb it should use for this route.
$others = $this->checkForAlternateVerbs($request);
if (! empty($others)) {
return $this->getOtherMethodsRoute($request, $others);
}
throw new NotFoundHttpException;
} | Find the first route matching a given request.
@param \Nova\Http\Request $request
@return \Nova\Routing\Route
@throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException | entailment |
protected function checkForAlternateVerbs($request)
{
$methods = array_diff(
Router::$verbs, (array) $request->getMethod()
);
// Here we will spin through all verbs except for the current request verb and
// check to see if any routes respond to them. If they do, we will return a
// proper error response with the correct headers on the response string.
return array_filter($methods, function ($method) use ($request)
{
$route = $this->check($this->get($method), $request, false);
return ! is_null($route);
});
} | Determine if any routes match on another HTTP verb.
@param \Nova\Http\Request $request
@return array | entailment |
protected function getOtherMethodsRoute($request, array $others)
{
if ($request->method() !== 'OPTIONS') {
throw new MethodNotAllowedHttpException($others);
}
$route = new Route('OPTIONS', $request->path(), function () use ($others)
{
return new Response('', 200, array('Allow' => implode(',', $others)));
});
return $route->bind($request);
} | Get a route (if necessary) that responds when other available methods are present.
@param \Nova\Http\Request $request
@param array $others
@return \Nova\Routing\Route
@throws \Symfony\Component\Routing\Exception\MethodNotAllowedHttpException | entailment |
protected function check(array $routes, $request, $includingMethod = true)
{
return Arr::first($routes, function ($key, $route) use ($request, $includingMethod)
{
return $route->matches($request, $includingMethod);
});
} | Determine if a route in the array matches the request.
@param array $routes
@param \Nova\http\Request $request
@param bool $includingMethod
@return \Nova\Routing\Route|null | entailment |
protected function fastCheck(array $routes, $request)
{
$domain = $request->getHost();
$path = ($request->path() == '/') ? '/' : '/' .$request->path();
foreach (array($domain .$path, $path) as $key) {
$route = Arr::get($routes, $key);
if (! is_null($route) && $route->matches($request, true)) {
return $route;
}
}
} | Determine if a route in the array fully matches the request - the fast way.
@param array $routes
@param \Nova\http\Request $request
@return \Nova\Routing\Route|null | entailment |
public function handle($request, Closure $next)
{
$session = $this->app['session'];
if (! $session->has('language')) {
$cookie = $request->cookie(PREFIX .'language', null);
$locale = $cookie ?: $this->app['config']->get('app.locale');
$session->set('language', $locale);
} else {
$locale = $session->get('language');
}
$this->app['language']->setLocale($locale);
return $next($request);
} | Handle an incoming request.
@param \Nova\Http\Request $request
@param \Closure $next
@return mixed
@throws \Nova\Http\Exception\PostTooLargeException | entailment |
public function handle()
{
$this->checkPhpVersion();
chdir($this->container['path.base']);
$host = $this->input->getOption('host');
$port = $this->input->getOption('port');
$public = $this->container['path.public'];
$this->info("Nova Framework development Server started on http://{$host}:{$port}");
passthru('"'.PHP_BINARY.'"'." -S {$host}:{$port} -t \"{$public}\" server.php");
} | Execute the console command.
@return void | entailment |
public function broadcastOn()
{
$channels = $this->notification->broadcastOn();
if (! empty($channels)) {
return $channels;
}
$channel = 'private-' .$this->channelName();
return array($channel);
} | Get the channels the event should broadcast on.
@return array | entailment |
public function broadcastWith()
{
return array_merge($this->data, array(
'id' => $this->notification->id,
'type' => get_class($this->notification),
));
} | Get the data that should be sent with the broadcasted event.
@return array | entailment |
protected function evaluatePath($__path, $__data)
{
$obLevel = ob_get_level();
//
ob_start();
// Extract the rendering variables.
foreach ($__data as $__variable => $__value) {
if (in_array($__variable, array('__path', '__data'))) {
continue;
}
${$__variable} = $__value;
}
// Housekeeping...
unset($__data, $__variable, $__value);
// We'll evaluate the contents of the view inside a try/catch block so we can
// flush out any stray output that might get out before an error occurs or
// an exception is thrown. This prevents any partial views from leaking.
try {
include $__path;
}
catch (\Exception $e) {
$this->handleViewException($e, $obLevel);
}
catch (\Throwable $e) {
$this->handleViewException($e, $obLevel);
}
return ltrim(ob_get_clean());
} | Get the evaluated contents of the View at the given path.
@param string $__path
@param array $__data
@return string | entailment |
public static function fromFile($path)
{
return new self($path, filesize($path), \DateTime::createFromFormat('U', filemtime($path)));
} | @param string $path The path to the file.
@return Backup | entailment |
public function addKeyboardButton($button): self
{
if (!(is_string($button) || ($button instanceof KeyboardButton))) {
throw new \DomainException("Button should be a string or a KeyboardButton instance");
}
$lastRowIndex = max(count($this->keyboard) - 1, 0);
$this->keyboard[$lastRowIndex][] = $button;
return $this;
} | @param string|KeyboardButton $button
@return ReplyKeyboardMarkup | entailment |
function jsonSerialize()
{
$result = [
'keyboard' => $this->keyboard
];
if ($this->selective !== null) {
$result['selective'] = $this->selective;
}
return $result;
} | Specify data which should be serialized to JSON | entailment |
protected function writeLog($level, $message, $context)
{
$this->fireLogEvent($level, $message = $this->formatMessage($message), $context);
$this->monolog->{$level}($message, $context);
} | Write a message to Monolog.
@param string $level
@param string $message
@param array $context
@return void | entailment |
public function useFiles($path, $level = 'debug')
{
$this->monolog->pushHandler($handler = new StreamHandler($path, $this->parseLevel($level)));
$handler->setFormatter($this->getDefaultFormatter());
} | Register a file log handler.
@param string $path
@param string $level
@return void | entailment |
public function useDailyFiles($path, $days = 0, $level = 'debug')
{
$this->monolog->pushHandler(
$handler = new RotatingFileHandler($path, $days, $this->parseLevel($level))
);
$handler->setFormatter($this->getDefaultFormatter());
} | Register a daily file log handler.
@param string $path
@param int $days
@param string $level
@return void | entailment |
public function useErrorLog($level = 'debug', $messageType = ErrorLogHandler::OPERATING_SYSTEM)
{
$this->monolog->pushHandler(
$handler = new ErrorLogHandler($messageType, $this->parseLevel($level))
);
$handler->setFormatter($this->getDefaultFormatter());
} | Register an error_log handler.
@param string $level
@param int $messageType
@return void | entailment |
public function listen(Closure $callback)
{
if (! isset($this->events)) {
throw new RuntimeException('Events dispatcher has not been set.');
}
$this->events->listen('framework.log', $callback);
} | Register a new callback handler for when a log event is triggered.
@param \Closure $callback
@return void
@throws \RuntimeException | entailment |
protected function fireLogEvent($level, $message, array $context = array())
{
if (isset($this->events)) {
$this->events->dispatch('framework.log', compact('level', 'message', 'context'));
}
} | Fires a log event.
@param string $level
@param string $message
@param array $context
@return void | entailment |
public function handle()
{
$this->table = new Table($this->output);
if (count($this->routes) == 0) {
return $this->error("Your application doesn't have any routes.");
}
$this->displayRoutes($this->getRoutes());
} | Execute the console command.
@return void | entailment |
protected function getRoutes()
{
$results = array();
foreach($this->routes as $route) {
$results[] = $this->getRouteInformation($route);
}
return array_filter($results);
} | Compile the routes into a displayable format.
@return array | entailment |
protected function getRouteInformation(Route $route)
{
$methods = implode('|', $route->methods());
return $this->filterRoute(array(
'host' => $route->domain(),
'method' => $methods,
'uri' => $route->uri(),
'name' => $route->getName(),
'action' => $route->getActionName(),
'middleware' => $this->getMiddleware($route),
));
} | Get the route information for a given route.
@param string $name
@param \Nova\Routing\Route $route
@return array | entailment |
protected function getControllerMiddleware($actionName)
{
list($controller, $method) = explode('@', $actionName);
return $this->getControllerMiddlewareFromInstance(
$this->container->make($controller), $method
);
} | Get the middleware for the given Controller@action name.
@param string $actionName
@return array | entailment |
protected function getControllerMiddlewareFromInstance($controller, $method)
{
$middlewares = $this->router->getMiddleware();
//
$results = array();
foreach ($controller->getMiddleware() as $middleware => $options) {
if (ControllerDispatcher::methodExcludedByOptions($method, $options)) {
continue;
}
list($name, $parameters) = array_pad(explode(':', $middleware, 2), 2, null);
$middleware = Arr::get($middlewares, $name, $name);
$results[] = (! $middleware instanceof Closure) ? $middleware : $name;
}
return $results;
} | Get the middlewares for the given controller instance and method.
@param \Nova\Routing\Controller $controller
@param string $method
@return array | entailment |
public function getParams(): array
{
$params = [
'callback_query_id' => $this->callbackQueryId,
];
$params = array_merge($params, $this->buildJsonAttributes([
'show_alert' => $this->showAlert,
'cache_time' => $this->cacheTime
]));
return $params;
} | Get parameters for HTTP query.
@return mixed | entailment |
public function execute($path = '/', $method = HTTPRequest::GET)
{
$targetURL = $this->httpConnection->getURI().$path;
$hasParameters = count($this->requestParameter) > 0;
$query = $hasParameters ? http_build_query($this->requestParameter) : null;
switch ($method) {
case HTTPRequest::PUT :
case HTTPRequest::POST :
if ($method != HTTPRequest::POST) {
curl_setopt($this->curlResource, CURLOPT_CUSTOMREQUEST,
$method);
} else {
curl_setopt($this->curlResource, CURLOPT_POST, 1);
}
if (empty($this->requestBody)) {
curl_setopt($this->curlResource, CURLOPT_POSTFIELDS, $query);
} else {
if ($hasParameters) {
$targetURL .= '?'.$query;
}
curl_setopt($this->curlResource, CURLOPT_POSTFIELDS,
$this->requestBody);
}
curl_setopt($this->curlResource, CURLOPT_URL, $targetURL);
break;
case HTTPRequest::DELETE :
case HTTPRequest::HEAD :
case HTTPRequest::OPTIONS :
case HTTPRequest::TRACE :
curl_setopt($this->curlResource, CURLOPT_CUSTOMREQUEST, $method);
case HTTPRequest::GET :
if ($hasParameters) {
$targetURL .= '?'.$query;
}
curl_setopt($this->curlResource, CURLOPT_URL, $targetURL);
break;
default :
throw new UnexpectedValueException('Unknown method.');
}
$resp = curl_exec($this->curlResource);
$errno = curl_errno($this->curlResource);
$error = curl_error($this->curlResource);
if ($errno != 0) {
throw new RuntimeException($error, $errno);
}
$this->httpResponse = new HTTPResponse();
$this->httpResponse->setRawResponse($resp);
if ($this->httpResponse->hasResponseHeader('Set-Cookie')) {
$cookieManager = $this->httpConnection->getCookieManager();
if ($cookieManager != null) {
$cookieManager->setCookie(
$this->httpResponse->getHeader('Set-Cookie'),
$this->httpConnection->getHostName());
}
}
$statusCode = $this->httpResponse->getStatusCode();
return $statusCode < 400;
} | Executa a requisição HTTP em um caminho utilizando um método específico.
@param string $method Método da requisição.
@param string $path Alvo da requisição.
@return bool Resposta HTTP.
@throws \BadMethodCallException Se não houver uma conexão inicializada.
@see \Moip\Http\HTTPRequest::execute() | entailment |
public function open(HTTPConnection $httpConnection)
{
if (function_exists('curl_init')) {
$this->close();
$curl = curl_init();
if (is_resource($curl)) {
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // FIXME
curl_setopt($curl, CURLOPT_HEADER, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLINFO_HEADER_OUT, true);
if (($timeout = $httpConnection->getTimeout()) != null) {
curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
}
if (($connectionTimeout = $httpConnection->getConnectionTimeout()) !=
null) {
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT,
$connectionTimeout);
}
$headers = array();
foreach ($this->requestHeader as $header) {
$headers[] = sprintf('%s: %s', $header['name'],
$header['value']);
}
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$this->curlResource = $curl;
$this->httpConnection = $httpConnection;
$this->openned = true;
} else {
throw new RuntimeException('cURL failed to start');
}
} else {
throw new RuntimeException('cURL not found.');
}
} | Abre a requisição.
@param \Moip\Http\HTTPConnection $httpConnection Conexão HTTP relacionada com essa requisição
@see \Moip\Http\HTTPRequest::open() | entailment |
public function jsonSerialize()
{
$data = [
'url' => $this->url
];
$data = array_merge($data, $this->buildJsonAttributes([
'certificate' => $this->certificate,
'max_connections' => $this->maxConnections,
'allowed_updates' => $this->allowedUpdates
]));
return $data;
} | Specify data which should be serialized to JSON
@link http://php.net/manual/en/jsonserializable.jsonserialize.php
@return mixed data which can be serialized by <b>json_encode</b>,
which is a value of any type other than a resource.
@since 5.4.0 | entailment |
public function render(Closure $callback = null)
{
try {
$contents = $this->renderContents();
$response = isset($callback) ? $callback($this, $contents) : null;
// Once we have the contents of the view, we will flush the sections if we are
// done rendering all views so that there is nothing left hanging over when
// another view gets rendered in the future by the application developer.
$this->factory->flushSectionsIfDoneRendering();
return $response ?: $contents;
} catch (Exception $e) {
$this->factory->flushSections();
throw $e;
}
} | Get the string contents of the View.
@param \Closure $callback
@return string | entailment |
public function renderSections()
{
$env = $this->factory;
return $this->render(function ($view) use ($env) {
return $env->getSections();
});
} | Get the sections of the rendered view.
@return array | entailment |
public function nest($key, $view, array $data = array())
{
// The nested View instance inherit parent Data if none is given.
if (empty($data)) $data = $this->data;
return $this->with($key, $this->factory->make($view, $data));
} | Add a view instance to the view data.
<code>
// Add a View instance to a View's data
$view = View::make('foo')->nest('footer', 'Partials/Footer');
// Equivalent functionality using the "with" method
$view = View::make('foo')->with('footer', View::make('Partials/Footer'));
</code>
@param string $key
@param string $view
@param array $data
@return View | entailment |
public function withErrors($provider)
{
if ($provider instanceof MessageProvider) {
$this->with('errors', $provider->getMessageBag());
} else {
$this->with('errors', new MessageBag((array) $provider));
}
return $this;
} | Add validation errors to the view.
@param \Nova\Support\Contracts\MessageProviderInterface|array $provider
@return \Nova\View\View | entailment |
public function display(Exception $exception, $code)
{
// Collect some info about the exception.
$info = $this->info($code, $exception);
// Is the current request an AJAX request?
if ((boolean)($this->request instanceof Request && $this->request->wantsJson()) == true) {
$json_object = (object)[ 'error' => [
'type' => 'Exception',
'message' => $info['message'],
] ];
return JsonResponse::create($json_object, $code);
}
// For model-not-found, use 404 errors.
if ($exception instanceof ModelNotFoundException) {
$code = 404;
}
// If there is a custom view, use that.
if ($this->view->exists("errors.{$code}")) {
return $this->view->make("errors.{$code}", $info)->render();
}
// If the configured default error view (or errors.error) exists, render that.
if (($errorview = $this->config->get('view.error', 'errors.error')) && $this->view->exists($errorview)) {
return $this->view->make($errorview, $info)->render();
}
// Last resort: simply show the error code and message.
return new Response($this->getFallbackDisplay($code, $info['name'], $info['message']), $code);
} | Get the HTML content associated with the given exception.
@param \Exception $exception
@param int $code
@return string | entailment |
protected function info($code, Exception $exception)
{
$description = $exception->getMessage();
$namespace = 'winternight/laravel-error-handler';
// If there is no error message for the given HTTP code, default to 500.
if (!$this->lang->has("$namespace::messages.error.$code.name")) {
$code = 500;
}
$name = $this->lang->get("$namespace::messages.error.$code.name");
$message = $this->lang->get("$namespace::messages.error.$code.message");
return compact('code', 'name', 'message', 'description');
} | Get the exception information.
@param int $code
@param \Exception $exception
@return array | entailment |
public function create($name, $scratchDir, $processor, $namer, array $sources, array $destinations)
{
return new Profile(
$name,
$scratchDir,
$this->getProcessor($processor),
$this->getNamer($namer),
$this->getSources($sources),
$this->getDestinations($destinations)
);
} | @param string $name
@param string $scratchDir
@param string $processor
@param string $namer
@param array $sources
@param array $destinations
@return Profile | entailment |
public function getSource($name)
{
if (!isset($this->sources[$name])) {
throw new \InvalidArgumentException(sprintf('Source "%s" is not registered.', $name));
}
return $this->sources[$name];
} | @param string $name
@return Source | entailment |
public function getSources(array $names)
{
$self = $this;
return array_map(function ($name) use ($self) {
return $self->getSource($name);
}, $names);
} | @param array $names
@return Source[] | entailment |
public function getNamer($name)
{
if (!isset($this->namers[$name])) {
throw new \InvalidArgumentException(sprintf('Namer "%s" is not registered.', $name));
}
return $this->namers[$name];
} | @param string $name
@return Namer | entailment |
public function getProcessor($name)
{
if (!isset($this->processors[$name])) {
throw new \InvalidArgumentException(sprintf('Processor "%s" is not registered.', $name));
}
return $this->processors[$name];
} | @param string $name
@return Processor | entailment |
public function getDestination($name)
{
if (!isset($this->destinations[$name])) {
throw new \InvalidArgumentException(sprintf('Destination "%s" is not registered.', $name));
}
return $this->destinations[$name];
} | @param string $name
@return Destination | entailment |
public function getDestinations(array $names)
{
$self = $this;
return array_map(function ($name) use ($self) {
return $self->getDestination($name);
}, $names);
} | @param array $names
@return Destination[] | entailment |
public function compileRenameColumn(Blueprint $blueprint, Fluent $command, Connection $connection)
{
$schema = $connection->getDoctrineSchemaManager();
$table = $this->getTablePrefix().$blueprint->getTable();
$column = $connection->getDoctrineColumn($table, $command->from);
$tableDiff = $this->getRenamedDiff($blueprint, $command, $column, $schema);
return (array) $schema->getDatabasePlatform()->getAlterTableSQL($tableDiff);
} | Compile a rename column command.
@param \Nova\Database\Schema\Blueprint $blueprint
@param \Nova\Support\Fluent $command
@param \Nova\Database\Connection $connection
@return array | entailment |
protected function getRenamedDiff(Blueprint $blueprint, Fluent $command, Column $column, SchemaManager $schema)
{
$tableDiff = $this->getDoctrineTableDiff($blueprint, $schema);
return $this->setRenamedColumns($tableDiff, $command, $column);
} | Get a new column instance with the new column name.
@param \Nova\Database\Schema\Blueprint $blueprint
@param \Nova\Support\Fluent $command
@param \Doctrine\DBAL\Schema\Column $column
@param \Doctrine\DBAL\Schema\AbstractSchemaManager $schema
@return \Doctrine\DBAL\Schema\TableDiff | entailment |
protected function getColumns(Blueprint $blueprint)
{
$columns = array();
foreach ($blueprint->getColumns() as $column) {
// Each of the column types have their own compiler functions which are tasked
// with turning the column definition into its SQL format for this platform
// used by the connection. The column's modifiers are compiled and added.
$sql = $this->wrap($column).' '.$this->getType($column);
$columns[] = $this->addModifiers($sql, $blueprint, $column);
}
return $columns;
} | Compile the blueprint's column definitions.
@param \Nova\Database\Schema\Blueprint $blueprint
@return array | entailment |
public function wrapTable($table)
{
if ($table instanceof Blueprint) $table = $table->getTable();
return parent::wrapTable($table);
} | Wrap a table in keyword identifiers.
@param mixed $table
@return string | entailment |
public function wrap($value)
{
if ($value instanceof Fluent) $value = $value->name;
return parent::wrap($value);
} | Wrap a value in keyword identifiers.
@param string $value
@return string | entailment |
public function send($view, array $data, $callback)
{
// First we need to parse the view, which could either be a string or an array
// containing both an HTML and plain text versions of the view which should
// be used when sending an e-mail. We will extract both of them out here.
list($view, $plain, $raw) = $this->parseView($view);
$data['message'] = $message = $this->createMessage();
$this->callMessageBuilder($callback, $message);
// Once we have retrieved the view content for the e-mail we will set the body
// of this message using the HTML type, which will provide a simple wrapper
// to creating view based emails that are able to receive arrays of data.
$this->addContent($message, $view, $plain, $raw, $data);
$message = $message->getSwiftMessage();
$this->sendSwiftMessage($message);
} | Send a new message using a view.
@param string|array $view
@param array $data
@param \Closure|string $callback
@return void | entailment |
public function queue($view, array $data, $callback, $queue = null)
{
$callback = $this->buildQueueCallable($callback);
return $this->queue->push('mailer@handleQueuedMessage', compact('view', 'data', 'callback'), $queue);
} | Queue a new e-mail message for sending.
@param string|array $view
@param array $data
@param \Closure|string $callback
@param string $queue
@return mixed | entailment |
protected function parseView($view)
{
if (is_string($view)) {
return array($view, null, null);
}
// If the given view is an array with numeric keys, we will just assume that
// both a "pretty" and "plain" view were provided, so we will return this
// array as is, since must should contain both views with numeric keys.
if (is_array($view) && isset($view[0])) {
return array($view[0], $view[1], null);
}
// If the view is an array, but doesn't contain numeric keys, we will assume
// the the views are being explicitly specified and will extract them via
// named keys instead, allowing the developers to use one or the other.
else if (is_array($view)) {
return array(
Arr::get($view, 'html'),
Arr::get($view, 'text'),
Arr::get($view, 'raw'),
);
}
throw new \InvalidArgumentException("Invalid view.");
} | Parse the given view name or array.
@param string|array $view
@return array
@throws \InvalidArgumentException | entailment |
protected function sendSwiftMessage($message)
{
if ($this->events) {
$this->events->dispatch('mailer.sending', array($message));
}
if (! $this->pretending) {
try {
$this->swift->send($message, $this->failedRecipients);
}
finally {
$this->swift->getTransport()->stop();
}
}
// In the pretending mode.
else if (isset($this->logger)) {
$this->logMessage($message);
}
} | Send a Swift Message instance.
@param \Swift_Message $message
@return void | entailment |
protected function logMessage($message)
{
$emails = implode(', ', array_keys((array) $message->getTo()));
$this->logger->info("Pretending to mail message to: {$emails}");
} | Log that a message was sent.
@param \Swift_Message $message
@return void | entailment |
protected function callMessageBuilder($callback, $message)
{
if ($callback instanceof Closure) {
return call_user_func($callback, $message);
} else if (is_string($callback)) {
return $this->container[$callback]->mail($message);
}
throw new \InvalidArgumentException("Callback is not valid.");
} | Call the provided message builder.
@param \Closure|string $callback
@param \Nova\Mail\Message $message
@return mixed
@throws \InvalidArgumentException | entailment |
protected function createMessage()
{
$message = new Message(new Swift_Message);
// If a global from address has been specified we will set it on every message
// instances so the developer does not have to repeat themselves every time
// they create a new message. We will just go ahead and push the address.
if (isset($this->from['address'])) {
$message->from($this->from['address'], $this->from['name']);
}
return $message;
} | Create a new message instance.
@return \Nova\Mail\Message | entailment |
public function getParams(): array
{
$params = [
'chat_id' => $this->chatId,
'audio' => $this->audio,
];
if ($this->disableNotification !== null) {
$params['disable_notification'] = (int)$this->disableNotification;
}
if ($this->replyToMessageId) {
$params['reply_to_message_id'] = $this->replyToMessageId;
}
return $params;
} | Get parameters for HTTP query.
@return mixed | entailment |
public function handle()
{
$path = $this->container['config']->get('view.compiled');
if (! $this->files->exists($path)) {
throw new RuntimeException('View path not found.');
}
foreach ($this->files->glob("{$path}/*.php") as $view) {
$this->files->delete($view);
}
$this->info('Compiled views cleared!');
} | Execute the console command.
@return void | entailment |
public function retrieveById($identifier)
{
$user = $this->conn->table($this->table)->find($identifier);
if (! is_null($user)) {
return new GenericUser((array) $user);
}
} | Retrieve a user by their unique identifier.
@param mixed $identifier
@return \Nova\Auth\UserInterface|null | entailment |
public function retrieveByToken($identifier, $token)
{
$user = $this->conn->table($this->table)
->where('id', $identifier)
->where('remember_token', $token)
->first();
if (! is_null($user)) {
return new GenericUser((array) $user);
}
} | Retrieve a user by by their unique identifier and "remember me" token.
@param mixed $identifier
@param string $token
@return \Nova\Auth\UserInterface|null | entailment |
public function retrieveByCredentials(array $credentials)
{
// First we will add each credential element to the query as a where clause.
// Then we can execute the query and, if we found a user, return it in a
// generic "user" object that will be utilized by the Guard instances.
$query = $this->conn->table($this->table);
foreach ($credentials as $key => $value) {
if (! Str::contains($key, 'password')) {
$query->where($key, $value);
}
}
// Now we are ready to execute the query to see if we have an user matching
// the given credentials. If not, we will just return nulls and indicate
// that there are no matching users for these given credential arrays.
$user = $query->first();
if (! is_null($user)) {
return new GenericUser((array) $user);
}
} | Retrieve a user by the given credentials.
@param array $credentials
@return \Nova\Auth\UserInterface|null | entailment |
public function validateCredentials(UserInterface $user, array $credentials)
{
$plain = $credentials['password'];
return $this->hasher->check($plain, $user->getAuthPassword());
} | Validate a user against the given credentials.
@param \Auth\UserInterface $user
@param array $credentials
@return bool | entailment |
public function indexAction($categorySlug, $questionSlug)
{
if (!$categorySlug || !$questionSlug) {
$redirect = $this->generateRedirectToDefaultSelection($categorySlug, $questionSlug);
if ($redirect) {
return $redirect;
}
}
// Otherwise get the selected category and/or question as usual
$questions = array();
$categories = $this->getCategoryRepository()->retrieveActive();
$selectedCategory = $this->getSelectedCategory($categorySlug);
$selectedQuestion = $this->getSelectedQuestion($questionSlug);
if ($selectedCategory) {
$questions = $selectedCategory->getSortedQuestions();
}
// Throw 404 if there is no category in the database
if (!$categories) {
throw $this->createNotFoundException('You need at least 1 active faq category in the database');
}
return $this->render(
'GenjFaqBundle:Faq:index.html.twig',
array(
'categories' => $categories,
'questions' => $questions,
'selectedCategory' => $selectedCategory,
'selectedQuestion' => $selectedQuestion
)
);
} | Default index.
list all questions + answers show/hide can be defined in the template
@param string $categorySlug
@param string $questionSlug
@throws \Symfony\Component\HttpKernel\Exception\NotFoundException
@return \Symfony\Component\HttpFoundation\Response | entailment |
protected function generateRedirectToDefaultSelection($categorySlug, $questionSlug)
{
$doRedirect = false;
$config = $this->container->getParameter('genj_faq');
if (!$categorySlug && $config['select_first_category_by_default']) {
$firstCategory = $this->getCategoryRepository()->retrieveFirst();
if ($firstCategory instanceof \Genj\FaqBundle\Entity\Category) {
$categorySlug = $firstCategory->getSlug();
$doRedirect = true;
} else {
throw $this->createNotFoundException('Tried to open the first faq category by default, but there was none.');
}
}
if (!$questionSlug && $config['select_first_question_by_default']) {
$firstQuestion = $this->getQuestionRepository()->retrieveFirstByCategorySlug($categorySlug);
if ($firstQuestion instanceof \Genj\FaqBundle\Entity\Question) {
$questionSlug = $firstQuestion->getSlug();
$doRedirect = true;
} else {
throw $this->createNotFoundException('Tried to open the first faq question by default, but there was none.');
}
}
if ($doRedirect) {
return $this->redirect(
$this->generateUrl('genj_faq_faq_index', array('categorySlug' => $categorySlug, 'questionSlug' => $questionSlug), true)
);
}
return false;
} | Open first category or question if none was selected so far.
@param string $categorySlug
@param string $questionSlug
@return \Symfony\Component\HttpFoundation\RedirectResponse
@throws \Symfony\Component\HttpKernel\Exception\NotHttpException | entailment |
protected function getSelectedQuestion($questionSlug = null)
{
$selectedQuestion = null;
if ($questionSlug !== null) {
$selectedQuestion = $this->getQuestionRepository()->findOneBySlug($questionSlug);
}
return $selectedQuestion;
} | @param string $questionSlug
@return \Genj\FaqBundle\Entity\Question | entailment |
protected function getSelectedCategory($categorySlug = null)
{
$selectedCategory = null;
if ($categorySlug !== null) {
$selectedCategory = $this->getCategoryRepository()->findOneBy(array('isActive' => true, 'slug' => $categorySlug));
}
return $selectedCategory;
} | @param string $categorySlug
@return \Genj\FaqBundle\Entity\Category | entailment |
public function addHeaderRequest($name, $value, $override = true)
{
if (is_scalar($name) && is_scalar($value)) {
$key = strtolower($name);
if ($override === true || !isset($this->requestHeader[$key])) {
$this->requestHeader[$key] = array('name' => $name,
'value' => $value,
);
return true;
}
return false;
}
throw new InvalidArgumentException('Name and value MUST be scalar');
} | Adiciona um campo de cabeçalho para ser enviado com a requisição.
@param string $name Nome do campo de cabeçalho.
@param string $value Valor do campo de cabeçalho.
@param bool $override Indica se o campo deverá ser sobrescrito caso já tenha sido definido.
@return bool
@throws \InvalidArgumentException Se o nome ou o valor do campo não forem valores scalar. | entailment |
public function load($environment = null)
{
if ($environment == 'production') $environment = null;
if (! $this->files->exists($path = $this->getFile($environment))) {
return array();
} else {
return $this->files->getRequire($path);
}
} | Load the environment variables for the given environment.
@param string $environment
@return array | entailment |
public function listen($connection, $queue, $delay, $memory, $timeout = 60)
{
$process = $this->makeProcess($connection, $queue, $delay, $memory, $timeout);
while(true) {
$this->runProcess($process, $memory);
}
} | Listen to the given queue connection.
@param string $connection
@param string $queue
@param string $delay
@param string $memory
@param int $timeout
@return void | entailment |
public function runProcess(Process $process, $memory)
{
$process->run(function($type, $line)
{
$this->handleWorkerOutput($type, $line);
});
// Once we have run the job we'll go check if the memory limit has been
// exceeded for the script. If it has, we will kill this script so a
// process managers will restart this with a clean slate of memory.
if ($this->memoryExceeded($memory)) {
$this->stop();
return;
}
} | Run the given process.
@param \Symfony\Component\Process\Process $process
@param int $memory
@return void | entailment |
public function makeProcess($connection, $queue, $delay, $memory, $timeout)
{
$string = $this->workerCommand;
// If the environment is set, we will append it to the command string so the
// workers will run under the specified environment. Otherwise, they will
// just run under the production environment which is not always right.
if (isset($this->environment)) {
$string .= ' --env=' .$this->environment;
}
// Next, we will just format out the worker commands with all of the various
// options available for the command. This will produce the final command
// line that we will pass into a Symfony process object for processing.
$command = sprintf(
$string, $connection, $queue, $delay,
$memory, $this->sleep, $this->maxTries
);
return new Process($command, $this->commandPath, null, null, $timeout);
} | Create a new Symfony process for the worker.
@param string $connection
@param string $queue
@param int $delay
@param int $memory
@param int $timeout
@return \Symfony\Component\Process\Process | entailment |
public function boot()
{
$db = $this->app['db'];
$events = $this->app['events'];
// Setup the ORM Model.
Model::setConnectionResolver($db);
Model::setEventDispatcher($events);
} | Bootstrap the Application events.
@return void | entailment |
public function register()
{
$this->app->bindShared('db.factory', function($app)
{
return new ConnectionFactory($app);
});
$this->app->bindShared('db', function($app)
{
return new DatabaseManager($app, $app['db.factory']);
});
} | Register the Service Provider.
@return void | entailment |
private function transformPathAnchors(PathInterface $path, StyleInterface $style)
{
$anchors = $path->getAnchors();
$origin = $style->getTransformOrigin();
$transformations = $style->getTransformations();
if ($origin) {
$bounds = $path->getBounds();
//Map relative values to absolute values
$origin = new Point($bounds->getWidth() * $origin->getX(), $bounds->getHeight() * $origin->getY());
}
return array_map(function (AnchorInterface $anchor) use ($transformations, $origin) {
//Transform the anchor
foreach ($transformations as $transformation) {
$anchor = $transformation->transformAnchor($anchor, $origin);
}
return $anchor;
}, $anchors);
} | @param PathInterface $path
@param StyleInterface $style
@return AnchorInterface[] | entailment |
public function handle()
{
$name = $this->argument('name');
if ($this->option('model')) {
$this->call('make:model', ['name' => $this->option('model')]);
}
parent::handle();
if (!str_contains($name, '\\')) {
$name = '\\App\\Observers\\'. $name;
}
if ($this->files->exists(app_path('/Providers/EloquentEventServiceProvider.php')) && $this->option('model')) {
$provider = $this->files->get(app_path('/Providers/EloquentEventServiceProvider.php'));
$replacement = str_replace_last(
'class);',
"class);\n\t\t{$this->option('model')}::observe($name::class);",
$provider
);
$this->files->put(app_path('/Providers/EloquentEventServiceProvider.php'), $replacement);
}
if ($this->option('model') && !$this->files->exists(app_path('/Providers/EloquentEventServiceProvider.php'))) {
$this->call('make:provider', ['name' => 'EloquentEventServiceProvider']);
$provider = $this->files->get(app_path('/Providers/EloquentEventServiceProvider.php'));
$replacement = str_replace('public function boot()
{
//', "public function boot()\n\t{\n\t\t{$this->option('model')}::observe($name::class);", $provider);
$this->files->put(app_path('/Providers/EloquentEventServiceProvider.php'), $replacement);
$this->registerProvider();
}
} | Execute the console command.
@return mixed | entailment |
public function register()
{
$this->app->singleton('command.queue.table', function ($app) {
return new TableCommand($app['files']);
});
$this->app->bindShared('command.queue.failed', function()
{
return new ListFailedCommand;
});
$this->app->bindShared('command.queue.retry', function()
{
return new RetryCommand;
});
$this->app->bindShared('command.queue.forget', function()
{
return new ForgetFailedCommand;
});
$this->app->bindShared('command.queue.flush', function()
{
return new FlushFailedCommand;
});
$this->app->bindShared('command.queue.failed-table', function($app)
{
return new FailedTableCommand($app['files']);
});
$this->commands(
'command.queue.table', 'command.queue.failed', 'command.queue.retry',
'command.queue.forget', 'command.queue.flush', 'command.queue.failed-table'
);
} | Register the service provider.
@return void | entailment |
public function define($ability, $callback)
{
if (is_callable($callback)) {
$this->abilities[$ability] = $callback;
} elseif (is_string($callback) && Str::contains($callback, '@')) {
$this->abilities[$ability] = $this->buildAbilityCallback($callback);
} else {
throw new InvalidArgumentException("Callback must be a callable or a 'Class@method' string.");
}
return $this;
} | Define a new ability.
@param string $ability
@param callable|string $callback
@return $this
@throws \InvalidArgumentException | entailment |
public function allows($ability, $arguments = array())
{
if (! is_array($arguments)) {
$arguments = array_slice(func_get_args(), 1);
}
return $this->check($ability, $arguments);
} | Determine if the given ability should be granted for the current user.
@param string $ability
@param array|mixed $arguments
@return bool | entailment |
public function denies($ability, $arguments = array())
{
if (! is_array($arguments)) {
$arguments = array_slice(func_get_args(), 1);
}
return ! $this->check($ability, $arguments);
} | Determine if the given ability should be denied for the current user.
@param string $ability
@param array|mixed $arguments
@return bool | entailment |
public function check($ability, $arguments = array())
{
if (! is_array($arguments)) {
$arguments = array_slice(func_get_args(), 1);
}
try {
$result = $this->raw($ability, $arguments);
}
catch (AuthorizationException $e) {
return false;
}
return (bool) $result;
} | Determine if the given ability should be granted for the current user.
@param string $ability
@param array|mixed $arguments
@return bool | entailment |
public function authorize($ability, $arguments = array())
{
if (! is_array($arguments)) {
$arguments = array_slice(func_get_args(), 1);
}
$result = $this->raw($ability, $arguments);
if ($result instanceof Response) {
return $result;
}
return $result ? $this->allow() : $this->deny();
} | Determine if the given ability should be granted for the current user.
@param string $ability
@param array|mixed $arguments
@return \Nova\Auth\Access\Response
@throws \Nova\Auth\Access\AuthorizationException | entailment |
protected function raw($ability, array $arguments)
{
if (is_null($user = $this->resolveUser())) {
return false;
}
$result = $this->callBeforeCallbacks($user, $ability, $arguments);
if (is_null($result)) {
$result = $this->callAuthCallback($user, $ability, $arguments);
}
$this->callAfterCallbacks($user, $ability, $arguments, $result);
return $result;
} | Get the raw result for the given ability for the current user.
@param string $ability
@param array $arguments
@return mixed | entailment |
protected function callAuthCallback(User $user, $ability, array $arguments)
{
$callback = $this->resolveAuthCallback($user, $ability, $arguments);
return call_user_func_array($callback, array_merge(array($user), $arguments));
} | Resolve and call the appropriate authorization callback.
@param \Nova\Auth\UserInterface $user
@param string $ability
@param array $arguments
@return bool | entailment |
protected function callBeforeCallbacks(User $user, $ability, array $arguments)
{
$arguments = array_merge(array($user, $ability), $arguments);
foreach ($this->beforeCallbacks as $callback) {
if (! is_null($result = call_user_func_array($callback, $arguments))) {
return $result;
}
}
} | Call all of the before callbacks and return if a result is given.
@param \Nova\Auth\UserInterface $user
@param string $ability
@param array $arguments
@return bool|null | entailment |
protected function callAfterCallbacks(User $user, $ability, array $arguments, $result)
{
$arguments = array_merge(array($user, $ability, $result), $arguments);
foreach ($this->afterCallbacks as $callback) {
call_user_func_array($callback, $arguments);
}
} | Call all of the after callbacks with check result.
@param \Nova\Auth\UserInterface $user
@param string $ability
@param array $arguments
@param bool $result
@return void | entailment |
protected function firstArgumentCorrespondsToPolicy(array $arguments)
{
if (! isset($arguments[0])) {
return false;
}
$argument = $arguments[0];
if (is_object($argument)) {
$class = get_class($argument);
return isset($this->policies[$class]);
}
return is_string($argument) && isset($this->policies[$argument]);
} | Determine if the first argument in the array corresponds to a policy.
@param array $arguments
@return bool | entailment |
protected function resolvePolicyCallback(User $user, $ability, array $arguments)
{
return function () use ($user, $ability, $arguments)
{
$class = head($arguments);
if (method_exists($instance = $this->getPolicyFor($class), 'before')) {
$parameters = array_merge(array($user, $ability), $arguments);
if (! is_null($result = call_user_func_array(array($instance, 'before'), $parameters))) {
return $result;
}
}
if (! method_exists($instance, $method = Str::camel($ability))) {
return false;
}
return call_user_func_array(array($instance, $method), array_merge(array($user), $arguments));
};
} | Resolve the callback for a policy check.
@param \Nova\Auth\UserInterface $user
@param string $ability
@param array $arguments
@return callable | entailment |
public function forUser($user)
{
$callback = function () use ($user)
{
return $user;
};
return new static(
$this->container, $callback, $this->abilities,
$this->policies, $this->beforeCallbacks, $this->afterCallbacks
);
} | Get a guard instance for the given user.
@param \Nova\Auth\UserInterface|mixed $user
@return static | entailment |
public static function get($value)
{
if ($value instanceof ColorInterface)
return $value;
if (empty($value))
return new RgbColor(0,0,0);
if (is_int($value))
return self::parseInt($value);
if ($color = self::parseName($value))
return $color;
if ($color = self::parseHexString($value))
return $color;
if ($color = self::parseFunctionString($value))
return $color;
return null;
} | @param mixed $value
@return ColorInterface | entailment |
public static function getDifference(ColorInterface $color, ColorInterface $compareColor, array $weights = [1,1,1])
{
$color = $color->toLab();
$compareColor = $compareColor->toLab();
$weights = array_pad($weights, 3, 1);
$kl = $weights[0];
$kc = $weights[1];
$kh = $weights[2];
$l1 = $color->getL();
$a1 = $color->getA();
$b1 = $color->getB();
$l2 = $compareColor->getL();
$a2 = $compareColor->getA();
$b2 = $compareColor->getB();
$c1 = sqrt($a1 * $a1 + $b1 * $b1);
$c2 = sqrt($a2 * $a2 + $b2 * $b2);
$cx = ($c1 + $c2) / 2;
$gx = 0.5 * (1 - sqrt(($cx ** 7) / (($cx ** 7) + (25 ** 7))));
$nn = (1 + $gx) * $a1;
$c1 = sqrt($nn * $nn + $b1 * $b1);
$h1 = self::cieLabToHue($nn, $b1);
$nn = (1 + $gx) * $a2;
$c2 = sqrt($nn * $nn + $b2 * $b2);
$h2 = self::cieLabToHue($nn, $b2);
$dl = $l2 - $l1;
$dc = $c2 - $c1;
$dh = 0;
if (($c1 * $c2) !== 0) {
$nn = round($h1 - $h2, 12);
if (abs($nn) <= 180) {
$dh = $h2 - $h1;
} else {
if ($nn > 180)
$dh = $h2 - $h1 - 360;
else
$dh = $h2 - $h1 + 360;
}
}
$dh = 2 * sqrt($c1 * $c2) * sin(deg2rad($dh / 2));
$lx = ($l1 + $l2) / 2;
$cy = ($c1 + $c2) / 2;
$hx = $h1 + $h2;
if (($c1 * $c2) !== 0) {
$nn = abs(round($h1 - $h2, 12));
if ($nn > 180) {
if (($h2 + $h1) < 360)
$hx = $h1 + $h2 + 360;
else
$hx = $h1 + $h2 - 360;
} else {
$hx = $h1 + $h2;
}
$hx /= 2;
}
$tx = 1 - 0.17 * cos(deg2rad($hx - 30)) + 0.24 * cos(deg2rad(2 * $hx)) + 0.32
* cos(deg2rad(3 * $hx + 6)) - 0.20 * cos(deg2rad(4 * $hx - 63));
$ph = 30 * exp(-(($hx - 275) / 25) * (($hx - 275) / 25));
$rc = 2 * sqrt(($cy ** 7) / (($cy ** 7) + (25 ** 7)));
$sl = 1 + ((0.015 * (($lx - 50) * ($lx - 50))) / sqrt(20 + (($lx - 50) * ($lx - 50))));
$sc = 1 + 0.045 * $cy;
$sh = 1 + 0.015 * $cy * $tx;
$rt = -sin(deg2rad(2 * $ph)) * $rc;
$dl /= ($kl * $sl);
$dc /= ($kc * $sc);
$dh /= ($kh * $sh);
return sqrt(($dl ** 2) + ($dc ** 2) + ($dh ** 2) + $rt * $dc * $dh);
} | http://www.easyrgb.com/index.php?X=DELT&H=05#text5 | entailment |
public function handle()
{
$iron = $this->container['queue']->connection();
if ( ! $iron instanceof IronQueue)
{
throw new RuntimeException("Iron.io based queue must be default.");
}
$iron->getIron()->updateQueue($this->argument('queue'), $this->getQueueOptions());
$this->line('<info>Queue subscriber added:</info> <comment>'.$this->argument('url').'</comment>');
} | Execute the console command.
@return void
@throws \RuntimeException | entailment |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.