示例#1
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;
 }
示例#2
0
 /**
  * Gets a connection from the pool. It will cycle through the existent
  * connections.
  *
  * @return Connection
  */
 public function getConnection()
 {
     if ($chosenConn = $this->connections->pop()) {
         $this->connections->push($chosenConn);
         return $chosenConn;
     }
 }
示例#3
0
 /**
  * Close the channel, this operation will terminate all receivers that cannot receive any data.
  * 
  * Closing a closed channel has no effect and does not throw an error!
  * 
  * @param \Throwable $e Error will be propagated to all receivers that cannot receive a buffered value anymore.
  */
 public function close(\Throwable $e = null)
 {
     if ($this->closed) {
         return;
     }
     $this->closed = $e ?? true;
     if ($this->generator) {
         $this->generator->cancel($e ?? new \RuntimeException('Channel closed'));
     }
     // Dispose of queued receivers that cannot receive a value from the channel.
     $sources = ($this->senders ? $this->countActiveSubscriptions($this->senders) : 0) + ($this->buffer ? $this->buffer->count() : 0);
     $sinks = $this->receivers ? $this->countActiveSubscriptions($this->receivers) : 0;
     $fails = new \SplStack();
     $fails->setIteratorMode(\SplStack::IT_MODE_LIFO | \SplStack::IT_MODE_DELETE);
     while ($sinks > $sources) {
         $receiver = $this->receivers->pop();
         if ($receiver->active) {
             $sinks--;
             $fails->push($receiver);
         }
     }
     foreach ($fails as $subscription) {
         if ($e) {
             $subscription->fail($e);
         } else {
             $subscription->resolve($subscription->data);
         }
     }
 }
 /**
  * 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);
             }
         }
     }
 }
示例#5
0
 /**
  * Advance the internal collection pointer, and return the current value.
  *
  * @return  void
  */
 public function next()
 {
     $this->_current = null;
     if (0 === count($this->_stack)) {
         return;
     }
     while (0 === $this->_pop->top()) {
         $this->_pop->pop();
         $this->_path->pop();
         $this->_pop->push($this->_pop->pop() - 1);
     }
     list($behavior, $state) = array_values($this->_stack->pop());
     switch ($state) {
         case static::STATE_REQUIRES:
             ++$this->_key;
             if (true === $behavior->clauseExists('requires')) {
                 $this->_current = $behavior->getClause('requires');
                 $this->_path->push($this->_current);
             } else {
                 $this->_current = true;
                 $this->_path->push(null);
             }
             if (true === $behavior->clauseExists('behavior')) {
                 $behaviors = $behavior->getClause('behavior')->getIterator();
                 $this->_stack->push(['behavior' => $behavior, 'state' => static::STATE_BEHAVIOR]);
                 $this->_stack->push(['behavior' => $behaviors, 'state' => static::STATE_BEHAVIOR]);
                 $this->_pop->push(count($behaviors) + 2 * $behavior->clauseExists('default'));
             } else {
                 $this->_stack->push(['behavior' => $behavior, 'state' => static::STATE_ENSURES]);
                 $this->_pop->push(2);
                 $this->next();
             }
             break;
         case static::STATE_BEHAVIOR:
             if (true === $behavior->valid()) {
                 $this->_stack->push(['behavior' => $behavior, 'state' => static::STATE_BEHAVIOR]);
                 $this->_stack->push(['behavior' => $behavior->current(), 'state' => static::STATE_REQUIRES]);
                 $behavior->next();
                 $this->next();
                 break;
             }
             list($parentBehavior, ) = array_values($this->_stack->pop());
             if (true === $parentBehavior->clauseExists('default')) {
                 $this->_stack->push(['behavior' => $parentBehavior->getClause('default'), 'state' => static::STATE_ENSURES]);
             }
             $this->next();
             break;
         case static::STATE_ENSURES:
             $this->_stack->push(['behavior' => $behavior, 'state' => static::STATE_THROWABLE]);
             if (false === $behavior->clauseExists('ensures') || 0 === (Coverage::CRITERIA_NORMAL & $this->getCriteria())) {
                 $this->_pop->push($this->_pop->pop() - 1);
                 $this->next();
                 break;
             }
             ++$this->_key;
             $this->_current = $behavior->getClause('ensures');
             $this->_path->push($this->_current);
             $this->_pop->push(0);
             break;
         case static::STATE_THROWABLE:
             if (false === $behavior->clauseExists('throwable') || 0 === (Coverage::CRITERIA_EXCEPTIONAL & $this->getCriteria())) {
                 $this->_pop->push($this->_pop->pop() - 1);
                 $this->next();
                 break;
             }
             ++$this->_key;
             $this->_current = $behavior->getClause('throwable');
             $this->_path->push($this->_current);
             $this->_pop->push(0);
             break;
     }
     return;
 }
