Example #1
1
 /**
  * {@inheritdoc}
  */
 public function writeItem(array $item)
 {
     $this->queue->push($item);
     if (count($this->queue) >= $this->size) {
         $this->flush();
     }
 }
Example #2
1
 /**
  * Translate array sequence of tokens from infix to 
  * Reverse Polish notation (RPN) which representing mathematical expression.
  * 
  * @param array $tokens Collection of Token intances
  * @return array Collection of Token intances
  * @throws InvalidArgumentException
  */
 public function translate(array $tokens)
 {
     $this->operatorStack = new SplStack();
     $this->outputQueue = new SplQueue();
     for ($i = 0; $i < count($tokens); $i++) {
         $token = $tokens[$i];
         switch ($token->getType()) {
             case Token::T_OPERAND:
                 $this->outputQueue->enqueue($token);
                 break;
             case Token::T_OPERATOR:
             case Token::T_FUNCTION:
                 $o1 = $token;
                 $isUnary = $this->isPreviousTokenOperator($tokens, $i) || $this->isPreviousTokenLeftParenthesis($tokens, $i) || $this->hasPreviousToken($i) === false;
                 if ($isUnary) {
                     if ($o1->getValue() === '-' || $o1->getValue() === '+') {
                         $o1 = new Operator($o1->getValue() . 'u', 3, Operator::O_NONE_ASSOCIATIVE);
                     } else {
                         if (!$o1 instanceof FunctionToken) {
                             throw new \InvalidArgumentException("Syntax error: operator '" . $o1->getValue() . "' cannot be used as a unary operator or with an operator as an operand.");
                         }
                     }
                 } else {
                     while ($this->hasOperatorInStack() && ($o2 = $this->operatorStack->top()) && $o1->hasLowerPriority($o2)) {
                         $this->outputQueue->enqueue($this->operatorStack->pop());
                     }
                 }
                 $this->operatorStack->push($o1);
                 break;
             case Token::T_LEFT_BRACKET:
                 $this->operatorStack->push($token);
                 break;
             case Token::T_RIGHT_BRACKET:
                 if ($this->isPreviousTokenOperator($tokens, $i)) {
                     throw new \InvalidArgumentException('Syntax error: an operator cannot be followed by a right parenthesis.');
                 } elseif ($this->isPreviousTokenLeftParenthesis($tokens, $i)) {
                     throw new \InvalidArgumentException('Syntax error: empty parenthesis.');
                 }
                 while (!$this->operatorStack->isEmpty() && Token::T_LEFT_BRACKET != $this->operatorStack->top()->getType()) {
                     $this->outputQueue->enqueue($this->operatorStack->pop());
                 }
                 if ($this->operatorStack->isEmpty()) {
                     throw new \InvalidArgumentException('Syntax error: mismatched parentheses.');
                 }
                 $this->operatorStack->pop();
                 break;
             default:
                 throw new \InvalidArgumentException(sprintf('Invalid token detected: %s.', $token));
                 break;
         }
     }
     while ($this->hasOperatorInStack()) {
         $this->outputQueue->enqueue($this->operatorStack->pop());
     }
     if (!$this->operatorStack->isEmpty()) {
         throw new InvalidArgumentException('Syntax error: mismatched parentheses or misplaced number.');
     }
     return iterator_to_array($this->outputQueue);
 }
 /**
  * @param $type
  * @param $message
  * @param null $data
  */
 public function log($type, $message, $data = null)
 {
     if (!$this->traitErrorLog) {
         $this->traitErrorLog = new \SplQueue();
     }
     $this->traitErrorLog->enqueue(['type' => $type, 'message' => $message, 'data' => $data]);
 }
Example #4
0
 /**
  * Запуск в работу
  *
  * @param mixed $data данные для задачи
  * @param bool $wait ожидание результата
  *@return mixed результатs
  */
 public function run($data = null, $wait = true)
 {
     // добавляем задачу
     if ($data) {
         $this->add($data);
     }
     // обработка
     while ($this->_Messages->count()) {
         $message = $this->_Messages->pop();
         $this->_Channel->basic_publish($message, '', $this->_queue());
         // массив запущенных задач
         $this->_runtime[$message->get('correlation_id')] = time();
     }
     // если есть обработчик ответов, то слушаем его
     if ($this->_cbQueue && $wait) {
         if (method_exists($this, 'onResponse')) {
             $this->_Channel->basic_consume($this->_cbQueue, '', false, true, false, false, [$this, 'onResponse']);
         } else {
             // если же метода нет, но подождать надо, то тут всё просто:
             $this->_Channel->basic_consume($this->_cbQueue, '', false, true, false, false, function (AMQPMessage $Message) {
                 $response = $this->_decode($Message->body);
                 unset($this->_collerations[$Message->get('correlation_id')], $this->_runtime[$Message->get('correlation_id')]);
                 if ($response instanceof \Exception) {
                     throw $response;
                 }
                 return true;
             });
         }
         // ждём
         while (count($this->_collerations)) {
             $this->_Channel->wait();
         }
     }
     return true;
 }
