// use win-rate distribution of node to play a legal move in tracker func (node *Node) seed(t Tracker, path []int) bool { if node.parent == nil { return false } dist := new(vector.Vector) sum := 0.0 for sibling := node.parent.Child; sibling != nil; sibling = sibling.Sibling { for i := 0; i < len(path); i++ { if sibling.Vertex == path[i] { continue } } dist.Push(sibling.blendedMean) sum += sibling.blendedMean } node.totalseeds++ r := rand.Float64() * sum for i := 0; i < dist.Len(); i++ { r -= dist.At(i).(float64) if r <= 0 { if t.Legal(node.Color, i) { t.Play(node.Color, i) node.seeds++ return true } return false } } return false }
// Fetch all remaining results. If we get no results at // all, an error will be returned; otherwise it probably // still occurred but will be hidden. func ClassicFetchAll(rs ClassicResultSet) (data [][]interface{}, error os.Error) { var v vector.Vector var d interface{} var e os.Error for rs.More() { r := rs.Fetch() d = r.Data() if d != nil { v.Push(d) } e = r.Error() if e != nil { break } } l := v.Len() if l > 0 { // TODO: how can this be done better? data = make([][]interface{}, l) for i := 0; i < l; i++ { data[i] = v.At(i).([]interface{}) } } else { // no results at all, return the error error = e } return }
func makeBugDocs(v *vector.Vector) []string { d := make([]string, v.Len()) for i := 0; i < v.Len(); i++ { d[i] = CommentText(v.At(i).(*ast.CommentGroup)) } return d }
func main(){ var v vector.Vector v.Push(1234.) //stored as interface value i := v.At(0) if i.(float64) != 1234. {} //if i.(int) != 1234 {} //runtime err, as the cast fails //if i.(MyFloat) != 1234. {} //err, MyFloat unknown v.Push(666) v.Push("foobar") for _, elem := range v{ if i, ok := elem.(int); ok { fmt.Printf("int: %d\n", i) } else if f, ok := elem.(float64); ok { fmt.Printf("float64: %g\n", f) } else { fmt.Print("unknown type\n") } } for _, elem := range v{ switch v := elem.(type){ case int: fmt.Printf("is int: %d\n", v) case float64: fmt.Printf("is float64: %g\n", v) default: fmt.Print("unknown type\n") } } }
// Next will chose a random point to put a piece. func (ap *RandomPlayer) Next(m *match.Match) *match.Response { color := ap.teban.Color() candidates := new(vector.Vector) size := m.Board.Size() for y := 1; y <= size; y++ { for x := 1; x <= size; x++ { if m.Board.CanPutAt(color, x, y, m.History) { if !m.Board.IsEye(color, x, y) { candidates.Push(&point.Point{x, y}) } } } } if candidates.Len() != 0 { bs := make([]byte, 1) _, err := rand.Read(bs) if err == nil { p := candidates.At(int(bs[0]) % candidates.Len()).(*point.Point) ts, resp := m.Board.PutAt(color, p.X(), p.Y(), m.History) if resp == board.OK { fmt.Printf("[random] put %d,%d\n", p.X(), p.Y()) return match.NewPutResponse(p.X(), p.Y(), ts) } } } return match.NewPassResponse() }
func (p *parser) parseExpression() Expression { var list vector.Vector for { x := p.parseSequence() if x != nil { list.Push(x) } if p.tok != token.OR { break } p.next() } // no need for an Alternative node if list.Len() < 2 switch list.Len() { case 0: return nil case 1: return list.At(0).(Expression) } // convert list into an Alternative node alt := make(Alternative, list.Len()) for i := 0; i < list.Len(); i++ { alt[i] = list.At(i).(Expression) } return alt }
func makeStmtList(list *vector.Vector) []ast.Stmt { stats := make([]ast.Stmt, list.Len()) for i := 0; i < list.Len(); i++ { stats[i] = list.At(i).(ast.Stmt) } return stats }
func renderSection(section *sectionElement, context reflect.Value, buf io.Writer) { value := lookup(context, section.name) valueInd := reflect.Indirect(value) var contexts = new(vector.Vector) switch val := valueInd.(type) { case *reflect.BoolValue: if !val.Get() { return } else { contexts.Push(context) } case *reflect.SliceValue: for i := 0; i < val.Len(); i++ { contexts.Push(val.Elem(i)) } case *reflect.ArrayValue: for i := 0; i < val.Len(); i++ { contexts.Push(val.Elem(i)) } default: contexts.Push(context) } //by default we execute the section for j := 0; j < contexts.Len(); j++ { ctx := contexts.At(j).(reflect.Value) for i := 0; i < section.elems.Len(); i++ { renderElement(section.elems.At(i), ctx, buf) } } }
func (p *parser) parseStructType() *ast.StructType { if p.trace { defer un(trace(p, "StructType")) } pos := p.expect(token.STRUCT) lbrace := p.expect(token.LBRACE) list := new(vector.Vector) for p.tok == token.IDENT || p.tok == token.MUL { f := p.parseFieldDecl() if p.tok != token.RBRACE { p.expect(token.SEMICOLON) } f.Comment = p.lineComment list.Push(f) } rbrace := p.expect(token.RBRACE) p.optSemi = true // convert vector fields := make([]*ast.Field, list.Len()) for i := list.Len() - 1; i >= 0; i-- { fields[i] = list.At(i).(*ast.Field) } return &ast.StructType{pos, lbrace, fields, rbrace, false} }
func (p *parser) parseInterfaceType() *ast.InterfaceType { if p.trace { defer un(trace(p, "InterfaceType")) } pos := p.expect(token.INTERFACE) lbrace := p.expect(token.LBRACE) list := new(vector.Vector) for p.tok == token.IDENT { m := p.parseMethodSpec() if p.tok != token.RBRACE { p.expect(token.SEMICOLON) } m.Comment = p.lineComment list.Push(m) } rbrace := p.expect(token.RBRACE) p.optSemi = true // convert vector methods := make([]*ast.Field, list.Len()) for i := list.Len() - 1; i >= 0; i-- { methods[i] = list.At(i).(*ast.Field) } return &ast.InterfaceType{pos, lbrace, methods, rbrace, false} }
func (p *parser) parseLiteral() literal { s := []byte(p.parseString()) // A string literal may contain %-format specifiers. To simplify // and speed up printing of the literal, split it into segments // that start with "%" possibly followed by a last segment that // starts with some other character. var list vector.Vector i0 := 0 for i := 0; i < len(s); i++ { if s[i] == '%' && i+1 < len(s) { // the next segment starts with a % format if i0 < i { // the current segment is not empty, split it off list.Push(s[i0:i]) i0 = i } i++ // skip %; let loop skip over char after % } } // the final segment may start with any character // (it is empty iff the string is empty) list.Push(s[i0:]) // convert list into a literal lit := make(literal, list.Len()) for i := 0; i < list.Len(); i++ { lit[i] = list.At(i).([]byte) } return lit }
func test1() { var a [1000]*S for i := 0; i < len(a); i++ { a[i] = new(S).Init(i) } v := new(vector.Vector) for i := 0; i < len(a); i++ { v.Insert(0, a[i]) if v.Len() != i+1 { panic("len = ", v.Len(), "\n") } } for i := 0; i < v.Len(); i++ { x := v.At(i).(*S) if x.val != v.Len()-i-1 { panic("expected ", i, ", found ", x.val, "\n") } } for v.Len() > 10 { v.Delete(10) } }
// Consume a group of adjacent comments, add it to the parser's // comments list, and return the line of which the last comment // in the group ends. An empty line or non-comment token terminates // a comment group. // func (p *parser) consumeCommentGroup() int { list := new(vector.Vector) endline := p.pos.Line for p.tok == token.COMMENT && endline+1 >= p.pos.Line { var comment *ast.Comment comment, endline = p.consumeComment() list.Push(comment) } // convert list group := make([]*ast.Comment, list.Len()) for i := 0; i < list.Len(); i++ { group[i] = list.At(i).(*ast.Comment) } // add comment group to the comments list g := &ast.CommentGroup{group, nil} if p.lastComment != nil { p.lastComment.Next = g } else { p.comments = g } p.lastComment = g return endline }
// takes vector of nodes, returns sequential schedule length func SeqTime(v vec.Vector) int64 { var s int64 s = 0 for i := 0; i < v.Len(); i++ { s += (v.At(i).(*p.Node)).Ex } return s }
func _AppendParamsData(buff *bytes.Buffer, sig string, params *vector.Vector) { sigOffset := 0 prmsOffset := 0 for ; sigOffset < len(sig); prmsOffset++ { offset, _ := _AppendValue(buff, sig[sigOffset:len(sig)], params.At(prmsOffset)) sigOffset += offset } }
// get the index of a node in a vector given nodes ID func GetIndexById(v vector.Vector, id int) int { for i := 0; i < v.Len(); i++ { if v.At(i).(*Node).Id == id { return i } } return -1 }
func process(c Conn, in chan paxos.Packet, out <-chan paxos.Packet) { pend := make(map[string]bool) h := new(vector.Vector) ticker := time.NewTicker(interval / 4) defer ticker.Stop() rawIn := make(chan paxos.Packet) go func() { recv(c, rawIn) close(rawIn) }() peek := func() check { if h.Len() < 1 { return check{at: math.MaxInt64} } return h.At(0).(check) } for { select { case p := <-rawIn: if closed(rawIn) { return } if p.Msg.HasFlags(paxos.Ack) { if pend[p.Id()] { pend[p.Id()] = false, false } continue } in <- p // send ack write(c, p.Msg.Dup().SetFlags(paxos.Ack), p.Addr) case p := <-out: pend[p.Id()] = true write(c, p.Msg, p.Addr) t := time.Nanoseconds() heap.Push(h, check{p, t + interval, t + timeout}) case t := <-ticker.C: for k := peek(); k.at < t; k = peek() { heap.Pop(h) if t > k.until { pend[k.Id()] = false, false } if pend[k.Id()] { write(c, k.Msg, k.Addr) heap.Push(h, check{k.Packet, t + interval, k.until}) } } } } }
// Given the id of a task that has been scheduled on a processor // return the index of that Task's Event entry func findInSchedule(v vec.Vector, id int) int { for i := 0; i < len(v); i++ { if v.At(i).(*Event).id == id { return i } } return -1 }
func NewSoyListDataFromVector(o *vector.Vector) SoyListData { if o == nil { return &soyListData{l: list.New()} } l := list.New() for i := 0; i < o.Len(); i++ { l.PushBack(o.At(i)) } a := &soyListData{l: l} return a }
func (self Transformer) split(arr *vec.Vector, index, inside int) { mut := arr.At(index) if IsDeleteMutation(mut) { arr.Insert(index+1, NewDeleteMutation(toDeleteMutation(mut).Count()-inside)) toDeleteMutation(mut).SetCount(inside) } else if IsSkipMutation(mut) { arr.Insert(index+1, NewSkipMutation(toSkipMutation(mut).Count()-inside)) toSkipMutation(mut).SetCount(inside) } else { panic("Unsupported mutation for split()") } }
func BenchmarkGenericVector(b *testing.B) { for i := 0; i < b.N; i++ { var vec vector.Vector for j := 0; j < vectorLength; j++ { vec.Push(j) } for j := 0; j < vectorLength; j++ { val, _ := vec.At(j).(int) val++ } } }
// navigate through the tree until a leaf node is found to playout func (root *Node) step(t Tracker) { var start int64 path := new(vector.Vector) start = time.Nanoseconds() curr := root.Next(root, t) root.next_time += time.Nanoseconds() - start root.next_count++ if curr == nil { root.Visits = math.Inf(1) return } for { path.Push(curr) // apply node's position to the board start = time.Nanoseconds() t.Play(curr.Color, curr.Vertex) root.play_time += time.Nanoseconds() - start root.play_count++ if curr.Visits <= root.config.ExpandAfter { var color byte if root.config.Seed { color = curr.seedPlayout(t) } else { color = Reverse(curr.Color) } start = time.Nanoseconds() t.Playout(color) root.playout_time += time.Nanoseconds() - start break } time.Nanoseconds() next := curr.Next(root, t) root.next_time += time.Nanoseconds() - start root.next_count++ curr = next if curr == nil { break } } start = time.Nanoseconds() winner := t.Winner() root.win_calc_time += time.Nanoseconds() - start start = time.Nanoseconds() for j := 0; j < path.Len(); j++ { path.At(j).(*Node).update(t) } root.update_time += time.Nanoseconds() - start if winner == Reverse(root.Color) { root.Wins++ } root.Visits++ root.Mean = root.Wins / root.Visits }
func (p *parser) makeIdentList(list *vector.Vector) []*ast.Ident { idents := make([]*ast.Ident, list.Len()) for i := 0; i < list.Len(); i++ { ident, isIdent := list.At(i).(*ast.Ident) if !isIdent { pos := list.At(i).(ast.Expr).Pos() p.errorExpected(pos, "identifier") idents[i] = &ast.Ident{pos, ast.NewObj(ast.Err, pos, "")} } idents[i] = ident } return idents }
func TestSchedTrigger(t *testing.T) { q := new(vector.Vector) d := int64(15e8) ts := time.Nanoseconds() + d schedTrigger(q, 1, d) assert.Equal(t, 1, q.Len()) f, ok := q.At(0).(trigger) assert.Tf(t, ok, "expected a trigger, got a %T", q.At(0)) assert.Equal(t, int64(1), f.n) assert.T(t, f.t >= ts) }
// Evaluate interfaces and pointers looking for a value that can look up the name, via a // struct field, method, or map key, and return the result of the lookup. func lookup(contextChain *vector.Vector, name string) reflect.Value { defer func() { if r := recover(); r != nil { fmt.Printf("Panic while looking up %q: %s\n", name, r) } }() Outer: for i := contextChain.Len() - 1; i >= 0; i-- { v := contextChain.At(i).(reflect.Value) for v.IsValid() { typ := v.Type() if n := v.Type().NumMethod(); n > 0 { for i := 0; i < n; i++ { m := typ.Method(i) mtyp := m.Type if m.Name == name && mtyp.NumIn() == 1 { return v.Method(i).Call(nil)[0] } } } if name == "." { return v } switch av := v; av.Kind() { case reflect.Ptr: v = av.Elem() case reflect.Interface: v = av.Elem() case reflect.Struct: ret := av.FieldByName(name) if ret.IsValid() { return ret } else { continue Outer } case reflect.Map: ret := av.MapIndex(reflect.ValueOf(name)) if ret.IsValid() { return ret } else { continue Outer } default: continue Outer } } } return reflect.Value{} }
func (e *XMLConnector) match(conds vector.Vector, row map[string]Value) bool { if conds.Len() == 0 { return true } //fast out for i := range conds { cond := conds.At(i).(*Condition) if !e.match_one(cond, row) { return false } } return true }
func (p *parser) parseFieldDecl() *ast.Field { if p.trace { defer un(trace(p, "FieldDecl")) } doc := p.leadComment // a list of identifiers looks like a list of type names var list vector.Vector for { // TODO(gri): do not allow ()'s here list.Push(p.parseType()) if p.tok != token.COMMA { break } p.next() } // if we had a list of identifiers, it must be followed by a type typ := p.tryType() // optional tag var tag []*ast.BasicLit if p.tok == token.STRING { x := &ast.BasicLit{p.pos, p.tok, p.lit} p.next() tag = []*ast.BasicLit{x} } // analyze case var idents []*ast.Ident if typ != nil { // IdentifierList Type idents = p.makeIdentList(&list) } else { // Type (anonymous field) if len(list) == 1 { // TODO(gri): check that this looks like a type typ = list.At(0).(ast.Expr) } else { p.errorExpected(p.pos, "anonymous field") typ = &ast.BadExpr{p.pos} } } p.expectSemi() return &ast.Field{doc, idents, typ, tag, p.lineComment} }
func makeValueDocs(v *vector.Vector, tok token.Token) []*ValueDoc { d := make([]*ValueDoc, v.Len()) // big enough in any case n := 0 for i := range d { decl := v.At(i).(*ast.GenDecl) if decl.Tok == tok { d[n] = &ValueDoc{CommentText(decl.Doc), decl, i} n++ decl.Doc = nil // doc consumed - removed from AST } } d = d[0:n] sort.Sort(sortValueDoc(d)) return d }
func applyTriggers(packets, ticks *vector.Vector, now int64, tpl *M) (n int) { for ticks.Len() > 0 { tt := ticks.At(0).(trigger) if tt.t > now { break } heap.Pop(ticks) p := packet{M: *tpl} p.M.Seqn = &tt.n heap.Push(packets, p) n++ } return }
func (p *parser) parseFile() *ast.File { if p.trace { defer un(trace(p, "File")) } // package clause doc := p.leadComment pos := p.expect(token.PACKAGE) ident := p.parseIdent() // Common error: semicolon after package clause. // Accept and report it for better error synchronization. if p.tok == token.SEMICOLON { p.Error(p.pos, "expected declaration, found ';'") p.next() } var decls []ast.Decl // Don't bother parsing the rest if we had errors already. // Likely not a Go source file at all. if p.ErrorCount() == 0 && p.mode&PackageClauseOnly == 0 { // import decls list := new(vector.Vector) for p.tok == token.IMPORT { decl, _ := p.parseGenDecl(token.IMPORT, parseImportSpec, true) // consume optional semicolon list.Push(decl) } if p.mode&ImportsOnly == 0 { // rest of package body for p.tok != token.EOF { decl, _ := p.parseDecl(true) // consume optional semicolon list.Push(decl) } } // convert declaration list decls = make([]ast.Decl, list.Len()) for i := 0; i < list.Len(); i++ { decls[i] = list.At(i).(ast.Decl) } } return &ast.File{doc, pos, ident, decls, p.comments} }