示例#6
0
<?php

$q = new SplQueue();
$q->push(1);
$q->push(2);
$q->push(3);
echo $q->pop() . PHP_EOL;
print_r($q);
// vim600:ts=4 st=4 foldmethod=marker foldmarker=<<<,>>>
// vim600:syn=php commentstring=//%s
示例#7
0
<?php

##############################SPL queue##################################
$q = new SplQueue();
$q->push(1);
$q->push(2);
$q->push(3);
$q->pop();
print_r($q);
##############################SPL heap##################################
class MySimpleHeap extends SplHeap
{
    //compare()方法用来比较两个元素的大小,绝对他们在堆中的位置
    public function compare($value1, $value2)
    {
        return $value1 - $value2;
    }
}
$obj = new MySimpleHeap();
$obj->insert(4);
$obj->insert(8);
$obj->insert(1);
$obj->insert(0);
echo $obj->top();
//8
echo $obj->count();
//4
foreach ($obj as $number) {
    echo $number;
}
示例#8
0
 public function pop()
 {
     return parent::pop();
 }
示例#9
0
 /**
  * (non-PHPdoc)
  * @see ContentEngine\Request.QueueInterface::get()
  */
 public function get()
 {
     if (!$this->queue->isEmpty()) {
         return $this->queue->pop();
     }
 }
示例#10
0
 private function postProcess(\DOMDocument $document)
 {
     $nodes = new \SplQueue();
     $nodes->push($document);
     while ($nodes->count()) {
         $current = $nodes->pop();
         if ($current instanceof BBDomText) {
             $this->parseText($current);
         } else {
             foreach ($current->childNodes as $child) {
                 $nodes->push($child);
             }
         }
     }
 }
示例#11
0
/**
 * Determine if a binary tree rooted at $node satisfies the binary search tree property (every child in the nodes
 * subtree is less than or equal to the node and every child in the nodes right tree is greater than or equal to the
 * node).  This works by traversing through each node using BFS and adding an entry to the queue with the current node
 * and the range constraint that the node value must satisfy.  Starting at the root node, the root node is added to the
 * queue along with the range constraint [-infinity, infinity].  Then the left child node of the root is added to the
 * queue with the constraint [-infinity, root node key].  Then the right child node of the root is added to the queue
 * with the constraint [root node key, infinity].  The root node is then popped from the queue.  Each child node key
 * will then be checked against the stored constraints, their children added and then they will be popped.  If any
 * constraint is not met, the binary tree does not satisfy the BST property.
 *
 * i.e.
 * If the input tree is:
 *                           8
 *                         /   \
 *                        3    7
 *                       / \    \
 *                      1   6   14
 *
 * $queue = [
 *  $node (with key 8), -infinity, infinity
 * ]
 * Is 8 < -infinity or > infinity? No
 * $queue = [
 *  $node (with key 3), -infinity, 8
 *  $node (with key 7), 8, infinity
 * ]
 *
 * Is 3 < -infinity or > 8? No
 * Is 7 < 8 or > infinity? Yes
 *
 * This tree does not satisfy the BST property
 *
 * @param Node|null $node
 * @return bool
 */
