Ejemplo n.º 1
0
func (x *TopApps) Mark(ApplicationId string, z time.Time) {
	t := z.Unix()

	x.Lock()
	defer x.Unlock()

	y := x.m[ApplicationId]
	if y != nil {
		z1 := heap.Remove(&x.t, y.ti).(*topAppsEntry)
		if z1 != y {
			panic("z1 != y")
		}
		z2 := heap.Remove(&x.n, y.ni).(*topAppsEntry)
		if z2 != y {
			panic("z2 != y")
		}
	} else {
		// New entry
		y = &topAppsEntry{ApplicationId: ApplicationId}
		x.m[ApplicationId] = y
	}

	y.Mark(t)

	heap.Push(&x.t, y)
	heap.Push(&x.n, y)
}
Ejemplo n.º 2
0
func TestHeapRemove(t *testing.T) {
	q := pq.NewQueue()
	q.Push(&message{8})
	q.Push(&message{3})
	q.Push(&message{9})
	q.Push(&message{1})
	q.Push(&message{10})
	q.Push(&message{2})
	q.Push(&message{5})
	q.Push(&message{6})
	q.Push(&message{7})
	q.Push(&message{4})
	heap.Init(q)

	r := heap.Remove(q, 5).(pq.Queueable)
	fmt.Println("removed:", r)

	if r.Priority() != 9 {
		t.Fatalf("Remove() fails, incorrect member removed.", r.Priority())
	}

	mb, _ := q.Member(0)
	if mb.Priority() != 1 {
		t.Fatalf("Remove() fails, unexpected value for min member")
	}
}
Ejemplo n.º 3
0
func (tm *TimerMgr) OnTick() {
	nowTime := time.Now()
	for {
		if tm.tq.Len() > 0 {
			t := heap.Pop(tm.tq)
			if te, ok := t.(*TimerEntity); ok {
				if te.next.Before(nowTime) {
					if te.times > 0 {
						te.times--
					}
					//Avoid async stop timer failed
					if te.times != 0 {
						te.next = te.next.Add(te.interval)
						heap.Push(tm.tq, te)
					}
					if !SendTimeout(te) {
						if v, ok := tm.tq.ref[te.h]; ok {
							heap.Remove(tm.tq, v)
						}
					}
				} else {
					heap.Push(tm.tq, te)
					return
				}
			}
		} else {
			return
		}
	}
}
Ejemplo n.º 4
0
func (g *Graph) update(n *Node, lowCost int) {
	if n.lowCost > lowCost {
		heap.Remove(g, n.index)
		n.lowCost = lowCost
		heap.Push(g, n)
	}
}
Ejemplo n.º 5
0
func (this *priorityQueue) update(node *HuffmanNode, ch string, weight float64) {
	heap.Remove(this, node.index)
	node.ch = ch
	node.weight = weight
	heap.Push(this, node)

}
Ejemplo n.º 6
0
func (t *TaskRunner) CancelAlarm(alarm *GoQuicAlarm) {
	item := t.alarmList[alarm]
	if item.heapIdx >= 0 {
		heap.Remove(t.alarmHeap, item.heapIdx)
	}
	t.resetTimer()
}
Ejemplo n.º 7
0
func (s *MemStorage) StorePosts(req *http.Request, posts []Activity) {
	s.mu.Lock()
	defer s.mu.Unlock()
	for _, post := range posts {
		if s.filter != nil && !s.filter(post) {
			continue
		}
		log.Printf("store: %s\n", post.Id)
		s.m[post.Id] = post
		updated := false
		datespec := GetDatespec(post.Published)
		for i, p := range s.a[datespec] {
			if p.Id == post.Id {
				s.a[datespec][i] = post
				updated = true
				break
			}
		}
		if !updated {
			s.a[datespec] = append(s.a[datespec], post)
		}
		heap.Push(&s.h, post)
		if s.h.Len() >= 10 {
			_ = heap.Remove(&s.h, s.h.Len()-1)
		}
	}
}
Ejemplo n.º 8
0
// advanceRoot retrieves the next row for the source at the root of the heap and
// updates the heap accordingly.
func (s *orderedSynchronizer) advanceRoot() error {
	if len(s.heap) == 0 {
		return nil
	}
	src := &s.sources[s.heap[0]]
	if src.row == nil {
		panic("trying to advance closed source")
	}
	oldRow := src.row
	var err error
	src.row, err = src.src.NextRow()
	if err != nil {
		s.err = err
		return err
	}
	if src.row == nil {
		heap.Remove(s, 0)
	} else {
		heap.Fix(s, 0)
		// TODO(radu): this check may be costly, we could disable it in production
		if cmp, err := oldRow.Compare(&s.alloc, s.ordering, src.row); err != nil {
			return err
		} else if cmp > 0 {
			return util.Errorf("incorrectly ordered stream %s after %s", src.row, oldRow)
		}
	}
	// heap operations might set s.err (see Less)
	return s.err
}
Ejemplo n.º 9
0
func TestRemove(t *testing.T) {
	var count int
	if golangcafeheap.Len() <= 0 {
		// Add時に0件になるので…。
		heap.Push(golangcafeheap, GolangCafe{Name: "ttyokoyama", Priority: 1, Count: 13, Index: 2})
		heap.Push(golangcafeheap, GolangCafe{Name: "taknb2nch", Priority: 2, Count: 13, Index: 3})
		heap.Push(golangcafeheap, GolangCafe{Name: "qt_luigi", Priority: 3, Count: 13, Index: 4})
		heap.Push(golangcafeheap, GolangCafe{Name: "tam_x", Priority: 4, Count: 1, Index: 1})
	} else {
		count = golangcafeheap.Len()
	}

	heap.Remove(golangcafeheap, 2)

	if golangcafeheap.Len() != (count - 1) {
		t.Errorf("golangcafeheap.Len() = %d, %d", golangcafeheap.Len(), count)
	}

	n := golangcafeheap.Len()
	for i := 0; i < n; i++ {
		item := golangcafeheap.Pop()
		golangcafe := item.(*GolangCafe)

		t.Logf("Name: %s Priority: %d Count: %d Index: %d",
			golangcafe.Name, golangcafe.Priority, golangcafe.Count, golangcafe.Index)
	}
}
Ejemplo n.º 10
0
func (h *ttlKeyHeap) update(n *node) {
	index, ok := h.keyMap[n]
	if ok {
		heap.Remove(h, index)
		heap.Push(h, n)
	}
}
Ejemplo n.º 11
0
func (d *Driver) Dequeue(queue string, eid uid.ID) (e *storage.Envelope, err error) {
	now := time.Now().UnixNano()
	d.m.Lock()
	defer d.m.Unlock()
	msgs := d.queues.get(queue)
	for i, n := 0, len(*msgs); i < n; i++ {
		msg := (*msgs)[i]
		if msg.availAt > now {
			break
		}
		if !msg.envelope.Retry.IsValid() {
			event.Emit(event.EventMessageDiscarded, msg.envelope)
			msg.removed = true
		}
		if msg.removed {
			heap.Remove(msgs, i)
			i--
			n--
			continue
		}
		e = msg.envelope
		msg.eid = eid
		msg.availAt = now + int64(msg.envelope.Timeout)
		msg.envelope.Retry.Decr()
		msg.accumlating = false
		heap.Fix(msgs, i)
		d.ephemeralIndex[eid] = msg
		return
	}
	err = storage.ErrEmpty
	return
}
Ejemplo n.º 12
0
/*
For snowflake proxies to request a client from the Broker.
*/
func proxyHandler(w http.ResponseWriter, r *http.Request) {
	if isPreflight(w, r) {
		return
	}
	id := r.Header.Get("X-Session-ID")
	body, err := ioutil.ReadAll(r.Body)
	if nil != err {
		log.Println("Invalid data.")
		w.WriteHeader(http.StatusBadRequest)
		return
	}
	if string(body) != id { // Mismatched IDs!
		w.WriteHeader(http.StatusBadRequest)
	}
	// Maybe confirm that X-Session-ID is the same.
	log.Println("Received snowflake: ", id)
	snowflake := AddSnowflake(id)

	// Wait for a client to avail an offer to the snowflake, or timeout
	// and ask the snowflake to poll later.
	select {
	case offer := <-snowflake.offerChannel:
		log.Println("Passing client offer to snowflake.")
		w.Write(offer)

	case <-time.After(time.Second * ProxyTimeout):
		// This snowflake is no longer available to serve clients.
		heap.Remove(snowflakes, snowflake.index)
		delete(snowflakeMap, snowflake.id)
		w.WriteHeader(http.StatusGatewayTimeout)
	}
}
Ejemplo n.º 13
0
// Remove a job from the queue.
func (jq *JobQueue) Remove(job *Job) {
	Debug("rm", job)
	delete(jq.byname, job.file)
	delete(jq.byidx, job.id)
	heap.Remove(&(jq.pq), job.index)
	job.index = -1
}
Ejemplo n.º 14
0
func (this *priorityQueue) update(node *space, end int, cost int) {
	heap.Remove(this, node.index)
	node.end = end
	node.cost = cost
	heap.Push(this, node)

}
Ejemplo n.º 15
0
func (g *Graph) update(n *Node, distance int) {
	if n.distance > distance {
		heap.Remove(g, n.index)
		n.distance = distance
		heap.Push(g, n)
	}
}
Ejemplo n.º 16
0
//
// 获取下一个可用的Worker
//
func (pq *PriorityQueue) NextWorker() *Worker {
	now := time.Now()
	for pq.Len() > 0 {
		result := (*pq)[0]

		if result.index != INVALID_INDEX && result.Expire.After(now) {
			// 只要活着,就留在优先级队列中,等待分配任务
			//			log.Println("Find Valid Worker...")

			result.priority -= 1

			// 调整Worker的优先级
			heap.Fix(pq, result.index)

			return result
		} else {
			if result.index != INVALID_INDEX {
				log.Errorf("Invalid Item index in PriorityQueue#NextWorker")
			} else {
				log.Println("Worker Expired")
				// 只有过期的元素才删除
				heap.Remove(pq, result.index)
			}
		}
	}

	log.Println("Has Not Worker...")
	return nil

}
Ejemplo n.º 17
0
func (s *sandboxData) rmEndpoint(ep *endpoint) int {
	ep.Lock()
	joinInfo := ep.joinInfo
	ep.Unlock()

	sb := s.sandbox()
	for _, i := range sb.Info().Interfaces() {
		// Only remove the interfaces owned by this endpoint from the sandbox.
		if ep.hasInterface(i.SrcName()) {
			if err := i.Remove(); err != nil {
				logrus.Debugf("Remove interface failed: %v", err)
			}
		}
	}

	// Remove non-interface routes.
	for _, r := range joinInfo.StaticRoutes {
		if err := sb.RemoveStaticRoute(r); err != nil {
			logrus.Debugf("Remove route failed: %v", err)
		}
	}

	// We don't check if s.endpoints is empty here because
	// it should never be empty during a rmEndpoint call and
	// if it is we will rightfully panic here
	s.Lock()
	highEpBefore := s.endpoints[0]
	var (
		i int
		e *endpoint
	)
	for i, e = range s.endpoints {
		if e == ep {
			break
		}
	}
	heap.Remove(&s.endpoints, i)
	var highEpAfter *endpoint
	if len(s.endpoints) > 0 {
		highEpAfter = s.endpoints[0]
	}

	s.Unlock()

	if highEpBefore != highEpAfter {
		s.updateGateway(highEpAfter)
	}

	s.Lock()
	s.refCnt--
	refCnt := s.refCnt
	s.Unlock()

	if refCnt == 0 {
		s.sandbox().Destroy()
	}

	return refCnt
}
Ejemplo n.º 18
0
func (sb *sandbox) clearNetworkResources(ep *endpoint) error {
	sb.Lock()
	osSbox := sb.osSbox
	sb.Unlock()
	if osSbox != nil {
		for _, i := range osSbox.Info().Interfaces() {
			// Only remove the interfaces owned by this endpoint from the sandbox.
			if ep.hasInterface(i.SrcName()) {
				if err := i.Remove(); err != nil {
					log.Debugf("Remove interface failed: %v", err)
				}
			}
		}

		ep.Lock()
		joinInfo := ep.joinInfo
		ep.Unlock()

		// Remove non-interface routes.
		for _, r := range joinInfo.StaticRoutes {
			if err := osSbox.RemoveStaticRoute(r); err != nil {
				log.Debugf("Remove route failed: %v", err)
			}
		}
	}

	sb.Lock()
	if len(sb.endpoints) == 0 {
		// sb.endpoints should never be empty and this is unexpected error condition
		// We log an error message to note this down for debugging purposes.
		log.Errorf("No endpoints in sandbox while trying to remove endpoint %s", ep.Name())
		sb.Unlock()
		return nil
	}

	highEpBefore := sb.endpoints[0]
	var (
		i int
		e *endpoint
	)
	for i, e = range sb.endpoints {
		if e == ep {
			break
		}
	}
	heap.Remove(&sb.endpoints, i)
	var highEpAfter *endpoint
	if len(sb.endpoints) > 0 {
		highEpAfter = sb.endpoints[0]
	}
	delete(sb.epPriority, ep.ID())
	sb.Unlock()

	if highEpBefore != highEpAfter {
		sb.updateGateway(highEpAfter)
	}

	return nil
}
Ejemplo n.º 19
0
Archivo: jobs.go Proyecto: logan/heim
func (jq *JobQueue) remove(jobID snowflake.Snowflake, err error) error {
	for i, entry := range jq.working {
		if entry.ID == jobID {
			heap.Remove(&jq.working, i)
			return nil
		}
	}

	for i, entry := range jq.available {
		if entry.ID == jobID {
			heap.Remove(&jq.available, i)
			return nil
		}
	}

	return jobs.ErrJobNotFound
}
Ejemplo n.º 20
0
//removeMessage removes the message from mh.
//If mh is empty, message is nil, or message is not in mh, then this is a nop
//and returns false.
//Returns true or false indicating whether or not message was actually removed
//from mh.
func (mh *messageHeap) removeMessage(message *Message) bool {
	if mh.Len() == 0 || message == nil || message.index == notInIndex || message.mh != mh {
		return false
	}
	result := heap.Remove(mh, message.index).(*Message)
	beforeRemoval(result)
	return true
}
Ejemplo n.º 21
0
func (q *writeQueue) deque() (Frame, bool) {
	if len(q.frames) > 0 {
		result := q.frames[0].frame
		heap.Remove(&q.frames, 0)
		return result, true
	}
	return nil, false
}
Ejemplo n.º 22
0
// Job is complete; update heap
func (b *Balancer) completed(w *Worker) {
	// One fewer in the queue.
	w.pending--
	// Remove it from heap.
	heap.Remove(&b.pool, w.index)
	// Put it into its place on the heap.
	heap.Push(&b.pool, w)
}
Ejemplo n.º 23
0
// remove removes an element from purgatory (if it's experienced an
// error) or from the priority queue by index. Caller must hold mutex.
func (bq *baseQueue) remove(item *replicaItem) {
	if _, ok := bq.mu.purgatory[item.value.RangeID]; ok {
		delete(bq.mu.purgatory, item.value.RangeID)
	} else {
		heap.Remove(&bq.mu.priorityQ, item.index)
	}
	delete(bq.mu.replicas, item.value.RangeID)
}
Ejemplo n.º 24
0
func (h *hostQueue) UpdatePriority(hostName string, priority int) {
	index := h.hostMap[hostName]
	host := h.hosts[index]
	host.priority = priority
	//heap.Fix(h, index)
	heap.Remove(h, index)
	heap.Push(h, host)
}
Ejemplo n.º 25
0
// calculates the shortest path between two GraphNodes;
// if no path is found, found will be false
func Path(from, to GraphNode) (path []GraphNode, distance int, found bool) {
	nodeMap := nodeMap{}
	queue := &PriorityQueue{}
	heap.Init(queue)
	fromNode := nodeMap.get(from)
	fromNode.open = true
	heap.Push(queue, (*item)(fromNode))
	for {
		if queue.Len() == 0 {
			// there's no path, return found false
			return
		}
		// priority queue does its magic:
		current := (*aStarNode)(heap.Pop(queue).(*item))
		current.open = false
		current.closed = true

		if current == nodeMap.get(to) {
			// found a path to the goal!
			reversePath := []GraphNode{}
			curr := current
			for curr != nil {
				reversePath = append(reversePath, curr.graphNode)
				curr = curr.parent
			}
			// reverse path to get from --> to
			path = make([]GraphNode, len(reversePath))
			j := 0
			for i := len(reversePath) - 1; i >= 0; i-- {
				path[j] = reversePath[i]
				j++
			}
			return path, current.cost, true
		}

		for _, neighbor := range current.graphNode.GetNeighbors() {
			cost := current.cost + current.graphNode.ActualNeighborCost(neighbor)
			neighborNode := nodeMap.get(neighbor)
			if cost < neighborNode.cost {
				// this branch is for handling nodes
				// that have already been assessed in previous iterations
				// where the new cost is cheaper
				if neighborNode.open {
					heap.Remove(queue, neighborNode.index)
				}
				neighborNode.open = false
				neighborNode.closed = false
			}
			if !neighborNode.open && !neighborNode.closed {
				neighborNode.cost = cost
				neighborNode.open = true
				neighborNode.rank = cost + neighbor.EstimatedTargetCost(to)
				neighborNode.parent = current
				heap.Push(queue, (*item)(neighborNode))
			}
		}
	}
}
Ejemplo n.º 26
0
func (m *memLS) hold(n *memLSNode) {
	if n.held {
		panic("webdav: memLS inconsistent held state")
	}
	n.held = true
	if n.details.Duration >= 0 && n.byExpiryIndex >= 0 {
		heap.Remove(&m.byExpiry, n.byExpiryIndex)
	}
}
Ejemplo n.º 27
0
//  Set a task's key with runtime O(n).
func (pq *PriorityQueue) SetKey(id int64, k float64) {
	var i, task = pq.h.FindId(id)
	if i < 0 {
		return
	}
	heap.Remove(pq.h, i)
	task.Task().(PrioritizedTask).SetKey(k)
	heap.Push(pq.h, task)
}
Ejemplo n.º 28
0
func (p *periodicHeap) Remove(job *structs.Job) error {
	if pJob, ok := p.index[job.ID]; ok {
		heap.Remove(&p.heap, pJob.index)
		delete(p.index, job.ID)
		return nil
	}

	return fmt.Errorf("heap doesn't contain job %v", job.ID)
}
Ejemplo n.º 29
0
// Remove will remove an identifier from the secondary index and deletes the
// corresponding node from the heap.
func (h *vaultClientHeap) Remove(id string) error {
	if entry, ok := h.heapMap[id]; ok {
		heap.Remove(&h.heap, entry.index)
		delete(h.heapMap, id)
		return nil
	}

	return fmt.Errorf("heap doesn't contain entry for %v", id)
}
Ejemplo n.º 30
0
func (stc *stopTimerCommand) Done(o *basic.Object) error {
	defer o.ProcessSeqnum()

	if v, ok := TimerModule.tq.ref[stc.h]; ok {
		heap.Remove(TimerModule.tq, v)
	}

	return nil
}