예제 #1
0
 /**
  * @inheritdoc
  */
 public function pushProcessor(ProcessorInterface ...$processors)
 {
     $this->initProcessors();
     foreach ($processors as $processor) {
         $this->processors->push($processor);
     }
 }
예제 #2
0
 public function parse($code)
 {
     $ary = new BrainDog_OpArray();
     $pst = new SplStack();
     foreach (str_split($code) as $op) {
         $idx = count($ary);
         switch ($op) {
             case self::OP_GT:
             case self::OP_LT:
             case self::OP_ADD:
             case self::OP_SUB:
             case self::OP_DOT:
             case self::OP_COM:
                 $ary[$idx] = new BrainDog_OpCode($op);
                 break;
             case self::OP_LBR:
                 $pst->push($idx);
                 $ary[$idx] = new BrainDog_OpCode($op);
                 break;
             case self::OP_RBR:
                 $pos = $pst->pop();
                 $ary[$pos]->jmp = $idx;
                 $ary[$idx] = new BrainDog_OpCode($op, $pos - 1);
                 break;
         }
     }
     return $ary;
 }
예제 #3
0
파일: Base.php 프로젝트: szyhf/DIServer
 /**
  * 加载指定目录下的配置并生成[绝对路径=>配置]
  * (备用)
  *
  * @param        $filePath
  * @param string $ext
  */
 private function LoadV2($filePath, $ext = '.php')
 {
     $resConfig = [];
     $split = '.';
     if (file_exists($filePath)) {
         $key = basename($filePath, $ext);
         $configs = (include $filePath);
         $keyStack = new \SplStack();
         $keyStack->push([$key, $configs]);
         $whileCount = 0;
         //防止意外进入死循环,限制最多循环1024层
         while (!$keyStack->isEmpty() && $whileCount < 1024) {
             $whileCount++;
             $pair = $keyStack->pop();
             foreach ($pair[1] as $pairKey => $pairVal) {
                 if (is_array($pairVal)) {
                     $keyStack->push([$pair[0] . $split . $pairKey, $pairVal]);
                 } else {
                     $resConfig[$pair[0] . $split . $pairKey] = $pairVal;
                 }
             }
         }
     }
     return $resConfig;
 }
예제 #4
0
 /**
  * Evaluate array sequence of tokens in Reverse Polish notation (RPN)
  * representing mathematical expression.
  * 
  * @param array $expressionTokens
  * @return float
  * @throws \InvalidArgumentException
  */
 private function evaluateRPN(array $expressionTokens)
 {
     $stack = new \SplStack();
     foreach ($expressionTokens as $token) {
         $tokenValue = $token->getValue();
         if (is_numeric($tokenValue)) {
             $stack->push((double) $tokenValue);
             continue;
         }
         switch ($tokenValue) {
             case '+':
                 $stack->push($stack->pop() + $stack->pop());
                 break;
             case '-':
                 $n = $stack->pop();
                 $stack->push($stack->pop() - $n);
                 break;
             case '*':
                 $stack->push($stack->pop() * $stack->pop());
                 break;
             case '/':
                 $n = $stack->pop();
                 $stack->push($stack->pop() / $n);
                 break;
             case '%':
                 $n = $stack->pop();
                 $stack->push($stack->pop() % $n);
                 break;
             default:
                 throw new \InvalidArgumentException(sprintf('Invalid operator detected: %s', $tokenValue));
                 break;
         }
     }
     return $stack->top();
 }
예제 #5
0
 function testPrintTraversable()
 {
     $stack = new \SplStack();
     $stack->push('foo');
     $stack->push('bar');
     $this->assertEquals("<SplStack>['bar', 'foo']", ValuePrinter::serialize($stack));
 }
예제 #6
0
 /**
  * @inheritdoc
  */
 public function pushHandler(HandlerInterface ...$handlers)
 {
     $this->initHandlers();
     foreach ($handlers as $handler) {
         $this->handlers->push($handler);
     }
 }