function testForBstPropertyUsingQueue(Node $node = null)
{
    if (empty($node)) {
        return true;
    }
    $queue = new \SplQueue();
    $queue->enqueue([$node, -9.223372036854776E+18, PHP_INT_MAX]);
    while (!$queue->isEmpty()) {
        if (!empty($queue->current())) {
            if ($queue->current()[0]->key < $queue->current()[1] || $queue->current()[1]->key > $queue->current()[2]) {
                return false;
            }
            $queue->enqueue([$node->left, $queue->current()[1], $queue->current()[0]->key]);
            $queue->enqueue([$node->right, $queue->current()[0]->key], $queue->current()[2]);
        }
        $queue->pop();
    }
    return true;
}
示例#12
0
function fromQueue(\SplQueue $queue)
{
    return Observable::create(function (ObserverInterface $observer) use($queue) {
        while ($value = $queue->count()) {
            //echo "dequeue";
            $observer->onNext($queue->pop());
        }
        $observer->onCompleted();
    });
}
示例#13
0
 public function statePhp(Token $token)
 {
     switch ($token->type) {
         case Token::WHITESPACE:
         case Token::EOL:
             $this->appendStatement($token);
             return false;
         case Token::TEXT && $token->value === '__DIR__':
             $token->value = self::SPEC_CLASS . '::dir(__DIR__)';
             $this->appendStatement($token);
             return false;
         case Token::COMMENT:
             $value = trim($token->value);
             // Line comments include a new line character
             if (substr($value, 0, 1) === '#' || substr($value, 0, 2) === '//') {
                 // Manage annotations
                 if (preg_match('/^#\\s*[A-Z-]+/i', $value, $m)) {
                     $value = '/** @' . trim($value, ' #') . ' */' . "\n";
                 } else {
                     $value = '/** ' . trim(substr($value, 2)) . ' */' . "\n";
                 }
                 $value .= str_repeat(' ', max(0, $this->indent - 4));
                 // Merge consecutive single line comments
                 $prevs = array();
                 while (!$this->statement->isEmpty()) {
                     $prevs[] = $prev = $this->statement->pop();
                     if ($prev->type === Token::COMMENT) {
                         $prev->value = str_replace('*/', '', $prev->value);
                         $value = substr($value, 3);
                         break;
                     } else {
                         if ($prev->type !== Token::WHITESPACE && $prev->type !== Token::EOL) {
                             break;
                         }
                     }
                 }
                 while (count($prevs)) {
                     $this->statement->push(array_pop($prevs));
                 }
                 $token->value = $value;
                 // Single line comments include a new line
                 $this->isIndent = true;
                 $this->indent = 0;
             }
             // Check if we want to modify indentation control
             if (stripos($token->value, '@end-manual') !== FALSE) {
                 $this->endAuto = false;
             } else {
                 if (strpos($token->value, '@end-auto') !== FALSE) {
                     $this->endAuto = true;
                 }
             }
             $this->appendStatement($token);
             return false;
         case Token::IDENT:
         case Token::RCURLY:
             $ident = strtolower($token->value);
             if (in_array($ident, array('describe', 'context', 'it', 'specify', 'before', 'before_each', 'after', 'after_each', 'end', '}'))) {
                 $this->dumpStatement();
                 $this->transition(self::BLOCK);
                 return $token;
             }
         default:
             if ($token->token === T_CLOSE_TAG) {
                 $this->transition(self::TOP);
                 return false;
             }
             $this->transition(self::STATEMENT);
             return $token;
     }
 }
示例#14
0
文件: Queue.php 项目: jgswift/qtcp
 function pop()
 {
     $value = parent::pop();
     $this->save();
     return $value;
 }
示例#15
0
 /**
  * 弹出 middleware
  *
  * @return callable
  */
 public function pop()
 {
     return $this->queue->pop();
 }
示例#16
0
 function breadthFirstSearch($startVertex)
 {
     $startVertex->visited = true;
     $Q = new SplQueue();
     $Q->push($startVertex);
     while (!$Q->empty()) {
         $x = new Vertex();
         $x = $Q->front();
         $Q->pop();
         foreach ($x->neighbors as $VertexPtr) {
             if ($VertexPtr->visited == false) {
                 $VertexPtr->visited = trie;
                 $VertexPtr->pred = $x;
                 $Q->push($VertexPtr);
             }
         }
     }
 }