// Callback is invoked while holding the mutate() lock, allowing // the caller to do more atomic things. func (p *partitionstore) setWithCallback(newItem *item, oldItem *item, cb func()) (deltaItemBytes int64, err error) { cBytes := casBytes(newItem.cas) cItem := &gkvlite.Item{ Key: cBytes, Val: newItem.toValueBytes(), Priority: rand.Int31(), Transient: unsafe.Pointer(newItem), } var kItem *gkvlite.Item if newItem.key != nil && len(newItem.key) > 0 { kItem = &gkvlite.Item{ Key: newItem.key, Val: cBytes, Priority: rand.Int31(), Transient: unsafe.Pointer(newItem), } } deltaItemBytes = newItem.NumBytes() var oldItemCasBytes []byte if oldItem != nil { oldItemCasBytes = make([]byte, 8) casBytesFill(oldItem.cas, oldItemCasBytes) deltaItemBytes -= oldItem.NumBytes() } p.mutate(func(keys, changes *gkvlite.Collection) { if err = changes.SetItem(cItem); err != nil { return } dirtyForce := false if newItem.key != nil && len(newItem.key) > 0 { // TODO: What if we flush between the keys update and changes // update? That could result in an inconsistent db file? // Solution idea #1 is to have load-time fixup, that // incorporates changes into the key-index. if err = keys.SetItem(kItem); err != nil { return } } else { dirtyForce = true // An nil/empty key means this is a metadata change. } if oldItem != nil { // TODO: Need a "frozen" CAS point where we don't de-duplicate changes stream. changes.Delete(oldItemCasBytes) } p.parent.dirty(dirtyForce) if cb != nil { cb() } }) return deltaItemBytes, err }
func (fuzzer *Fuzzer) PushPromiseFuzzer() { fuzzer.CheckConnection() for fuzzer.Alive { payloadLength := int32(rand.Intn(10000)) payload := make([]byte, payloadLength) crand.Read(payload) promise := http2.PushPromiseParam{ StreamID: uint32(rand.Int31()), PromiseID: uint32(rand.Int31()), BlockFragment: payload, EndHeaders: rand.Int31()%2 == 0, PadLength: uint8(rand.Intn(256)), } fuzzer.Mu.Lock() fuzzer.Conn.WritePushPromiseFrame(promise) fuzzer.Mu.Unlock() time.Sleep(config.FuzzDelay) fuzzer.CheckConnection() } fmt.Println("Stopping PushPromiseFuzzer:", fuzzer.Conn.Err) }
func (stream *Stream) Run() { stream.emit(&trace.StreamStart{ ProcessID: trace.ID(rand.Int31()), MachineID: trace.ID(rand.Int31()), Time: stream.advanceTime(0), Freq: 1e9, // ticks per second }) for stream.Alive() { time.Sleep(stream.threadInterval) stream.advanceTime(rand.Int31n(100)) n := rand.Intn(stream.max.Threads) if n < len(stream.threads) { thread := stream.threads[n] thread.Stop() stream.threads = append(stream.threads[:n], stream.threads[n+1:]...) } else { thread := &Thread{} thread.stream = stream thread.id = stream.lastThreadID stream.lastThreadID++ stream.threads = append(stream.threads, thread) thread.Start() } } for _, thread := range stream.threads { thread.Stop() } }
func (kv *ShardKV) GetShard(req *GetShardReq, rsp *GetShardRsp) error { kv.mu.Lock() // Use a fake operation to synchorize the data fake := Op{Opr: OpGet, Key: "tmp", Pid: kv.genPid(int(rand.Int31()), int(rand.Int31()))} kv.sync(fake) op := Op{Opr: OpLeave, Data: make(map[string]Value)} rsp.Data = make(map[string]Value) rsp.ReqData = make(map[string]reqdata) for k, v := range kv.data { if req.Shard == key2shard(k) { DPrintf("Reshard: %s %#v gid:%d seq:%d\n", k, v, kv.gid, kv.cfg.Num) rsp.Data[k] = v op.Data[k] = v pid, val := kv.v.GetByKey(k) rsp.ReqData[pid] = reqdata{k, val} } } DPrintf("Shard:%#v seq:%d gid:%d\n", kv.cfg.Shards, kv.cfg.Num, kv.gid) kv.cfg.Shards[req.Shard] = req.Gid /* if len(op.Data) > 0 { op.Pid = kv.genPid(req.Num, req.Shard) kv.sync(op) } */ kv.mu.Unlock() return nil }
func expectAreSameDirectory(dir1, dir2 string) { // we can't just compare equality of strings, because one may be a symlink // this happens with temp dir on mac filename := fmt.Sprintf("%x", rand.Int31()) data := []byte(fmt.Sprintf("%x", rand.Int31())) Expect(ioutil.WriteFile(filepath.Join(dir1, filename), data, 0600)).To(Succeed()) actualData, err := ioutil.ReadFile(filepath.Join(dir2, filename)) Expect(err).NotTo(HaveOccurred()) Expect(actualData).To(Equal(data)) }
// There's no difference between this and int64 benchmarks. func BenchmarkInt32(b *testing.B) { rand.Seed(time.Now().UnixNano()) var m, n int32 m = rand.Int31() n = rand.Int31() b.ResetTimer() for i := 0; i < b.N; i++ { _ = m == n } }
func newIrcClient(conn net.Conn) *ircClient { c := &ircClient{ conn, textproto.NewWriter(bufio.NewWriter(conn)), make(chan []string, 1024), make(chan string, 1), make(chan []string, 6), } go func() { var line string var fields []string var err error r := textproto.NewReader(bufio.NewReader(conn)) for { if line, err = r.ReadLine(); err == nil { fields = strings.Fields(line)[1:] if len(fields) > 3 { switch fields[0] { case RPL_NAMREPLY: c.namesReplies <- fields[2:] case RPL_WHOISUSER, RPL_WHOISSERVER, RPL_WHOISOPERATOR, RPL_WHOISIDLE, RPL_ENDOFWHOIS, RPL_WHOISCHANNELS: c.whoisReplies <- fields case RPL_ENDOFNAMES: default: if Verbose { fmt.Fprintln(os.Stderr, "\t ", line) } } } else if len(fields) >= 2 && fields[0] == "PING" { c.w.PrintfLine("PONG %s", fields[1]) } else { if Verbose { fmt.Fprintf(os.Stderr, "got some sort of short unhandled msg %q\n", line) } } } else { fmt.Fprintln(os.Stderr, err) conn.Close() break } } }() c.w.PrintfLine("NICK fc%x", rand.Int31()) c.w.PrintfLine("USER %x 8 * :%x", rand.Int31(), rand.Int31()) return c }
func TestBlockAPI(t *testing.T) { datastore.OpenTest() defer datastore.CloseTest() uuid, _ := initTestRepo() grayscale := makeGrayscale(uuid, t, "grayscale") // construct random blocks of data. numBlockBytes := int32(grayscale.BlockSize().Prod()) testBlocks := 1001 var blockData []byte for i := 0; i < testBlocks; i++ { blockData = append(blockData, dvid.RandomBytes(numBlockBytes)...) } // set start of span x := rand.Int31() y := rand.Int31() z := rand.Int31() // Test uncompressed roundtrip // send the blocks blockReq := fmt.Sprintf("%snode/%s/grayscale/blocks/%d_%d_%d/%d", server.WebAPIPath, uuid, x, y, z, testBlocks) server.TestHTTP(t, "POST", blockReq, bytes.NewBuffer(blockData)) // read same span of blocks returnedData := server.TestHTTP(t, "GET", blockReq, nil) // make sure blocks are same totBytes := testBlocks * int(numBlockBytes) if len(returnedData) != totBytes { t.Errorf("Returned %d bytes, expected %d bytes", len(returnedData), totBytes) } if !reflect.DeepEqual(returnedData, blockData) { t.Errorf("Returned block data != original block data\n") } // We should get blank blocks at different z z += 1 blockReq = fmt.Sprintf("%snode/%s/grayscale/blocks/%d_%d_%d/%d", server.WebAPIPath, uuid, x, y, z, testBlocks) returnedData = server.TestHTTP(t, "GET", blockReq, nil) if len(returnedData) != totBytes { t.Errorf("Returned %d bytes, expected %d bytes", len(returnedData), totBytes) } for i, b := range returnedData { if b != 0 { t.Fatalf("Expected 0 at returned byte %d, got %d instead.\n", i, b) } } }
func BLookup(n int) string { var res bytes.Buffer for i := 0; i < n; i++ { res.WriteByte(chars[rand.Int31()&63]) } return res.String() }
func clientGo(id int) { defer wg.Done() conn, err := net.DialTimeout(SERVER_NETWORK, SERVER_ADDRESS, 2*time.Second) if err != nil { printLog("Dial Error: %s (Client[%d])\n", err, id) return } defer conn.Close() printLog("Connected to server. (remote address: %s, local address: %s) (Client[%d])\n", conn.RemoteAddr(), conn.LocalAddr(), id) time.Sleep(200 * time.Millisecond) requestNumber := 5 conn.SetDeadline(time.Now().Add(5 * time.Millisecond)) for i := 0; i < requestNumber; i++ { i32Req := rand.Int31() n, err := write(conn, fmt.Sprintf("%d", i32Req)) if err != nil { printLog("Write Error: %s (Client[%d])\n", err, id) continue } printLog("Sent request (written %d bytes): %d (Client[%d])\n", n, i32Req, id) } for j := 0; j < requestNumber; j++ { strResp, err := read(conn) if err != nil { if err == io.EOF { printLog("The connection is closed by another side. (Client[%d])\n", id) } else { printLog("Read Error: %s (Client[%d])\n", err, id) } break } printLog("Received response: %s (Client[%d])\n", strResp, id) } }
func TestDecodeEncode(t *testing.T) { for i := 0; i < 1000; i++ { c := rand.Int31() d := encode(decode(c)) if d != c { t.Errorf("DecodeEncode(%v) == %v, want %v", i, d, c) } } for i := 0; i < 1000; i++ { c := -rand.Int31() d := encode(decode(c)) if d != c { t.Errorf("DecodeEncode(%v) == %v, want %v", i, d, c) } } }
func main() { if len(os.Args) != 2 { fmt.Fprintf(os.Stderr, "usage: %s <elem_count>\n", os.Args[0]) os.Exit(-1) } count, err := strconv.Atoi(os.Args[1]) if err != nil { panic(err) } file, err := os.Create("vec_gen.out") if err != nil { panic(err) } defer file.Close() bw := bufio.NewWriter(file) defer func() { err := bw.Flush() if err != nil { log.Fatal(err) } }() for i := 0; i < count; i++ { r := rand.Int31() fmt.Fprintf(bw, "%d\n", r) } }
func (self *Server) randomId() string { buf := make([]byte, idLength) for index, _ := range buf { buf[index] = byte(rand.Int31()) } return (base64.URLEncoding.EncodeToString(buf)) }
func writeCheckedFile(r io.ReadCloser, fileName string, checker fileChecker) error { tmpFile := fileName + ".tmp-" + strconv.FormatInt(int64(rand.Int31()), 16) f, err := os.Create(tmpFile) if err != nil { return err } defer r.Close() defer os.Remove(tmpFile) // make sure temp file always gets removed _, err = io.Copy(f, r) f.Close() if err != nil { return err } f, err = os.Open(tmpFile) if err != nil { return err } defer f.Close() if err := checker(f); err != nil { return err } if err := os.Rename(tmpFile, fileName); err != nil { return err } return nil }
// GenerateAndSaveKey generates a new SSH key pair and saves it to local. func (s *SSHKey) GenerateAndSaveKey() ([]byte, error) { var perms os.FileMode = 0600 if err := os.MkdirAll(filepath.Dir(s.PrivateKeyPath()), 0700); err != nil { return nil, err } publicKey, privateKey, err := sshkey.Generate() if err != nil { return nil, err } publicKey += fmt.Sprintf(" koding-%d", rand.Int31()) // save ssh private key err = ioutil.WriteFile(s.PrivateKeyPath(), []byte(privateKey), perms) if err != nil { return nil, err } // save ssh public key err = ioutil.WriteFile(s.PublicKeyPath(), []byte(publicKey), perms) if err != nil { return nil, err } return []byte(publicKey), nil }
func runClient() { if *server == "" { log.Printf("Please specify a -server id") flag.Usage() return } log.Printf("Starting client, connecting to server %s ...", *server) traversalId := uint32(rand.Int31()) log.Printf("Starting traversal: %d", traversalId) serverId, err := waddell.PeerIdFromString(*server) if err != nil { log.Fatalf("Unable to parse PeerID for server %s: %s", *server, err) } t := natty.Offer(TIMEOUT) defer t.Close() go sendMessages(t, serverId, traversalId) go receiveMessages(t, traversalId) ft, err := t.FiveTuple() if err != nil { t.Close() log.Fatalf("Unable to offer: %s", err) } log.Printf("Got five tuple: %s", ft) if <-serverReady { writeUDP(ft) } }
// 查询目录属性 // bucket: Bucket 名称 // path: 目录路径 // // 示例: // // client := cos.NewClient(appId, secretId, secretKey) // // res, err := client.StatFolder("cosdemo", "/hello") // if err != nil { // fmt.Println(err) // return // } // // fmt.Println("Code:", res.Code, // "\nMessage:", res.Message, // "\nName:", res.Data.Name, // "\nBizAttr:", res.Data.BizAttr, // "\nCtime:", res.Data.Ctime, // "\nMtime:", res.Data.Mtime) // func (c *Client) StatFolder(bucket, path string) (*StatFolderResponse, error) { var cosRequest StatFolderRequest var cosResponse StatFolderResponse encodedPath := utils.UrlEncode(c.validateFolderPath(path)) resource := c.generateResourceUrl(bucket, encodedPath) now := time.Now().Unix() strNow := fmt.Sprintf("%d", now) strExpires := fmt.Sprintf("%d", now+EXPIRES) strRand := fmt.Sprintf("%d", rand.Int31()) signer := auth.NewSignature(c.AppId, bucket, c.SecretId, strExpires, strNow, strRand, "") sign := signer.Sign(c.SecretKey) cosRequest.Op = "stat" httpRequest := http.Request{ Method: "GET", Uri: resource, Timeout: c.Timeout, QueryString: cosRequest.Request, } httpRequest.AddHeader("Authorization", sign) httpResponse, err := httpRequest.Do() if err != nil { return nil, err } err = httpResponse.Body.Unmarshal(&cosResponse) if err != nil { return nil, err } return &cosResponse, nil }
func genInt32Array(n int, min, max int32) []int32 { A := make([]int32, n) for i := 0; i < n; i++ { A[i] = gomath.ScaleInt32(min, max, 0, 1, rand.Int31()) } return A }
func testReadBlockBoundary(t *testing.T, android bool) { root, cleanup := startFs(t, android) defer cleanup() name := filepath.Join(root, fmt.Sprintf("mtpfs-test-%x", rand.Int31())) page := 4096 buf := bytes.Repeat([]byte("a"), 32*page) if err := ioutil.WriteFile(name, buf, 0644); err != nil { t.Fatalf("WriteFile: %v", err) } f, err := os.Open(name) if err != nil { t.Fatalf("Open: %v", name) } total := 0 for { b := make([]byte, page) n, err := f.Read(b) total += n if n == 0 && err == io.EOF { break } if n != 4096 || err != nil { t.Fatalf("Read: %v (%d bytes)", err, n) } } f.Close() }
func main() { ch := make(chan int32) go func() { for { time.Sleep(time.Duration((rand.Int31()%7)*100) * time.Millisecond) x := rand.Int31() ch <- x } }() for { fmt.Println(<-ch) } }
func Benchmark_Pack_________Int32(b *testing.B) { val := rand.Int31() b.N = 1000 runtime.GC() b.ResetTimer() doPack(val, b) }
func Lookup(n int) string { res := make([]uint8, n) for i := 0; i < n; i++ { res[i] = chars[rand.Int31()&63] } return string(res) }
func GenerateDomain(r *rand.Rand, size int) []byte { dnLen := size % 70 // artificially limit size so there's less to intrepret if a failure occurs var dn []byte done := false for i := 0; i < dnLen && !done; { max := dnLen - i if max > 63 { max = 63 } lLen := max if lLen != 0 { lLen = int(r.Int31()) % max } done = lLen == 0 if done { continue } l := make([]byte, lLen+1) l[0] = byte(lLen) for j := 0; j < lLen; j++ { l[j+1] = byte(rand.Int31()) } dn = append(dn, l...) i += 1 + lLen } return append(dn, 0) }
// placeVotes votes for votingDuration seconds. func placeVotes(join chan int) { volt, err := voltdb.NewConnection("username", "", "localhost:21212") defer volt.Close() if err != nil { log.Fatalf("Connection error db. %v\n", err) } timeout := time.After(votingDuration) placedVotes := 0 for { select { case <-timeout: join <- placedVotes return default: // construct a phoneNumber with a valid area code. var phoneNumber int64 = (5080000000 + int64(rand.Int31())) // pick a contestant at random (contestant ids are 1-based) var contestant = (rand.Int() % ttlContestants) + 1 rsp, err := volt.Call("Vote", phoneNumber, contestant, 100) if err != nil { log.Fatalf("Error voting. %v\n", err) } if rsp.Status() == voltdb.SUCCESS { placedVotes++ } else { fmt.Printf("Vote failed %#v\n", rsp) } } } }
// RPC is used to forward an RPC call to a consul server, or fail if no servers func (c *Client) RPC(method string, args interface{}, reply interface{}) error { // Check the last rpc time var server *serverParts if time.Now().Sub(c.lastRPCTime) < clientRPCCache { server = c.lastServer if server != nil { goto TRY_RPC } } // Bail if we can't find any servers c.consulLock.RLock() if len(c.consuls) == 0 { c.consulLock.RUnlock() return structs.ErrNoServers } // Select a random addr server = c.consuls[rand.Int31()%int32(len(c.consuls))] c.consulLock.RUnlock() // Forward to remote Consul TRY_RPC: if err := c.connPool.RPC(c.config.Datacenter, server.Addr, server.Version, method, args, reply); err != nil { c.lastServer = nil c.lastRPCTime = time.Time{} return err } // Cache the last server c.lastServer = server c.lastRPCTime = time.Now() return nil }
//export goNewTunnel // goNewTunnel is called from listener_accept_func. It creates a tunnel and // assigns an unique ID to it. func goNewTunnel(client *C.struct_tcp_client) C.uint32_t { var i uint32 log.Printf("goNewTunnel (lookup)") t, err := NewTunnel(client, Dialer) if err != nil { log.Printf("Could not start tunnel: %q", err) return 0 } // Looking for an unused ID to identify this tunnel. tunnelMu.Lock() defer tunnelMu.Unlock() for { i = uint32(rand.Int31()) if _, ok := tunnels[i]; !ok { tunnels[i] = t t.SetStatus(StatusReady) return C.uint32_t(i) } } panic("reached.") }
func TestSortableNodes(t *testing.T) { ns := []*client.Node{ 0: {CreatedIndex: 5}, 1: {CreatedIndex: 1}, 2: {CreatedIndex: 3}, 3: {CreatedIndex: 4}, } // add some randomness for i := 0; i < 10000; i++ { ns = append(ns, &client.Node{CreatedIndex: uint64(rand.Int31())}) } sns := sortableNodes{ns} sort.Sort(sns) cis := make([]int, 0) for _, n := range sns.Nodes { cis = append(cis, int(n.CreatedIndex)) } if sort.IntsAreSorted(cis) != true { t.Errorf("isSorted = %v, want %v", sort.IntsAreSorted(cis), true) } cis = make([]int, 0) for _, n := range ns { cis = append(cis, int(n.CreatedIndex)) } if sort.IntsAreSorted(cis) != true { t.Errorf("isSorted = %v, want %v", sort.IntsAreSorted(cis), true) } }
// Rand returns a random address from the addresslist. func (adl AddressList) Rand() *Address { if adl == nil || len(adl) == 0 { return nil } rand.Seed(times.NowNano()) return &adl[int(rand.Int31())%len(adl)] }
func randomPrimitiveObject() *primitive { p := &primitive{} p.BooleanField = rand.Int()%2 == 0 p.IntField = rand.Int31() if p.IntField%3 == 0 { p.IntField = -p.IntField } p.LongField = rand.Int63() if p.LongField%3 == 0 { p.LongField = -p.LongField } p.FloatField = rand.Float32() if p.BooleanField { p.FloatField = -p.FloatField } p.DoubleField = rand.Float64() if !p.BooleanField { p.DoubleField = -p.DoubleField } p.BytesField = randomBytes(rand.Intn(99) + 1) p.StringField = randomString(rand.Intn(99) + 1) return p }
func (t *Template) Process(device int, job Job) ([]byte, error) { type TemplateData struct { Input, Output string Seed, DeviceID int } data := TemplateData{Seed: int(rand.Int31())} data.DeviceID = device data.Output = fmt.Sprintf("sim.%d.dcd", data.Seed) for _, file := range job.Model.Files { parts := strings.Split(strings.ToLower(file), ".") if parts[len(parts)-1] == "tpr" { data.Input = strings.ToLower(fmt.Sprintf("gromacstprfile ../../../model/%s/%s", job.Model.Name, file)) break } if parts[len(parts)-1] == "pdb" { data.Input = strings.ToLower(fmt.Sprintf("../../../model/%s/%s", job.Model.Name, file)) break } } temp, err := template.New(strings.Split(job.Template.File, "/")[1]).ParseFiles(job.Template.File) if err != nil { return nil, err } var templateData bytes.Buffer if err := temp.Execute(&templateData, data); err != nil { return nil, err } return templateData.Bytes(), nil }