本文整理汇总了PHP中SplPriorityQueue::isEmpty方法的典型用法代码示例。如果您正苦于以下问题:PHP SplPriorityQueue::isEmpty方法的具体用法?PHP SplPriorityQueue::isEmpty怎么用?PHP SplPriorityQueue::isEmpty使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类SplPriorityQueue
的用法示例。
在下文中一共展示了SplPriorityQueue::isEmpty方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: __construct
public function __construct()
{
$this->queue = new \SplPriorityQueue();
$this->timer = Loop\periodic(1, function () {
$time = time();
while (!$this->queue->isEmpty()) {
$key = $this->queue->top();
if (isset($this->expire[$key])) {
if ($time <= $this->expire[$key]) {
break;
}
unset($this->data[$key], $this->expire[$key], $this->ttl[$key]);
}
$this->queue->extract();
}
if ($this->queue->isEmpty()) {
$this->timer->stop();
}
});
$this->timer->stop();
$this->timer->unreference();
}
示例2: pop
/**
* @see QueueInterface::pop()
*/
public function pop()
{
if (!$this->innerQueue->isEmpty()) {
$eta = $this->innerQueue->top()->getEta();
if (!$eta || $eta->getTimestamp() <= time()) {
return $this->innerQueue->extract();
}
}
return false;
}
示例3: pop
/**
* {@inheritdoc}
*/
public function pop()
{
if (!$this->queue->isEmpty()) {
$this->queue->setExtractFlags(\SplPriorityQueue::EXTR_PRIORITY);
$priority = $this->queue->top();
if (time() + $priority[0] >= 0) {
$this->queue->setExtractFlags(\SplPriorityQueue::EXTR_DATA);
return $this->queue->extract();
}
}
throw new NoItemAvailableException($this);
}
示例4: pop
/**
* {@inheritdoc}
*/
public function pop()
{
if ($this->queue->isEmpty()) {
return;
}
$this->queue->setExtractFlags(\SplPriorityQueue::EXTR_PRIORITY);
$priority = $this->queue->top();
if (time() + $priority[0] >= 0) {
$this->queue->setExtractFlags(\SplPriorityQueue::EXTR_DATA);
return $this->queue->extract();
}
}
示例5: loop
/**
* 主循环
* @see Events\EventInterface::loop()
*/
public function loop()
{
$e = null;
while (1) {
// 如果有信号,尝试执行信号处理函数
pcntl_signal_dispatch();
$read = $this->_readFds;
$write = $this->_writeFds;
// 等待可读或者可写事件
@stream_select($read, $write, $e, 0, $this->_selectTimeout);
// 尝试执行定时任务
if (!$this->_scheduler->isEmpty()) {
$this->tick();
}
// 这些描述符可读,执行对应描述符的读回调函数
if ($read) {
foreach ($read as $fd) {
$fd_key = (int) $fd;
if (isset($this->_allEvents[$fd_key][self::EV_READ])) {
call_user_func_array($this->_allEvents[$fd_key][self::EV_READ][0], array($this->_allEvents[$fd_key][self::EV_READ][1]));
}
}
}
// 这些描述符可写,执行对应描述符的写回调函数
if ($write) {
foreach ($write as $fd) {
$fd_key = (int) $fd;
if (isset($this->_allEvents[$fd_key][self::EV_WRITE])) {
call_user_func_array($this->_allEvents[$fd_key][self::EV_WRITE][0], array($this->_allEvents[$fd_key][self::EV_WRITE][1]));
}
}
}
}
}
示例6: tick
/**
* Executes any pending timers. Returns the number of timers executed.
*
* @return int
*
* @internal
*/
public function tick() : int
{
$count = 0;
$time = microtime(true);
while (!$this->queue->isEmpty()) {
list($timer, $timeout) = $this->queue->top();
if (!$this->timers->contains($timer) || $timeout !== $this->timers[$timer]) {
$this->queue->extract();
// Timer was removed from queue.
continue;
}
if ($this->timers[$timer] > $time) {
// Timer at top of queue has not expired.
return $count;
}
// Remove and execute timer. Replace timer if persistent.
$this->queue->extract();
if ($timer->isPeriodic()) {
$timeout = $time + $timer->getInterval();
$this->queue->insert([$timer, $timeout], -$timeout);
$this->timers[$timer] = $timeout;
} else {
$this->timers->detach($timer);
}
// Execute the timer.
$timer->call();
++$count;
}
return $count;
}
示例7: loop
/**
* @see Events\EventInterface::loop()
*/
public function loop()
{
$e = null;
while (1) {
// Calls signal handlers for pending signals
pcntl_signal_dispatch();
$read = $this->_readFds;
$write = $this->_writeFds;
// Waiting read/write/signal/timeout events.
$ret = @stream_select($read, $write, $e, 0, $this->_selectTimeout);
if (!$this->_scheduler->isEmpty()) {
$this->tick();
}
if (!$ret) {
continue;
}
foreach ($read as $fd) {
$fd_key = (int) $fd;
if (isset($this->_allEvents[$fd_key][self::EV_READ])) {
call_user_func_array($this->_allEvents[$fd_key][self::EV_READ][0], array($this->_allEvents[$fd_key][self::EV_READ][1]));
}
}
foreach ($write as $fd) {
$fd_key = (int) $fd;
if (isset($this->_allEvents[$fd_key][self::EV_WRITE])) {
call_user_func_array($this->_allEvents[$fd_key][self::EV_WRITE][0], array($this->_allEvents[$fd_key][self::EV_WRITE][1]));
}
}
}
}
示例8: nextTimeout
/**
* Get the number of microseconds until the next timer watcher is due.
*
* @return int or null when no timers are pending.
*/
protected function nextTimeout()
{
$time = \microtime(true);
while (!$this->scheduler->isEmpty()) {
list($watcher, $scheduled) = $this->scheduler->top();
if ($watcher->enabled && $watcher->scheduled === $scheduled) {
return (int) \max(0, ($watcher->due - $time) * 1000000);
}
}
}
示例9: find_path
/**
* Поиск самого дешёвого пути между двумя локациями
* Для поиска используется алгоритм Дейкстры
*
* @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];
}
示例10: compileRoutes
/**
* {@inheritdoc}
*/
public final function compileRoutes(RouteCompiler $compiler, RoutingContext $context) : array
{
$parsed = new \SplPriorityQueue();
foreach ($this->routes as $route) {
foreach ($route->compile($compiler) as list($priority, $depth, $route, $regex, $mapping)) {
$parsed->insert(\array_merge([$regex, $depth, $priority, $route], $mapping), $priority);
}
}
$result = [];
while (!$parsed->isEmpty()) {
$result[] = $parsed->extract();
}
return $result;
}
示例11: _shortestPath
/**
* Поиск кратчайшего пути
* @see https://www.youtube.com/watch?v=UA6aV1XJCGg
*/
private function _shortestPath()
{
while (!$this->_nodeQueue->isEmpty()) {
$u = $this->_nodeQueue->extract();
if (!empty($this->_routes[$u])) {
foreach ($this->_routes[$u] as $v => $cost) {
$newCost = $this->_destinations[$u] + $cost;
if ($newCost < $this->_destinations[$v]) {
$this->_destinations[$v] = $newCost;
$this->_predecessors[$v] = $u;
}
}
}
}
}
示例12: findNeighbors
private function findNeighbors($type, $keywords, $id)
{
$queue = new SplPriorityQueue();
$queue->setExtractFlags(SplPriorityQueue::EXTR_BOTH);
$cursor = $this->m->websites->find([]);
foreach ($cursor as $doc) {
if ($doc['_id'] != new MongoId($id)) {
$d = $this->distance($type, $keywords, $doc['type'], $doc['keywords']);
$queue->insert($doc, $d);
}
}
$res = [];
for ($i = 0; $i < 20 && !$queue->isEmpty(); $i++) {
$res[] = $queue->extract();
}
return $res;
}
示例13: getTimeout
/**
* @return int Milliseconds until next timer expires or -1 if there are no pending times.
*/
private function getTimeout()
{
while (!$this->timerQueue->isEmpty()) {
list($watcher, $expiration) = $this->timerQueue->top();
$id = $watcher->id;
if (!isset($this->timerExpires[$id]) || $expiration !== $this->timerExpires[$id]) {
$this->timerQueue->extract();
// Timer was removed from queue.
continue;
}
$expiration -= (int) (\microtime(true) * self::MILLISEC_PER_SEC);
if ($expiration < 0) {
return 0;
}
return $expiration;
}
return -1;
}
示例14: compileRoutes
/**
* {@inheritdoc}
*/
public final function compileRoutes(RouteCompiler $compiler, RoutingContext $context) : array
{
$ref = new \ReflectionClass(static::class);
$parsed = new \SplPriorityQueue();
foreach ($ref->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) {
if ($method->isStatic() || !$method->hasReturnType()) {
continue;
}
$type = (string) $method->getReturnType();
if ($type !== Route::class && !\is_subclass_of($type, Route::class)) {
continue;
}
$args = $context->container->populateArguments($method, [], new InjectionPoint(static::class));
$route = $this->{$method->name}(...$args);
foreach ($route->compile($compiler) as list($priority, $depth, $route, $regex, $mapping)) {
$parsed->insert(\array_merge([$regex, $depth, $priority, $route], $mapping), $priority);
}
}
$result = [];
while (!$parsed->isEmpty()) {
$result[] = $parsed->extract();
}
return $result;
}
示例15: tokenize
public function tokenize(string $input) : array
{
if (!$this->initialized) {
$this->initialized = true;
$this->initialize();
}
$types = [];
$parts = [];
$transform = [];
foreach ($this->tokens as $k => list($v, $t)) {
$types[] = $k;
$parts[] = '(' . $v . ')';
$transform[] = $t;
}
$sorter = new \SplPriorityQueue();
foreach ($this->terminals as $k => list(, $terminal)) {
$sorter->insert([$k, $terminal], strlen($terminal));
}
while (!$sorter->isEmpty()) {
list($k, $terminal) = $sorter->extract();
$types[] = $k;
$parts[] = '(' . $terminal . ')';
$transform[] = NULL;
}
$types[] = 'T_IDENTIFIER';
$parts[] = '(' . $this->identifierPattern . ')';
$transform[] = NULL;
$regex = "~" . implode('|', $parts) . "~AS";
$len = strlen($input);
$offset = 0;
$tokens = [];
$line = 1;
$pos = 1;
$m = NULL;
while (true) {
if ($offset >= $len) {
break;
}
if (!preg_match($regex, $input, $m, NULL, $offset)) {
throw new \RuntimeException(sprintf('No matching token found at position: "%s"', substr($input, $offset, 10)));
}
$i = count($m) - 2;
$type = $types[$i];
$tlen = strlen($m[0]);
if ($type === 'T_IDENTIFIER') {
$key = strtolower($m[0]);
if (isset($this->keywords[$key])) {
$keyword = $this->keywords[$key];
if (!$keyword[1] || $m[0] == $keyword[2]) {
$type = $keyword[0];
$m[0] = $keyword[2];
}
}
}
if (empty($this->skip[$type])) {
$tokens[] = $this->createToken($type, isset($transform[$i]) ? $transform[$i]($m[0]) : $m[0], $line, $pos, $offset + 1);
}
$offset += $tlen;
$pos += $tlen;
if (false !== strpos($m[0], "\n")) {
$line += substr_count($m[0], "\n");
$pos = strlen(substr($m[0], strrpos($m[0], "\n"))) + 1;
}
}
return $tokens;
}