예제 #7
0
 /**
  * Run the pathfinder algorithm
  *
  * @return \SplStack
  */
 public function run()
 {
     $start = $this->start;
     $goal = $this->goal;
     $open = new Set([$start], function (NodeInterface $node) use($goal) {
         return $this->getHeuristic($goal, $node);
     });
     $closed = new Set();
     $open->add($start);
     $path = new \SplStack();
     $step = null;
     while (!$open->isEmpty()) {
         $current = $open->current();
         $path->push($current->getNode());
         $step = new Step($current->getNode(), $step);
         if ($current->getNode() == $goal) {
             break;
         }
         $closed->add($current->getNode());
         $neighbours = $current->getNode()->getNeighbours();
         foreach ($neighbours as $neighbour) {
             if ($closed->has($neighbour)) {
                 continue;
             }
             if (!$open->has($neighbour)) {
                 $open->add($neighbour, $this->getHeuristic($current->getNode(), $neighbour) + $neighbour->getCost());
             }
         }
     }
     return $path;
 }
예제 #8
0
 /**
  * Resolves yield calls tree
  * and gives a return value if outcome of yield is CoroutineReturnValue instance
  *
  * @param \Generator $coroutine nested coroutine tree
  * @return \Generator
  */
 private static function stackedCoroutine(\Generator $coroutine)
 {
     $stack = new \SplStack();
     while (true) {
         $value = $coroutine->current();
         // nested generator/coroutine
         if ($value instanceof \Generator) {
             $stack->push($coroutine);
             $coroutine = $value;
             continue;
         }
         // coroutine end or value is a value object instance
         if (!$coroutine->valid() || $value instanceof CoroutineReturnValue) {
             // if till this point, there are no coroutines in a stack thatn stop here
             if ($stack->isEmpty()) {
                 return;
             }
             $coroutine = $stack->pop();
             $value = $value instanceof CoroutineReturnValue ? $value->getValue() : null;
             $coroutine->send($value);
             continue;
         }
         $coroutine->send((yield $coroutine->key() => $value));
     }
 }
 /**
  * That nested case will be corrected and fully supported
  * {% softdeleteable %}
  *    <span>
  *       {% softdeleteable 'Acme\Bundle\CoreBundle\Entity\Foo' %}
  *           {% softdeleteable %}
  *               {% softdeleteable 'Acme\Bundle\CoreBundle\Entity\Bar' %}
  *                   {{ object.owner.fullName }}
  *               {% endsoftdeleteable %}
  *           {% endsoftdeleteable %}
  *       {% endsoftdeleteable %}
  *    </span>
  * {% endsoftdeleteable %}
  * @param null $class
  * @return bool
  */
 public function enable($class = null)
 {
     if (!$this->entityManager->getFilters()->isEnabled('softdeleteable')) {
         if ($class !== null) {
             // Nested tags case.
             // {% softdeleteable 'FQCN' %} inside {% softdeleteable %}
             // So, just pop classes stack
             $this->classStack->pop();
         } else {
             // When we enable globally we need to restore disabled entities
             $this->entityManager->getFilters()->enable('softdeleteable');
             // Populate from stack of disabled entities
             /** @var SoftDeleteableFilter $filter */
             $filter = $this->entityManager->getFilters()->getFilter('softdeleteable');
             foreach ($this->classStack as $class) {
                 $filter->disableForEntity($class);
             }
         }
     } else {
         if ($class !== null) {
             /** @var SoftDeleteableFilter $filter */
             $filter = $this->entityManager->getFilters()->getFilter('softdeleteable');
             $filter->enableForEntity($class);
             $this->classStack->pop();
         }
     }
 }
예제 #10
0
 /**
  * {@inheritdoc}
  */
 public function withMiddleware($middleware) : StackContract
 {
     if ($middleware instanceof MiddlewareInterface || $middleware instanceof ServerMiddlewareInterface) {
         $this->stack->push($this->isContainerAware($middleware));
         return $this;
     }
     throw new LogicException('Unsupported middleware type.');
 }
