// peekToken performs lookahead of the given count on the token stream. func (l *peekableLexer) peekToken(count int) lexeme { if count < 1 { panic(fmt.Sprintf("Expected count > 1, received: %v", count)) } // Ensure that the readTokens has at least the requested number of tokens. if l.readTokens.Len() < count { for { l.readTokens.PushBack(l.lex.nextToken()) if l.readTokens.Len() == count { break } } } // Retrieve the count-th token from the list. var element *list.Element element = l.readTokens.Front() for i := 1; i < count; i++ { element = element.Next() } return element.Value.(lexeme) }
// listen is run in a goroutine. It reads new pull lists from its // input queue until the queue is closed. // listen takes ownership of the list that is passed to it. // // Note that the routine does not ever need to access the list // itself once the current_item has been initialized, so we do // not bother to keep a pointer to the list. Because it is a // doubly linked list, holding on to the current item will keep // it from garbage collection. // func (b *WorkQueue) listen() { var current_item *list.Element // When we're done, close the output channel to shut down any // workers. defer close(b.NextItem) for { // If the current list is empty, wait for a new list before // even checking if workers are ready. if current_item == nil { if p, ok := <-b.newlist; ok { current_item = p.Front() } else { // The channel was closed; shut down. return } } select { case p, ok := <-b.newlist: if ok { current_item = p.Front() } else { // The input channel is closed; time to shut down return } case b.NextItem <- current_item.Value: current_item = current_item.Next() } } }
// SetAsync 设置是否异步输出,仅当之前为非异步并且设置为异步时,logList和mu有效 func (this *SimpleLogWriter) SetAsync(async bool, logList *list.List, mu *sync.Mutex) { if !this.async && async { if logList == nil || mu == nil { panic(ErrorLogWriterInvalidParam) } this.logList = logList this.logmu = mu go func() { var counter = atomic.AddInt32(&this.counter, 1) for this.async && counter == this.counter && !this.closed { if this.logList.Len() > 0 { var start *list.Element var length = 0 this.logmu.Lock() if this.logList.Len() > 0 { start = this.logList.Front() length = this.logList.Len() this.logList.Init() } this.logmu.Unlock() for i := 0; i < length; i++ { var v, ok = start.Value.(string) if ok { this.writer.Write(v) } start = start.Next() } } else { time.Sleep(50 * time.Millisecond) } } }() } this.async = async }
// this time eviction is called by a scheduler for background, periodic evictions func TimeEvict(lru *LRUCache, now time.Time, ttl time.Duration) { lru.mu.Lock() defer lru.mu.Unlock() if lru.list.Len() < 1 { return } var n *entry var el *list.Element hasEvictCallback := lru.EvictCallback != nil el = lru.list.Back() for { if el == nil { break } n = el.Value.(*entry) if now.Sub(n.time_accessed) > ttl { // the Difference is greater than max TTL so we need to evict this entry // first grab the next entry (as this is about to dissappear) el = el.Prev() lru.remove(n.key) if hasEvictCallback { lru.EvictCallback(n.key, n.value) } } else { // since they are stored in time order, as soon as we find // first item newer than ttl window, we are safe to bail break } } lru.last_ttl_check = time.Now() }
// AsyncWrite 异步写入日志 func (this *ConsoleLogWriter) AsyncWrite(logList *list.List, mu *sync.Mutex) { this.logList = logList this.logmu = mu go func() { for !this.closed { if this.logList.Len() > 0 { var start *list.Element var length = 0 this.logmu.Lock() start = this.logList.Front() length = this.logList.Len() this.logList.Init() this.logmu.Unlock() for i := 0; i < length; i++ { var v, ok = start.Value.(string) if ok { this.Write(v) } start = start.Next() } } else { //暂停15毫秒 time.Sleep(15 * time.Millisecond) //runtime.Gosched() } } }() }
func (c *Cache) cleaner(limit int) { for _ = range c.clean { var item *list.Element for { c.lock.Lock() // X1+ if len(c.m) < limit { c.lock.Unlock() // X1- break } if item == nil { item = c.lru.Front() } if p := item.Value.(*cachepage); !p.dirty { delete(c.m, p.pi) c.lru.Remove(item) c.Purge++ } item = item.Next() c.lock.Unlock() // X1- } atomic.AddInt32(&c.cleaning, -1) } c.close <- true }
func listXmpl() { fmt.Println("Teste Liste") myList := list.New() // einige Elemente einfügen myList.PushFront(element2{"a", 1}) myList.PushFront(element2{"b", 2}) myList.PushFront(element2{"c", 3}) myList.PushFront(element2{"d", 4}) myList.PushFront(element2{"e", 5}) myList.PushFront(element2{"f", 6}) for e := myList.Front(); e != nil; e = e.Next() { fmt.Println(e.Value) } // Ein Element umsortieren fmt.Println("Gehe zum zweiten Element") // erstmal den Anfang holen var e *list.Element = myList.Front() // einen Schritt weiter, zum e gehen e = e.Next() // Ausgeben zum Test fmt.Println("aktuell:", e.Value) fmt.Println("Verschiebe Element ans Listenende") // und e/5 ans Ende verbannen myList.MoveToBack(e) // nochmal mittels Iterator Elemente auslesen for e := myList.Front(); e != nil; e = e.Next() { fmt.Println(e.Value) } }
// Returns the item after e or nil it is the last item or nil. // The item is a *list.Element from the 'container/list' package. // Even though it is possible to call e.Next() directly, don't. This behavior // may not be supported moving forward. func (q Queue) Next(e *list.Element) *list.Element { if e == nil { return e } return e.Next() }
func TestInsertBefore(t *testing.T) { var e *list.Element l := list.New() for i := 0; i < 5; i++ { if i == 3 { e = l.PushFront(i) } else { l.PushFront(i) } } l.InsertBefore(5, e) if l.Len() != 6 { t.Errorf("length = %d", l.Len()) } e = l.Front() for i := 0; i < 6; i++ { t.Logf("e = %d", e.Value) e = e.Next() } }
// C & U func (node Node) Update(cmp *RemoteNode) { bucketID := node.ID.DistanceTo(cmp.ID).GetBucketID() bucket := node.RoutingTable[bucketID] var found bool = false var foundElement *list.Element for elem := bucket.Front(); elem != nil; elem = elem.Next() { e, ok := elem.Value.(*RemoteNode) if !ok { continue // if it's not a NodeID, wtf is it doing in the list?? Probably should error out } if e.ID.EqualsTo(cmp.ID) || e.ID.EqualsTo(node.ID) { found = true foundElement = elem break } } if !found { if bucket.Len() <= BUCKET_SIZE { bucket.PushFront(cmp) } } else { foundElement.Value = cmp // update the foundElement value bucket.MoveToFront(foundElement) } }
func (s *Summary) incrElement(el *list.Element) { counter := el.Value.(*Counter) counter.count++ // This element already has the largest count so it won't get moved. if s.list.Front() == el { return } // Starting at the previous element, move this element behind the first // element we find which has a higher count. moved := false for currEl := el.Prev(); currEl != nil; currEl = currEl.Prev() { if currEl.Value.(*Counter).count > counter.count { s.list.MoveAfter(el, currEl) moved = true break } } // If we didn't find an element with a higher count then this element must // have the highest count. Move it to the front. if !moved { s.list.MoveToFront(el) } }
/* Create tree ball list with id random. If Ball is already taked, a first ball next is taked */ func (Data *Data) Manage_magnet(requete *list.Element, Tab_wd *owm.All_data) { rqt := requete.Value.(*protocol.Request) var tab [3]int64 list_tmp := list.New() var ifball Posball user := Data.User.Value.(*users.User) var answer []byte var eball *list.Element if user.MagnetisValid() == true { if Data.Lst_ball.Id_max > 0 { for i := 0; i < 3; i++ { tab[i] = rand.Int63n(Data.Lst_ball.Id_max) } list_tmp_2 := Data.Lst_ball.Get_ballbyid_tomagnet(tab, Data.User) eball = list_tmp_2.Front() } for eball != nil { ball := eball.Value.(*list.Element).Value.(*ballon.Ball) ifball.id = ball.Id_ball ifball.title = ball.Title ifball.FlagPoss = 0 ifball.lon = ball.Coord.Value.(ballon.Checkpoint).Coord.Lon ifball.lat = ball.Coord.Value.(ballon.Checkpoint).Coord.Lat ifball.wins = ball.Wind.Speed ifball.wind = ball.Wind.Degress list_tmp.PushBack(ifball) eball = eball.Next() } answer = Write_nearby(requete, list_tmp, MAGNET, user) } else { answer = Data.Manage_ack(rqt.Rtype, 0, 0) } Data.Lst_asw.PushBack(answer) }
func findRefKClosestTo(kadems []*Kademlia, portrange int, searchID ID, KConst int) *list.List { var retList *list.List = list.New() for i := 0; i < len(kadems); i++ { var newNodeID ID var newNodeIDDist int newNodeID = CopyID(kadems[i].ContactInfo.NodeID) newNodeIDDist = newNodeID.Distance(searchID) var e *list.Element = retList.Front() for ; e != nil; e = e.Next() { var dist int dist = e.Value.(ID).Distance(searchID) //if responseNode is closer than node in ShortList, add it if newNodeIDDist < dist { retList.InsertBefore(newNodeID, e) //node inserted! getout break } } if e == nil { //node is farthest yet retList.PushBack(newNodeID) } } return retList }
func compareClosestContacts(fn []FoundNode, kadems []*Kademlia, portrange int, searchID ID) { var closestList *list.List = findRefKClosestTo(kadems, portrange, searchID, KConst) /* var pE *list.Element = closestList.Front() for ; pE != nil; pE = pE.Next(){ log.Printf("Sorted? %s %d\n", pE.Value.(ID).AsString(), pE.Value.(ID).Distance(searchID)) }*/ var e *list.Element = closestList.Front() var overlap int = 0 //log.Printf("searching for:%s\n", searchID.AsString()) //log.Printf("reference List: \t\t\t\t\t iterativeFound List:\n") for i := 0; i < len(fn); i++ { var id ID = e.Value.(ID) //log.Printf("[%d]:%s %d\t%s %d", i, id.AsString(), id.Distance(searchID), fn[i].NodeID.AsString(), fn[i].NodeID.Distance(searchID)) if id.Equals(fn[i].NodeID) { overlap++ } else { for k := closestList.Front(); k != nil; k = k.Next() { if k.Value.(ID).Equals(fn[i].NodeID) { overlap++ } } } e = e.Next() } if overlap < 5 { log.Printf("overlap of %d. Out of %d total nodes\n", overlap, portrange) panic(1) } //return retContacts }
func defSetup(e *list.Element, s *env.Scope) (*parse.Atom, error) { name := e.Next().Value.(*parse.Atom).Value.(string) val, err := eval(e.Next().Next().Value, s) if err != nil { return nil, err } return Def(name, val, s), nil }
func (c *Client) requeue(cursor *list.Element) { // If `cursor` is not nil, this means there are notifications that // need to be delivered (or redelivered) for ; cursor != nil; cursor = cursor.Next() { if n, ok := cursor.Value.(Notification); ok { go func() { c.notifs <- n }() } } }
func ifSetup(e *list.Element, s *env.Scope) (*parse.Atom, error) { test, err := eval(e.Next().Value, s) if err != nil { return nil, err } thenStmt := e.Next().Next().Value elseStmt := e.Next().Next().Next().Value return If(test, thenStmt, elseStmt, s) }
// Removes as space map element from a space map cell and removes it, // or return nil if not found func (cell *SpaceMapCell) Remove(el SpaceMapElement) SpaceMapElement { var e *list.Element for e = cell.Shapes.Front(); e != nil; e = e.Next() { val := e.Value if val.(SpaceMapElement) == el { cell.Shapes.Remove(e) return el } } return nil }
// ListTruncate() removes elements from `e' to the last element in list `l'. // The range to be removed is [e, l.Back()]. It returns list `l'. func ListTruncate(l *list.List, e *list.Element) *list.List { AssertNotEqual(nil, l) AssertNotEqual(nil, e) // remove `e' and all elements after `e' var next *list.Element for ; e != nil; e = next { next = e.Next() l.Remove(e) } return l }
// Finalize and free the cached prepared statements // To be called in Conn#Close func (c *cache) flush() { if c.maxSize <= 0 { return } c.m.Lock() defer c.m.Unlock() var e, next *list.Element for e = c.l.Front(); e != nil; e = next { next = e.Next() c.l.Remove(e).(*Stmt).finalize() } }
//recursive function to find the kth from last element func findKFromLastRecr(l *list.Element, k int) WrapObj { if l.Next() == nil { return WrapObj{1, l.Value.(int)} } resObj := findKFromLastRecr(l.Next(), k) resObj = WrapObj{resObj.count + 1, l.Value.(int)} if resObj.count == k { return resObj } return resObj }
func firstNodeAfterTime(node *list.Element, cutoff time.Time) (*list.Element, bool) { for ; node != nil; node = node.Next() { tick := node.Value.(Tick) // log.Printf("Is %v > %v ?\n", tick.Time, cutoff) if tick.Time.After(cutoff) { return node, true } } return nil, false }
func (this *Chart) loadSentence(s *Sentence, k int) { var j, n int var w *list.Element //println("Loading sentence") n = s.Len() this.table = make([]*list.List, (1+n)*n/2) //println("Loading sentence 2") j = 0 l := list.New() for w = s.Front(); w != nil; w = w.Next() { ce := list.New() //println("Processing word " + w.Value.(*Word).getForm()) for a := w.Value.(*Word).selectedBegin(k).Element; a != w.Value.(*Word).selectedBegin(k).Next(); a = a.Next() { //println("selected tags") e := NewEdgeFromString(a.Value.(*Analysis).getTag(), l, 0) ce.PushBack(e) //println(" created edge " + a.Value.(*Analysis).getTag() + " in cell (0," + strconv.Itoa(j) + ")") this.findAllRules(e, ce, 0, j) e1 := NewEdgeFromString(a.Value.(*Analysis).getTag()+"("+w.Value.(*Word).getLCForm()+")", l, 0) ce.PushBack(e1) //println(" created edge " + a.Value.(*Analysis).getTag() + "(" + w.Value.(*Word).getLCForm() + ") in cell (0," + strconv.Itoa(j) + ")") this.findAllRules(e1, ce, 0, j) e2 := NewEdgeFromString(a.Value.(*Analysis).getTag()+"<"+a.Value.(*Analysis).getLemma()+">", l, 0) ce.PushBack(e2) //println(" created edge " + a.Value.(*Analysis).getTag() + "<" + a.Value.(*Analysis).getLemma() + "> in cell (0," + strconv.Itoa(j) + ")") this.findAllRules(e2, ce, 0, j) } this.table[this.index(0, j)] = ce j++ } this.size = j for k := 0; k < j; k++ { //println("Rule[", k, "]=", this.table[this.index(0, k)].Len()) ce := this.table[this.index(0, k)] //println("Found", ce.Len(), "Rules") for e := ce.Front(); e != nil; e = e.Next() { //println(e.Value.(*Edge).String()) //println("_______") } //println("=========") } //println("Sentence loaded") }
func main() { var n, m int fmt.Fscan(reader, &n, &m) w := make([]int, n) b := make([]int, m) d := make([]int, n) rs := list.New() for i := 0; i < n; i++ { fmt.Fscan(reader, &w[i]) } for i := 0; i < m; i++ { var j int fmt.Fscan(reader, &j) b[i] = j - 1 } for i := 0; i < m; i++ { if d[b[i]] == 0 { rs.PushBack(b[i]) } d[b[i]] = 1 } for i := 0; i < n; i++ { if d[i] == 0 { rs.PushBack(i) } d[i] = 1 } var res int for i := 0; i < m; i++ { e := new(list.Element) for e = rs.Front(); e != nil; e = e.Next() { if e.Value == b[i] { break } j, _ := e.Value.(int) res += w[j] } rs.Remove(e) rs.PushFront(e.Value) } fmt.Println(res) }
func (m *ChsFullTextMatch) mergeAllCombinations(redundancy int) *list.List { result := list.New() if (redundancy == 0 || !m.options.MultiDimensionality) && !m.options.ForceSingleWord { for _, v := range m.allCombinations[0] { result.PushBack(v) } return result } i := 0 var cur *list.Element forceOnce := false loop: for i <= redundancy && i < len(m.allCombinations) { cur = result.Front() for j := 0; j < len(m.allCombinations[i]); j++ { m.allCombinations[i][j].Level = i if cur != nil { for cur.Value.(dict.PositionLength).Position < m.allCombinations[i][j].Position { cur = cur.Next() if cur == nil { break } } if cur != nil { if cur.Value.(dict.PositionLength).Position != m.allCombinations[i][j].Position || cur.Value.(dict.PositionLength).Length != m.allCombinations[i][j].Length { result.InsertBefore(m.allCombinations[i][j], cur) } } else { result.PushBack(m.allCombinations[i][j]) } } else { result.PushBack(m.allCombinations[i][j]) } } i++ } if m.options.ForceSingleWord && !forceOnce { i = len(m.allCombinations) - 1 redundancy = i forceOnce = true goto loop } return result }
func (this *Chart) cover(a, b int) *list.List { x := 0 y := 0 var i, j int var f bool var ed *list.Element var lp, lr *list.List if a < 0 || b < 0 || a+b >= this.size { return list.New() } //println("Covering under (" + strconv.Itoa(a) + "," + strconv.Itoa(b) + ")") f = false best := NewEdge() for i = a; !f && i >= 0; i-- { for j = b; j < b+(a-i)+1; j++ { //println("ED len:" + strconv.Itoa(this.table[this.index(i, j)].Len())) for ed = this.table[this.index(i, j)].Front(); ed != nil; ed = ed.Next() { LOG.Tracef("ed.active:%b 1st best:%b", ed.Value.(*Edge).active(), this.betterEdge(ed.Value.(*Edge), best)) if !ed.Value.(*Edge).active() && this.betterEdge(ed.Value.(*Edge), best) { x = i y = j best = ed.Value.(*Edge) f = true } } } } //println(" Highest cell found is (" + strconv.Itoa(x) + "," + strconv.Itoa(y) + ")") //println(" Pending (" + strconv.Itoa(y-b-1) + "," + strconv.Itoa(b) + ") (" + strconv.Itoa((a+b)-(x+y+1)) + "," + strconv.Itoa(x+y+1) + ")") if !f { LOG.Panic("Inconsistent chart or wrongly loaded sentence") } lp = this.cover(y-b-1, b) lr = this.cover((a+b)-(x+y+1), x+y+1) lp.PushBack(Pair{x, y}) for tlr := lr.Front(); tlr != nil; tlr = tlr.Next() { lp.PushBack(tlr.Value.(Pair)) } return lp }
func (me *orderedList) ValueChanged(e *list.Element) { for prev := e.Prev(); prev != nil && me.lessFunc(e.Value, prev.Value); prev = e.Prev() { me.list.MoveBefore(e, prev) } for next := e.Next(); next != nil && me.lessFunc(next.Value, e.Value); next = e.Next() { me.list.MoveAfter(e, next) } }
func (this *Dictionary) Analyze(se *Sentence) { contr := false for pos := se.Front(); pos != nil; pos = pos.Next() { LOG.Tracef("Processing: %s - %d %s", pos.Value.(*Word).getForm(), pos.Value.(*Word).getNAnalysis(), string(pos.Value.(*Word).getTag(0))) if pos.Value.(*Word).getNAnalysis() == 0 || (pos.Value.(*Word).getNAnalysis() > 0 && string(pos.Value.(*Word).getTag(0)[0]) == "Z") { LOG.Trace("Annotating word:" + pos.Value.(*Word).getForm()) lw := list.New() if this.AnnotateWord(pos.Value.(*Word), lw, false) { st := pos.Value.(*Word).getSpanStart() fin := pos.Value.(*Word).getSpanFinish() LOG.Trace("Contraction found, replacing... " + pos.Value.(*Word).getForm() + ". span=(" + strconv.Itoa(int(st)) + "," + strconv.Itoa(int(fin)) + ")") step := (float64(fin) - float64(st) + 1.0) / float64(lw.Len()) step = math.Max(1, step) ln := math.Max(1, step-1.0) var n int var i *list.Element n = 1 for i = lw.Front(); i != nil; i = i.Next() { f := If(n == lw.Len(), fin, st+int(ln)).(int) i.Value.(*Word).setSpan(st, f) i.Value.(*Word).user = pos.Value.(*Word).user LOG.Trace(" Inserting " + i.Value.(*Word).getForm() + ". span=(" + strconv.Itoa(int(st)) + "," + strconv.Itoa(int(fin)) + ")") pos = se.InsertBefore(i.Value.(*Word), pos) pos = pos.Next() st = st + int(step) contr = true } LOG.Trace(" Erasing " + pos.Value.(*Word).getForm()) q := pos q = q.Prev() se.Remove(pos) pos = q } } } if contr { se.rebuildWordIndex() } }
//--------------------------------------------------------------------- // parse data //--------------------------------------------------------------------- func ikcp_parse_data(kcp *Ikcpcb, newseg *IKCPSEG) { var p *list.Element sn := newseg.sn repeat := 0 if _itimediff(sn, kcp.rcv_nxt+kcp.rcv_wnd) >= 0 || _itimediff(sn, kcp.rcv_nxt) < 0 { return } for p = kcp.rcv_buf.Back(); p != nil; p = p.Prev() { seg := p.Value.(*IKCPSEG) if seg.sn == sn { repeat = 1 break } if _itimediff(sn, seg.sn) > 0 { break } } if repeat == 0 { if p == nil { kcp.rcv_buf.PushFront(newseg) } else { kcp.rcv_buf.InsertAfter(newseg, p) } kcp.nrcv_buf++ } else { } for p = kcp.rcv_buf.Front(); p != nil; { seg := p.Value.(*IKCPSEG) if seg.sn == kcp.rcv_nxt && kcp.nrcv_que < kcp.rcv_wnd { q := p.Next() kcp.rcv_buf.Remove(p) p = q kcp.nrcv_buf-- kcp.rcv_queue.PushBack(seg) //if kcp.user[0] == 0 { //fmt.Println("insert from recvqueue2", kcp.rcv_queue.Len(), kcp.user) //} kcp.nrcv_que++ kcp.rcv_nxt++ } else { break } } //println("inputok!!!", kcp.nrcv_buf, kcp.nrcv_que, repeat, kcp.rcv_nxt, sn) }
func lambdaSetup(e *list.Element, s *env.Scope) (*parse.Atom, error) { arglist := e.Next().Value.(*list.List) args := make([]string, 0) for a := arglist.Front(); a != nil; a = a.Next() { args = append(args, a.Value.(*parse.Atom).Value.(string)) } body := make([]interface{}, 0) for b := e.Next().Next(); b != nil; b = b.Next() { body = append(body, b.Value) } // taking liberties with the name "Atom" return &parse.Atom{ Value: Lambda(args, body, env.New(s)), Type: "function", }, nil }