Example #5
0
function bfs_path($graph, $start, $end)
{
    $queue = new SplQueue();
    # Enqueue the path
    $queue->enqueue([$start]);
    $visited = [$start];
    while ($queue->count() > 0) {
        $path = $queue->dequeue();
        # Get the last node on the path
        # so we can check if we're at the end
        $node = $path[sizeof($path) - 1];
        if ($node === $end) {
            return $path;
        }
        foreach ($graph[$node] as $neighbour) {
            if (!in_array($neighbour, $visited)) {
                $visited[] = $neighbour;
                # Build new path appending the neighbour then and enqueue it
                $new_path = $path;
                $new_path[] = $neighbour;
                $queue->enqueue($new_path);
            }
        }
    }
    return false;
}
 /**
  * Solve missionaries and cannibals problem.
  *
  * @return bool
  */
 public function solve()
 {
     $initialState = new State(3, 3, 0, 0, 'left');
     $initialNode = new Node($initialState, null, null);
     if ($initialNode->state->isGoalState()) {
         $this->displayNodeInfo($initialNode);
         return true;
     }
     $queue = new SplQueue();
     $queue->push($initialNode);
     $explored = [];
     while (true) {
         if ($queue->isEmpty()) {
             return false;
             //nothing found
         }
         $node = $queue->pop();
         $this->displayNodeInfo($node);
         array_push($explored, $node->state);
         if ($node->state->isGoalState()) {
             return true;
         }
         //get all action and states available
         $states = $node->state->getNextStates();
         foreach ($states as $stateNode) {
             if (!$stateNode->state->isValidState()) {
                 continue;
             }
             if (!in_array($stateNode->state, $explored)) {
                 $queue->push($stateNode);
             }
         }
     }
 }
Example #7
0
 /**
  * @return LogEvent
  */
 public function getLoggedEvent() : LogEvent
 {
     if (!$this->hasLoggedEvents()) {
         throw new \LogicException('No more events logged!');
     }
     return $this->logs->dequeue();
 }
 public function onExit($status)
 {
     if ($this->pendingRequests->count() > 0) {
         $nextExpectedTest = $this->pendingRequests->dequeue();
         $this->distributor->testCompleted($this, TestResult::errorFromRequest($nextExpectedTest, "Worker{$this->id} died\n{$this->testErr}"));
     }
 }
Example #9
0
 /** @return Error|null */
 public static function pop()
 {
     if (!self::$errors) {
         return null;
     }
     return self::$errors->count() > 0 ? self::$errors->dequeue() : null;
 }
Example #10
0
 /**
  * Implements the when() method of the Promise interface.
  * 
  * @param callable $onResolved
  */
 public function when(callable $onResolved)
 {
     switch ($this->state) {
         case Awaitable::RESOLVED:
             try {
                 $onResolved(null, ...$this->result);
             } catch (\Throwable $ex) {
                 Loop::defer(function () use($ex) {
                     throw $ex;
                 });
             }
             break;
         case Awaitable::FAILED:
             try {
                 $onResolved($this->result);
             } catch (\Throwable $ex) {
                 Loop::defer(function () use($ex) {
                     throw $ex;
                 });
             }
             break;
         default:
             if (!$this->callbacks) {
                 $this->callbacks = new \SplQueue();
                 $this->callbacks->setIteratorMode(\SplQueue::IT_MODE_FIFO | \SplQueue::IT_MODE_DELETE);
             }
             $this->callbacks->enqueue($onResolved);
     }
 }