예제 #11
0
파일: Item.php 프로젝트: he--/liquidaJp
 /**
  * @return \SplStack
  */
 public function notify()
 {
     $pilhaNotificacoes = new \SplStack();
     foreach ($this->observers as $value) {
         $pilhaNotificacoes->push($value->update($this));
     }
     return $pilhaNotificacoes;
 }
 public function getPredicate()
 {
     $predicate = $this->predicateStack->bottom()->pruneInstancesOf(NullPredicate::class, true)->pruneRedundantComposites(true);
     if ($predicate instanceof CompositePredicate) {
         $predicate = $predicate->pruneInstancesOf(NullPredicate::class, true);
     }
     return $predicate;
 }
예제 #13
0
 private function stack($items)
 {
     $stack = new \SplStack();
     foreach ($items as $item) {
         $stack->push($item);
     }
     return $stack;
 }
예제 #14
0
 protected function firstrun()
 {
     $data = new \SplStack();
     foreach ($this->source as $val) {
         $data->push($val);
     }
     parent::__construct($data);
 }
예제 #15
0
 /**
  * @depends testGetStack
  * @covers Versionable\Ration\Client\Pipeline::send
  * @covers Versionable\Ration\Client\Pipeline::getStack
  */
 public function testSend()
 {
     $request = $this->getMock('Versionable\\Ration\\Request\\Request');
     $stack = new \SplStack();
     $stack->push($request);
     $this->object->send($request);
     $this->assertEquals($stack, $this->object->getStack());
 }
예제 #16
0
 public function shortestPath($source, $target)
 {
     // array of best estimates of shortest path to each
     // vertex
     $dist = array();
     // array of predecessors for each vertex
     $prev = array();
     $vertex = array();
     foreach ($this->graph as $v => $adj) {
         $vertex[$v] = 1;
         foreach ($adj as $w => $cost) {
             $vertex[$w] = 1;
         }
     }
     foreach ($vertex as $v => $value) {
         $dist[$v] = 1;
         $prev[$v] = null;
     }
     $dist[$source] = -1;
     while (!empty($vertex)) {
         $min = 2;
         $u = null;
         foreach ($vertex as $v => $value) {
             if ($dist[$v] < $min) {
                 $min = $dist[$v];
                 $u = $v;
             }
         }
         unset($vertex[$u]);
         if (isset($this->graph[$u])) {
             foreach ($this->graph[$u] as $n => $cost) {
                 $alt = -abs($dist[$u] * $cost);
                 if ($alt < $dist[$n]) {
                     $dist[$n] = $alt;
                     $prev[$n] = $u;
                 }
             }
         }
     }
     // we can now find the shortest path using reverse
     // iteration
     $S = new \SplStack();
     // shortest path with a stack
     $u = $target;
     $dist = 1;
     // traverse from target to source
     while (isset($prev[$u]) && $prev[$u] && $u != $source) {
         $S->push($u);
         $dist *= $this->graph[$prev[$u]][$u];
         // add distance to predecessor
         $u = $prev[$u];
     }
     if ($u != $source) {
         return 0;
     }
     return $dist;
 }
예제 #17
0
 /**
  * @return $this
  */
 public function push()
 {
     if (func_num_args() === 0) {
         throw new \InvalidArgumentException('Missing argument(s) when calling push');
     }
     $msgApp = func_get_args();
     $this->components->push($msgApp);
     return $this;
 }
예제 #18
0
파일: Builder.php 프로젝트: Niktux/swarrot
 /**
  * @return self
  *
  * @throws \InvalidArgumentException Missing argument(s) when calling push
  */
 public function push()
 {
     if (func_num_args() === 0) {
         throw new \InvalidArgumentException("Missing argument(s) when calling push");
     }
     $spec = func_get_args();
     $this->specs->push($spec);
     return $this;
 }
