func genLcg(mmax, cmax int64) (m, a, c int64) { m = rand.Int63n(mmax-1) + 1 a = rand.Int63n(cmax) c = rand.Int63n(cmax) return }
func TestKeyBitcountAddAndRemove(t *testing.T) { const loopsz = 1000 bset := Make() for i := 0; i < loopsz; i++ { bset.Add(i) checkbitcount(bset, "add(sequence)", t) } for i := 0; i < loopsz; i++ { bset.Add(rand.Int63()) checkbitcount(bset, "add(random(spread))", t) } for i := 0; i < loopsz; i++ { bset.Add(rand.Int63n(loopsz * 2)) checkbitcount(bset, "add(random(focussed))", t) } for i := 0; i < loopsz; i++ { bset.Remove(rand.Int63()) checkbitcount(bset, "remove(random(spread))", t) } for i := 0; i < loopsz; i++ { bset.Remove(rand.Int63n(loopsz * 2)) checkbitcount(bset, "remove(random(focussed))", t) } for i := 0; i < loopsz; i++ { bset.Remove(i) checkbitcount(bset, "remove(sequence)", t) } }
func philosopher(id int, left chan<- bool, right chan<- bool) { eaten := 0; var gotleft, gotright bool; for { for !gotleft || !gotright { time.Sleep(1000 * (1 + rand.Int63n(5))); gotleft = left <- true; if gotleft { // fmt.Printf("p%d picked up left\n",id); } else { // fmt.Printf("p%d could not pick up left\n",id); continue; } gotright = right <- true; if gotright { // fmt.Printf("p%d picked up right\n",id); } else { // fmt.Printf("p%d could not pick up right, dropped left\n",id); left <- true; } } eaten++; fmt.Printf("p%d eating [%d]\n",id,eaten); time.Sleep(1000 * (5 + rand.Int63n(20))); gotleft = false; left <- true; //fmt.Printf("p%d put down left\n",id); right <- true; gotright = false; //fmt.Printf("p%d put down right\n",id); //fmt.Printf("p%d thinking\n",id); time.Sleep(1000 * (5 + rand.Int63n(20))); } }
func RandomAthlete() Athlete { var ( Btime = rand.Int63n(int64(opt.maxbtime) * 1e9) Stime = rand.Int63n(int64(opt.maxstime) * 1e9) Rtime = rand.Int63n(int64(opt.maxrtime) * 1e9) ) return Athlete{Btime, Stime, Rtime} }
func work(id int, comm_chan chan int) { secs := rand.Int63n(33) + 2 fmt.Printf("worker %d working for %d seconds...\n", id, secs) time.Sleep(secs * 1000000000) fmt.Printf("worker %d done.\n", id) comm_chan <- 1 }
func numberGenerator(multiplier int, outputChannel chan int) { for i := 0; ; i += multiplier { fmt.Println(">>> Generating...", i) time.Sleep(rand.Int63n(10) * 1e8) // simulate CPU burn outputChannel <- i // blocks on writes to outputChannel } }
func (r *run) update(p packet, ticks heap.Interface) (learned bool) { if p.msg.Cmd != nil && *p.msg.Cmd == msg_TICK { log.Printf("tick wasteful=%v", r.l.done) } if r.l.done { return false } m, tick := r.c.update(p) r.broadcast(m) if tick { r.bound *= 2 schedTrigger(ticks, r.seqn, rand.Int63n(r.bound)) } m = r.a.update(&p.msg) r.broadcast(m) m, v, ok := r.l.update(p) r.broadcast(m) if ok { log.Printf("learn seqn=%d", r.seqn) r.ops <- store.Op{r.seqn, string(v)} return true } return false }
func (r *run) update(p *packet, from int, ticks heap.Interface) { if p.msg.Cmd != nil && *p.msg.Cmd == msg_TICK { log.Printf("tick wasteful=%v", r.l.done) } m, tick := r.c.update(p, from) r.broadcast(m) if tick { r.ntick++ r.bound *= 2 t := rand.Int63n(r.bound) log.Printf("sched tick=%d seqn=%d t=%d", r.ntick, r.seqn, t) schedTrigger(ticks, r.seqn, time.Nanoseconds(), t) } m = r.a.update(&p.msg) r.broadcast(m) m, v, ok := r.l.update(p, from) r.broadcast(m) if ok { log.Printf("learn seqn=%d", r.seqn) r.ops <- store.Op{r.seqn, string(v)} } }
func Changer(ops chan<- int, id int, min int, max int) { for { Wait(10 + rand.Int63n(30)) op := min + rand.Intn(max-min) fmt.Printf("Client%d: %d\n", id, op) ops <- op } }
func requester(work chan Request) { c := make(chan int) for { time.Sleep(rand.Int63n(nWorker * 2e9)) work <- Request{op, c} <-c } }
func handle(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/" { serve404(w) return } c := appengine.NewContext(r) b := BankAccount{4e6} key := datastore.NewKey(c, "BankAccount", "", 1, nil) if _, err := datastore.Put(c, key, &b); err != nil { serveError(c, w, err) return } sc := make(chan string) donec := make(chan bool) const N = 10 for i := 0; i < N; i++ { go func(id string, amount int) { // Spread out the withdrawal requests. time.Sleep(rand.Int63n(50e6)) var nAttempts int err := datastore.RunInTransaction(c, func(c appengine.Context) error { nAttempts++ return withdraw(c, sc, id, amount, nAttempts) }, nil) if err != nil { sc <- fmt.Sprintf("%s: error: %v\n", id, err) } else { sc <- fmt.Sprintf("%s: success\n", id) } donec <- true }(fmt.Sprintf("#%04d", 1<<uint(i)), 1e6-1<<uint(i)) } w.Header().Set("Content-Type", "text/plain; charset=utf-8") for nDone := 0; nDone < N; { select { case s := <-sc: io.WriteString(w, s) case <-donec: nDone++ } } if err := datastore.Get(c, key, &b); err != nil { serveError(c, w, err) return } fmt.Fprintf(w, "\nFinal balance: $%d\nSuccessful withdrawals:\n", b.Balance) for i := 0; i < N; i++ { x := 1 << uint(i) if (b.Balance%1e6)&x != 0 { fmt.Fprintf(w, "#%04d\n", x) } } }
func (dc *Daycare) newChild(activity int) *Child { c := &Child{ daycare: dc, activity: activity, attention: 1*Hour/2 + rand.Int63n(2*Hour), } go c.play() return c }
func BenchmarkLcgOrbit(b *testing.B) { for i := 0; i < b.N; i++ { m, a, c := genLcg(mMax, gMax) p := rand.Int63n(m-1) + 1 //skip, cyc := LcgOrbit(p, m, a, c, 1000000) // log.Print("p ", p, " skip ", skip, " len(cyc) ", len(cyc), " cyc [:2] ", cyc[:2]) } }
func numberProcessor(inputChannel chan int, outputChannel chan int) { for { generatedNumber := <-inputChannel fmt.Println(" <<< Processing...", generatedNumber) time.Sleep(rand.Int63n(10) * 1e8) // simulate CPU burn if generatedNumber%2 == 0 { outputChannel <- generatedNumber } } }
func consume(c chan int, n int) { for { time.Sleep(rand.Int63n(100) * 1e6) if i, ok := <-c; ok { fmt.Printf("Consumer %v consumed %v\n", n, i) } else { done <- 1 return } } }
func TestKeyMappingInterface(t *testing.T) { const uintsz = (1 + ^uint(0)>>32&1) * 32 var key bitchunkkey var mask bitchunk for i := 0; i < 1000; i++ { num := rand.Int63n(1 << 8) key, mask = ibitlocation(uint8(num)) checkkmn(key, mask, num, t) num = rand.Int63n(1 << 16) key, mask = ibitlocation(uint16(num)) checkkmn(key, mask, num, t) num = rand.Int63n(1 << 32) key, mask = ibitlocation(uint32(num)) checkkmn(key, mask, num, t) num = rand.Int63n(1<<63 - 1) key, mask = ibitlocation(uint64(num)) checkkmn(key, mask, num, t) num = rand.Int63n(1<<8) - (1 << 7) key, mask = ibitlocation(int8(num)) checkkmn(key, mask, num, t) num = rand.Int63n(1<<16) - (1 << 15) key, mask = ibitlocation(int16(num)) checkkmn(key, mask, num, t) num = rand.Int63n(1<<32) - (1 << 31) key, mask = ibitlocation(int32(num)) checkkmn(key, mask, num, t) num = rand.Int63n(1<<63-1) - (1 << 62) key, mask = ibitlocation(int64(num)) checkkmn(key, mask, num, t) num = rand.Int63n(1 << uintsz) key, mask = ibitlocation(uint(num)) checkkmn(key, mask, num, t) num = rand.Int63n(1<<uintsz) - (1 << (uintsz - 1)) key, mask = ibitlocation(int(num)) checkkmn(key, mask, num, t) } }
func (m *FooModel) ResetRows() { // Create some random data. m.items = make([]*Foo, rand.Intn(50000)) now := time.Seconds() for i := range m.items { m.items[i] = &Foo{ Bar: strings.Repeat("*", rand.Intn(5)+1), Baz: rand.Float64() * 1000, Quux: rand.Int63n(now), } } // Notify TableView and other interested parties about the reset. m.rowsResetPublisher.Publish() }
func withdraw(c appengine.Context, sc chan string, id string, amount, nAttempts int) error { b := BankAccount{} key := datastore.NewKey(c, "BankAccount", "", 1, nil) if err := datastore.Get(c, key, &b); err != nil { return err } sc <- fmt.Sprintf("%s: balance is $%07d (attempt number %d)\n", id, b.Balance, nAttempts) time.Sleep(5e6 + rand.Int63n(15e6)) b.Balance -= amount if b.Balance < 0 { return errors.New("insufficient funds") } if _, err := datastore.Put(c, key, &b); err != nil { return err } return nil }
func (it instance) process(seqn uint64, cf clusterer, res chan<- store.Op) { var sched bool var waitBound int64 = initialBound cx := cf.cluster(seqn) co := coordinator{cx: cx, crnd: uint64(cx.SelfIndex()), outs: cx} ac := acceptor{outs: cx} ln := *newLearner(uint64(cx.Quorum())) var sk sink for p := range it { if p.Cmd() == tick { sched = false } p.SetFrom(cx.indexByAddr(p.Addr)) co.Put(p.Msg) ac.Put(p.Msg) ln.Put(p.Msg) sk.Put(p.Msg) if co.seen > co.crnd && !sched { sched = true waitBound *= 2 go func() { time.Sleep(rand.Int63n(waitBound)) it.PutFrom("", msgTick) }() } if sk.done { cx.Put(newLearn(sk.v)) res <- store.Op{seqn, sk.v} } if ln.done { cx.Put(newLearn(ln.v)) res <- store.Op{seqn, ln.v} } } }
// Test of the SSI monitor. func TestSsiMonitor(t *testing.T) { mon := Monitor() // Generate values. for i := 0; i < 500; i++ { n := rand.Intn(10) id := fmt.Sprintf("Work %d", n) mon.SetValue(id, rand.Int63n(2001)-1000) } // Print, process with error, and print again. mon.StaySetVariablesPrintAll() mon.StaySetVariablesDo(func(ssv *StaySetVariable) { if ssv.Count >= 25 { // Divide by zero. ssv.Count = ssv.Count / (ssv.Count - ssv.Count) } }) mon.StaySetVariablesPrintAll() }
func randomKey() string { r := rand.Int63n(1000000000) + 10000000000 return fmt.Sprintf("%x", r) }
func randSleep(max int64) { time.Sleep(rand.Int63n(max)) }
func (this *ROARAgent) GetAction() (act rlglue.Action) { index := uint64(rand.Int63n(int64(this.task.Obs.Ints.Count()))) act = rlglue.NewAction(this.task.Obs.Ints.Values(index), []float64{}, []byte{}) this.LastAct = act return }
func (pd *PieceData) SearchPiece(addr string, bitfield *bit_field.Bitfield) (rpiece int64, rblock int, err os.Error) { // Check if peer has some of the active pieces to finish them //log.Println("PieceData -> Searching for an already present piece") for k, piece := range pd.pieces { available := -1 for block, downloads := range piece.downloaderCount { if downloads == 0 { available = block break } } if available != -1 && bitfield.IsSet(k) { // Send request piece k, block available pd.Add(addr, k, available) rpiece, rblock = k, available return } } //log.Println("PieceData -> No suitable piece found in active set") // Check what piece we can request totalPieces := pd.bitfield.Len() bytes := bitfield.Bytes() start := rand.Int63n(totalPieces) // Search fordward //log.Println("PieceData -> Searching fordwards") for piece := pd.bitfield.FindNextPiece(start, bytes); piece != -1 && piece < totalPieces; piece = pd.bitfield.FindNextPiece(piece+1, bytes) { //log.Println("PieceData -> Piece found, see if it's already in active piece set:", piece) if _, ok := pd.pieces[piece]; !ok { // Add new piece to set pd.Add(addr, piece, 0) rpiece, rblock = piece, 0 return } } // Search backwards //log.Println("PieceData -> Searching backwards") for piece := pd.bitfield.FindNextPiece(0, bytes); piece != -1 && piece < start; piece = pd.bitfield.FindNextPiece(piece+1, bytes) { //log.Println("PieceData -> Piece found, see if it's already in active piece set:", piece) if _, ok := pd.pieces[piece]; !ok { // Add new piece to set pd.Add(addr, piece, 0) rpiece, rblock = piece, 0 return } } // If all pieces are taken, double up on an active piece // if only 20% of pieces remaining //log.Println("PieceData -> Trying to enter endgame mode") if float64(pd.bitfield.Count())/float64(pd.bitfield.Len()) < 0.80 { err = os.NewError("No available block found") return } //log.Println("PieceData -> Doubling up on an active piece") first := true min := 0 for k, piece := range pd.pieces { for block, downloads := range piece.downloaderCount { if bitfield.IsSet(k) && !pd.CheckRequested(addr, k, block) { if first && downloads != -1 { rpiece, rblock, min = k, block, downloads first = false } if downloads != -1 && downloads < min { rpiece, rblock, min = k, block, downloads } } } } if !first && min < MAX_PIECE_REQUESTS { pd.Add(addr, rpiece, rblock) return } err = os.NewError("No available block found") return }
// Simulation of some work: just sleep for a while and report how long. func op() int { n := rand.Int63n(1e9) time.Sleep(nWorker * n) return int(n) }