Example #11
0
 /**
  * @return string[] names of any dependencies involved in dependency cycle[s] (or that depend
  *     upon those in the cycle)
  */
 public function list_dependency_cycles()
 {
     $dep_counts = $this->dependency_counts();
     $depends_on = $this->reverse_graph();
     $deps_met_queue = new \SplQueue();
     foreach ($dep_counts as $dependency => $count) {
         if ($count === 0) {
             $deps_met_queue->enqueue($dependency);
         }
     }
     // Iteratively resolve dependencies
     $num_removed = 0;
     while (!$deps_met_queue->isEmpty()) {
         $name = $deps_met_queue->dequeue();
         $num_removed++;
         if (!array_key_exists($name, $depends_on)) {
             continue;
         }
         foreach ($depends_on[$name] as $dependant) {
             $dep_counts[$dependant]--;
             if ($dep_counts[$dependant] === 0) {
                 $deps_met_queue->enqueue($dependant);
             }
         }
     }
     // Find the dependencies that couldn't be resolved
     $depends_on_cycle = [];
     foreach ($dep_counts as $dependency => $count) {
         if ($count > 0) {
             $depends_on_cycle[] = $dependency;
         }
     }
     return $depends_on_cycle;
 }
 /**
  * Re-order token stream into reverse polish notation.
  *
  * @param array $tokenList
  *
  * @return array of ComparatorVersions and logical operator tokens
  */
 private function shuntingYard(array $tokenList)
 {
     $operatorStack = new \SplStack();
     $output = new \SplQueue();
     foreach ($tokenList as $token) {
         // Accumulate Versions & Comparators
         if ($token instanceof VersionRangeInterface) {
             $output->enqueue($token);
             // Handle operators
         } elseif ($token instanceof Token) {
             // Loop while the current token has higher precedence then the stack token
             $operator1 = $token;
             while ($this->hasOperator($operatorStack) && ($operator2 = $operatorStack->top()) && $this->hasLowerPrecedence($operator1, $operator2)) {
                 $output->enqueue($operatorStack->pop());
             }
             $operatorStack->push($operator1);
         } else {
             throw new \RuntimeException('Invalid version number');
         }
     }
     // Merge remaining operators onto output list
     while ($this->hasOperator($operatorStack)) {
         $output->enqueue($operatorStack->pop());
     }
     return iterator_to_array($output);
 }
Example #13
0
 /**
  * Copies for the audits and audits_logs table into the elastic search storage.
  *
  * @return bool
  */
 public function main()
 {
     $table = $this->loadModel('Audits');
     $table->hasMany('AuditDeltas');
     $table->schema()->columnType('created', 'string');
     $map = [];
     $meta = [];
     $featureList = function ($element) {
         list($k, $v) = explode(':', $element);
         (yield $k => $v);
     };
     if (!empty($this->params['type-map'])) {
         $map = explode(',', $this->params['type-map']);
         $map = collection($map)->unfold($featureList)->toArray();
     }
     if (!empty($this->params['extra-meta'])) {
         $meta = explode(',', $this->params['extra-meta']);
         $meta = collection($meta)->unfold($featureList)->toArray();
     }
     $from = (new Time($this->params['from']))->modify('midnight');
     $until = (new Time($this->params['until']))->modify('23:59:59');
     $currentId = null;
     $buffer = new \SplQueue();
     $buffer->setIteratorMode(\SplDoublyLinkedList::IT_MODE_DELETE);
     $queue = new \SplQueue();
     $queue->setIteratorMode(\SplDoublyLinkedList::IT_MODE_DELETE);
     $index = ConnectionManager::get('auditlog_elastic')->getConfig('index');
     $eventsFormatter = function ($audit) use($index, $meta) {
         return $this->eventFormatter($audit, $index, $meta);
     };
     $changesExtractor = [$this, 'changesExtractor'];
     $query = $table->find()->where(function ($exp) use($from, $until) {
         return $exp->between('Audits.created', $from, $until, 'datetime');
     })->where(function ($exp) {
         if (!empty($this->params['exclude-models'])) {
             $exp->notIn('Audits.model', explode(',', $this->params['exclude-models']));
         }
         if (!empty($this->params['models'])) {
             $exp->in('Audits.model', explode(',', $this->params['models']));
         }
         return $exp;
     })->matching('AuditDeltas')->order(['Audits.created', 'AuditDeltas.audit_id'])->bufferResults(false)->hydrate(false)->unfold(function ($audit) use($buffer, &$currentId) {
         if ($currentId && $currentId !== $audit['id']) {
             (yield collection($buffer)->toList());
         }
         $currentId = $audit['id'];
         $buffer->enqueue($audit);
     })->map($changesExtractor)->map($eventsFormatter)->unfold(function ($audit) use($queue) {
         $queue->enqueue($audit);
         if ($queue->count() >= 50) {
             (yield collection($queue)->toList());
         }
     });
     $query->each([$this, 'persistBulk']);
     // There are probably some un-yielded results, let's flush them
     $rest = collection(count($buffer) ? [collection($buffer)->toList()] : [])->map($changesExtractor)->map($eventsFormatter)->append($queue);
     $this->persistBulk($rest->toList());
     return true;
 }
 /**
  * {@inheritdoc}
  */
 protected function executePipeline(ConnectionInterface $connection, \SplQueue $commands)
 {
     while (!$commands->isEmpty()) {
         $connection->writeRequest($commands->dequeue());
     }
     $connection->disconnect();
     return array();
 }