예제 #19
0
 public function getParamsStack()
 {
     if (null === $this->paramsStack) {
         $this->paramsStack = new \SplStack();
         if ($this->getParentCommand() instanceof CommandInterface) {
             $this->paramsStack->push($this->getParentCommand()->getParams());
         }
     }
     return $this->paramsStack;
 }
예제 #20
0
 private function solve($formula)
 {
     $findSubFormula = false;
     $stringStart = 0;
     $stringLength = 0;
     $stack = new \SplStack();
     $subFormulas = [];
     for ($i = 0; $i < strlen($formula); $i++) {
         $char = $formula[$i];
         if ($this->isBracketOpen($char)) {
             if ($findSubFormula == false && $stack->count() == 0) {
                 $stringStart = $i;
             }
             $stack->push(1);
             $findSubFormula = true;
         }
         if ($findSubFormula) {
             $stringLength++;
         }
         if ($this->isBracketClose($char)) {
             $stack->pop();
             if ($stack->count() === 0 && $findSubFormula) {
                 $subFormulas[substr($formula, $stringStart, $stringLength)] = substr($formula, $stringStart, $stringLength);
                 $findSubFormula = false;
                 $stringLength = 0;
             }
         }
     }
     if (count($subFormulas) > 0) {
         foreach ($subFormulas as &$subFormula) {
             $temp = trim(substr($subFormula, 1, strlen($subFormula) - 2));
             $subFormula = $this->solve($temp);
         }
         $formula = str_replace(array_keys($subFormulas), array_values($subFormulas), $formula);
     }
     $elems = new \SplDoublyLinkedList();
     array_map(function ($item) use($elems) {
         if ($item != ' ') {
             $elems->push($item);
         }
     }, explode(' ', $formula));
     while ($elems->count() > 1) {
         $maxPriority = 0;
         $index = 0;
         foreach ($elems as $i => $el) {
             if (isset(static::$symbols[$el]) && static::$symbols[$el] > $maxPriority) {
                 $maxPriority = static::$symbols[$el];
                 $index = $i;
             }
         }
         $this->process($index, $elems);
     }
     return $elems->pop();
 }
예제 #21
0
파일: bug65328.php 프로젝트: badlamer/hhvm
 /**
  * @param mixed $uid
  * @return \SplStack
  */
 public function &findAll($uid)
 {
     $result = new \SplStack();
     /** @var Node $node */
     foreach ($this->getIterator() as $node) {
         if ($node->getUid() == $uid) {
             $result->push($node);
         }
     }
     return $result;
 }
예제 #22
0
 /**
  * Walks through the pageIdStack, collects all pageIds
  * as array and passes them on to clearPageCache.
  *
  * @return void
  */
 public function clearCachesOfRegisteredPageIds()
 {
     if (!$this->pageIdStack->isEmpty()) {
         $pageIds = array();
         while (!$this->pageIdStack->isEmpty()) {
             $pageIds[] = (int) $this->pageIdStack->pop();
         }
         $pageIds = array_values(array_unique($pageIds));
         $this->clearPageCache($pageIds);
     }
 }
 public function testForValidValues()
 {
     $var = new \SplStack();
     $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);
 }
예제 #24
0
 public function getPathTo($endVertex)
 {
     if (!$this->hasPathTo($endVertex)) {
         return null;
     }
     $path = new \SplStack();
     for ($i = $endVertex; $i != $this->startVertex; $i = $this->edgeTo[$i]) {
         $path->push($i);
     }
     $path->push($this->startVertex);
     return $path;
 }
예제 #25
0
/**
 * Поиск самого дешёвого пути между двумя локациями
 * Для поиска используется алгоритм Дейкстры
 *
 * @see http://www.sitepoint.com/data-structures-4/
 *
 * @param array  $data   Массив с локациями и ценой проезда между ними [][src, dst, cost]
 * @param string $source Название исходного пункта
 * @param string $target Название конечного пункта
 *
 * @return SplStack
 */