Example #15
0
 public function __invoke($id, $service)
 {
     if ($this->middlewares->isEmpty()) {
         return $service;
     }
     $method = $this->middlewares->dequeue();
     return call_user_func($method, $this->container, new Next($this->container, $this->middlewares), $id, $service);
 }
Example #16
0
 /**
  * @param EventInterface $event
  * @param bool           $asynchronously
  */
 public function dispatch(EventInterface $event, $asynchronously = false)
 {
     if (!$asynchronously) {
         $this->scope->emit($event->getName(), [$event]);
     } else {
         $this->queue->enqueue($event);
         $this->run();
     }
 }
 private function filterMetadataStack(\SplDoublyLinkedList $metadataStack)
 {
     $filteredMetadataStack = new \SplQueue();
     foreach ($metadataStack as $curProperty) {
         if ($curProperty instanceof PropertyMetadata) {
             $filteredMetadataStack->unshift($curProperty);
         }
     }
     return $filteredMetadataStack;
 }
Example #18
0
 /**
  *
  * Adds a route to the router
  *
  * @param $callable
  * @param $conditions
  * @author Tim Perry
  */
 public function addRoute($callable, $conditions)
 {
     $route = clone $this->routePrototype;
     $route->setCallable($callable);
     if (!is_array($conditions)) {
         $conditions = array($conditions);
     }
     $route->addConditionsFromArray($this->replaceFilterFunctions($conditions));
     $this->routes->enqueue($route);
 }
Example #19
0
 /**
  * @inheritDoc
  */
 public function getQuery(Driver $driver, $link)
 {
     if (!$this->pool->contains($link)) {
         throw new \OutOfBoundsException(sprintf('Undefined %s in the pooling controller.', $driver->info($link)));
     }
     if (!$this->waiting->isEmpty()) {
         return $this->waiting->dequeue();
     }
     $this->idle->enqueue($link);
 }
 protected function shouldShutDownMessenger(Messenger $messenger)
 {
     if ($this->callQueue->count() == 0 && $this->pool->count() > $this->options['min_size']) {
         unset($this->coreMessengerMapping[spl_object_hash($messenger)]);
         $this->pool->detach($messenger);
         $messenger->softTerminate();
         return;
     }
     $this->readyPool->enqueue($messenger);
 }
Example #21
0
 /**
  * @covers Gliph\Traversal\DepthFirst::traverse
  */
 public function testProvideQueueAsStartPoint()
 {
     extract($this->v);
     $queue = new \SplQueue();
     $queue->push($a);
     $queue->push($e);
     $this->g->addVertex($a);
     $this->g->addVertex($e);
     DepthFirst::traverse($this->g, new DepthFirstNoOpVisitor(), $queue);
 }
Example #22
0
 private function tick()
 {
     while (!$this->tick->isEmpty() && !$this->main->isFinished()) {
         $task = $this->nextTask();
         $task->run();
         if ($task->isBlocked()) {
             $this->addFutureTask($task);
         }
     }
 }
Example #23
0
 /**
  * {@inheritdoc}
  */
 public function start()
 {
     if (isset($this->deferred)) {
         throw new \RuntimeException('Tasks is already started');
     }
     $this->deferred = new Deferred();
     $this->process->start(function () {
         $this->outputBuffer->enqueue(func_get_args());
     });
     return $this->deferred->promise();
 }
 public function testForValidValues()
 {
     $var = new \SplQueue();
     $var->push(1);
     $var->push(2);
     $var->push(3);
     $data = new VariableWrapper(get_class($var), $var);
     $result = $this->inspector->get($data);
     $this->assertInstanceOf('Ladybug\\Plugin\\Extra\\Type\\CollectionType', $result);
     $this->assertCount(3, $result);
 }
Example #25
0
 /**
  * @param callable $func
  * @return callable
  */
 protected function filesystemResultHandler(callable $func)
 {
     return function ($mixed) use($func) {
         if ($this->callQueue->count() == 0) {
             $this->callQueueActive = false;
         } else {
             $this->processQueue();
         }
         return $func($mixed);
     };
 }
Example #26
0
 /**
  * @param Message $chapterCommand
  * @param mixed $data
  * @param ChapterLogger $chapterLogger
  */
 public function __invoke(Message $chapterCommand, $data, ChapterLogger $chapterLogger)
 {
     $done = $this->done;
     // No middleware remains; done
     if ($this->queue->isEmpty()) {
         return $done($chapterCommand, $data, $chapterLogger);
     }
     $stage = $this->queue->dequeue();
     $executeStage = $this->executeStage;
     return $executeStage($stage, $chapterCommand, $data, $chapterLogger, $this);
 }
 /**
  * Once a connection has finished being used...
  * @param Connection $connection
  */
 public function releaseConnection(Connection $connection)
 {
     // If we have any promises waiting for the connection, pass it along.
     if ($this->waiting->count() > 0) {
         $cb = $this->waiting->dequeue();
         $cb($connection);
         return;
     }
     // Otherwise, move it to the idle queue.
     $this->available->enqueue($connection);
 }
Example #28
0
 protected function addRulesForPackage(PackageInterface $package)
 {
     $workQueue = new \SplQueue();
     $workQueue->enqueue($package);
     while (!$workQueue->isEmpty()) {
         $package = $workQueue->dequeue();
         if (isset($this->addedMap[$package->getId()])) {
             continue;
         }
         $this->addedMap[$package->getId()] = true;
         foreach ($package->getRequires() as $link) {
             $possibleRequires = $this->pool->whatProvides($link->getTarget(), $link->getConstraint());
             $this->addRule(RuleSet::TYPE_PACKAGE, $rule = $this->createRequireRule($package, $possibleRequires, Rule::RULE_PACKAGE_REQUIRES, $link));
             foreach ($possibleRequires as $require) {
                 $workQueue->enqueue($require);
             }
         }
         foreach ($package->getConflicts() as $link) {
             $possibleConflicts = $this->pool->whatProvides($link->getTarget(), $link->getConstraint());
             foreach ($possibleConflicts as $conflict) {
                 $this->addRule(RuleSet::TYPE_PACKAGE, $this->createConflictRule($package, $conflict, Rule::RULE_PACKAGE_CONFLICT, $link));
             }
         }
         $isInstalled = isset($this->installedMap[$package->getId()]);
         foreach ($package->getReplaces() as $link) {
             $obsoleteProviders = $this->pool->whatProvides($link->getTarget(), $link->getConstraint());
             foreach ($obsoleteProviders as $provider) {
                 if ($provider === $package) {
                     continue;
                 }
                 if (!$this->obsoleteImpossibleForAlias($package, $provider)) {
                     $reason = $isInstalled ? Rule::RULE_INSTALLED_PACKAGE_OBSOLETES : Rule::RULE_PACKAGE_OBSOLETES;
                     $this->addRule(RuleSet::TYPE_PACKAGE, $this->createConflictRule($package, $provider, $reason, $link));
                 }
             }
         }
         $obsoleteProviders = $this->pool->whatProvides($package->getName(), null);
         foreach ($obsoleteProviders as $provider) {
             if ($provider === $package) {
                 continue;
             }
             if ($package instanceof AliasPackage && $package->getAliasOf() === $provider) {
                 $this->addRule(RuleSet::TYPE_PACKAGE, $rule = $this->createRequireRule($package, array($provider), Rule::RULE_PACKAGE_ALIAS, $package));
             } elseif (!$this->obsoleteImpossibleForAlias($package, $provider)) {
                 $reason = $package->getName() == $provider->getName() ? Rule::RULE_PACKAGE_SAME_NAME : Rule::RULE_PACKAGE_IMPLICIT_OBSOLETES;
                 $this->addRule(RuleSet::TYPE_PACKAGE, $rule = $this->createConflictRule($package, $provider, $reason, $package));
             }
         }
     }
 }
Example #29
0
 /**
  * @param Request $request
  * @param Response $response
  * @param callable[] ...$callables unshift callables (top priority)
  * @return Response
  */
 public function __invoke(Request $request, Response $response, ...$callables)
 {
     while ($callable = array_pop($callables)) {
         $this->queue->unshift($callable);
     }
     if ($this->queue->isEmpty()) {
         return $response;
     }
     $callable = $this->resolve($this->queue->dequeue());
     if (is_callable($callable)) {
         return call_user_func($callable, $request, $response, $this);
     } else {
         throw new \UnexpectedValueException();
     }
 }
 /**
  * Close the writer
  *
  * @return void
  */
 public function shutdown()
 {
     while (!$this->buffer->isEmpty()) {
         $this->buffer->dequeue();
     }
     $this->writer->shutdown();
 }