function find_path(array $data, $source, $target)
{
    $graph = build_graph($data);
    // массив лучших цен кратчайшего пути для каждой локации
    $best_cost = [];
    // массив предыдущих локаций для каждой локации
    $prev_loc = array();
    // очередь из необработанных локаций
    $queue = new SplPriorityQueue();
    foreach ($graph as $src => $dst) {
        $best_cost[$src] = INF;
        // изначальные значения цен бесконечны
        $prev_loc[$src] = null;
        // предыдущие локации неизвестны
        foreach ($dst as $name => $cost) {
            // используем цену как приоритет в очереди
            $queue->insert($name, $cost);
        }
    }
    // цена поездки в исходный пункт = 0
    $best_cost[$source] = 0;
    while (!$queue->isEmpty()) {
        // получаем минимальную цену
        $u = $queue->extract();
        if (empty($graph[$u])) {
            continue;
        }
        // обрабатываем доступные маршруты для локации
        foreach ($graph[$u] as $v => $cost) {
            // альтернативная цена для маршрута
            $alt = $best_cost[$u] + $cost;
            if ($alt < $best_cost[$v]) {
                // обновляем минимальную цену для локации
                $best_cost[$v] = $alt;
                // добавляем локацию в массив предыдущих локаций
                $prev_loc[$v] = $u;
            }
        }
    }
    // ищем дешёвый путь и складываем его в стек
    $stack = new SplStack();
    $u = $target;
    $final_cost = 0;
    // проходим в обратном порядке от пункта назначения к исходному пункту
    while (isset($prev_loc[$u]) && $prev_loc[$u]) {
        $stack->push($u);
        $final_cost += $graph[$u][$prev_loc[$u]];
        $u = $prev_loc[$u];
    }
    $stack->push($source);
    return [$stack, $final_cost];
}
 /**
  * @param \PHP\Manipulator\Token $token
  */
 protected function _checkLevel(Token $token)
 {
     if ($this->isOpeningCurlyBrace($token)) {
         $this->_level++;
         $this->_maxLevel = max(array($this->_level, $this->_maxLevel));
     }
     if ($this->isClosingCurlyBrace($token)) {
         $this->_level--;
         if (!$this->_classStack->isEmpty() && $this->_level === $this->_classStack[count($this->_classStack) - 1]) {
             $this->_classStack->pop();
         }
     }
 }
예제 #27
0
function isPalindrome($word)
{
    $word = strtolower(str_replace(" ", "", $word));
    $stack = new SplStack();
    $cnt = strlen($word);
    for ($i = 0; $i < $cnt; ++$i) {
        $stack->push($word[$i]);
    }
    $rword = "";
    while ($stack->count() > 0) {
        $rword .= $stack->pop();
    }
    return $word == $rword;
}
 /**
  * @param \SplStack $metadataStack
  * @return null|string
  */
 protected function getStackAsString(\SplStack $metadataStack)
 {
     if ($metadataStack->count() > 1) {
         $propertyNames = [];
         foreach ($metadataStack as $metadata) {
             if ($metadata instanceof PropertyMetadata) {
                 $propertyNames[] = $metadata->name;
             }
         }
         $propertyNames = array_reverse($propertyNames);
         return implode('.', $propertyNames);
     }
     return null;
 }
예제 #29
0
 /**
  * Get the transformed text off the stack, and clear down the other stacks.
  *
  * @return string
  */
 private function blockFinished()
 {
     $transformedText = $this->transformedTextStack->pop();
     $this->blockTypeStack->pop();
     $this->blockAttributesStack->pop();
     return $transformedText;
 }
예제 #30
0
 /**
  * Convenient access to the last handler return value.
  *
  * If the collection is empty, returns null. Otherwise, returns value
  * returned by last handler.
  *
  * @return mixed The last handler return value
  */
 public function last()
 {
     if (count($this) === 0) {
         return null;
     }
     return parent::top();
 }