func TestBasic(t *testing.T) {
	smh, gids, ha, _, clean := setup("basic", false)
	defer clean()

	fmt.Printf("Test: Basic Join/Leave ...\n")

	mck := shardmaster.MakeClerk(smh)
	mck.Join(gids[0], ha[0])

	ck := MakeClerk(smh)

	ck.Put("a", "x")
	v := ck.PutHash("a", "b")
	if v != "x" {
		t.Fatalf("Puthash got wrong value")
	}
	ov := NextValue("x", "b")
	if ck.Get("a") != ov {
		t.Fatalf("Get got wrong value")
	}

	keys := make([]string, 10)
	vals := make([]string, len(keys))
	for i := 0; i < len(keys); i++ {
		keys[i] = strconv.Itoa(rand.Int())
		vals[i] = strconv.Itoa(rand.Int())
		ck.Put(keys[i], vals[i])
	}
	// are keys still there after joins?
	for g := 1; g < len(gids); g++ {
		mck.Join(gids[g], ha[g])
		time.Sleep(1 * time.Second)
		for i := 0; i < len(keys); i++ {
			v := ck.Get(keys[i])
			if v != vals[i] {
				t.Fatalf("joining; wrong value; g=%v k=%v wanted=%v got=%v",
					g, keys[i], vals[i], v)
			}
			vals[i] = strconv.Itoa(rand.Int())
			ck.Put(keys[i], vals[i])
		}
	}

	// are keys still there after leaves?
	for g := 0; g < len(gids)-1; g++ {
		mck.Leave(gids[g])
		time.Sleep(1 * time.Second)
		for i := 0; i < len(keys); i++ {
			v := ck.Get(keys[i])
			if v != vals[i] {
				t.Fatalf("leaving; wrong value; g=%v k=%v wanted=%v got=%v",
					g, keys[i], vals[i], v)
			}
			vals[i] = strconv.Itoa(rand.Int())
			ck.Put(keys[i], vals[i])
		}
	}

	fmt.Printf("  ... Passed\n")
}
Beispiel #2
0
func newResult(q quiz) result {
	r := result{
		Level:    q.Level,
		End:      q.Start.Add(q.Duration),
		Duration: q.Duration,
		Word:     q.Word,
		Tries:    q.Tries,
	}
	t := r.End.Unix()
	r.ID = []byte{
		byte(t >> 56),
		byte(t >> 48),
		byte(t >> 40),
		byte(t >> 32),
		byte(t >> 24),
		byte(t >> 16),
		byte(t >> 8),
		byte(t),
		byte(rand.Int()),
		byte(rand.Int()),
		byte(rand.Int()),
		byte(rand.Int()),
	}

	return r
}
Beispiel #3
0
func TestHDel(t *testing.T) {
	ss := []string{}
	for i := 0; i < 32; i++ {
		k := strconv.Itoa(i)
		v := strconv.Itoa(rand.Int())
		ss = append(ss, k, v)
	}
	hmset(t, 0, "hash", ss...)
	hgetall(t, 0, "hash", ss...)

	hdel(t, 0, "hash", 2, "0", "1")
	hdel(t, 0, "hash", 1, "2", "2", "2")
	hdel(t, 0, "hash", 0, "0", "1", "2", "0", "1", "2")

	hlen(t, 0, "hash", int64(len(ss)/2)-3)
	hgetall(t, 0, "hash", ss[6:]...)
	kpexpire(t, 0, "hash", 10, 1)
	sleepms(20)
	hdelall(t, 0, "hash", 0)

	for i := 0; i < 10; i++ {
		hset(t, 0, "hash", strconv.Itoa(i), strconv.Itoa(rand.Int()), 1)
	}
	for i := 0; i < 10; i++ {
		hdel(t, 0, "hash", 1, strconv.Itoa(i))
		hdel(t, 0, "hash", 0, strconv.Itoa(i))
	}
	hgetall(t, 0, "hash")
	checkempty(t)
}
Beispiel #4
0
func TestSearchBig(t *testing.T) {

	if testing.Short() {
		t.Skip("Skipping big test search")
	}

	rand.Seed(0)

	const maxLimit = 100e6

	ints := make([]int, maxLimit)

	for i := 0; i < maxLimit; i++ {
		ints[i] = rand.Int()
	}

	sort.Ints(ints)

	for i := 0; i < 100000000; i++ {
		elt := rand.Int()
		vidx := Search(ints, elt)
		idx := sort.SearchInts(ints, elt)
		if vidx != idx {
			t.Fatalf("Search failed for elt=%d: got %d want %d\n", elt, vidx, idx)
		}
	}
}
Beispiel #5
0
func benchZRevRangeByScore() {
	f := func() {
		waitBench("zrevrangebyscore", "myzsetkey", 0, rand.Int(), "withscores", "limit", rand.Int()%100, 100)
	}

	bench("zrevrangebyscore", f)
}
Beispiel #6
0
func (c *Client) Do(req *http.Request) (*http.Response, error) {
	if strings.HasPrefix(c.Key, "jwt:") {
		req.Header.Add("Authorization", strings.Split(c.Key, ":")[1])
	}
	req.Header.Set("User-Agent", c.UserAgent)

	var res *http.Response
	var err error

	retryPatterns := append(c.RetryPatterns, time.Millisecond)

	for _, sleepTime := range retryPatterns {
		res, err = c.HTTPClient.Do(req)
		if err != nil {
			if strings.Contains(err.Error(), "TLS handshake timeout") {
				time.Sleep(sleepTime + time.Duration(rand.Int()%1000)*time.Millisecond)
				continue
			}
			return nil, err
		}

		if res.StatusCode == 503 {
			// Rate limited, try again according to patterns.
			// following https://cloud.google.com/storage/docs/json_api/v1/how-tos/upload#exp-backoff to the letter
			res.Body.Close()
			time.Sleep(sleepTime + time.Duration(rand.Int()%1000)*time.Millisecond)
			continue
		}

		break
	}

	return res, err
}
Beispiel #7
0
func BenchmarkReadPid(b *testing.B) {
	b.StopTimer()
	c := new(Context)

	rand.Seed(time.Now().UnixNano())
	max := 64
	length := 16
	pids := make([]*bytes.Buffer, max)

	for i := 0; i < max; i++ {
		w := new(bytes.Buffer)
		s := bytes.Repeat([]byte{'a'}, length)
		b := bytes.Map(randRune, s)
		b[6] = '@'
		w.Write([]byte{ettPid, ettSmallAtom, byte(length)})
		w.Write(b)
		w.Write([]byte{0, 0, 0, uint8(rand.Int())})
		w.Write([]byte{0, 0, 0, uint8(rand.Int())})
		w.Write([]byte{uint8(rand.Int())})
		pids[i] = w
	}

	b.StartTimer()

	for i := 0; i < b.N; i++ {
		in := pids[i%max]
		_, err := c.Read(in)

		if err != io.EOF && err != nil {
			b.Fatal(err)
		}
	}
}
Beispiel #8
0
// TestSetwinsz Tests settig the terminal windowsize
func TestSetwinsz(t *testing.T) {
	nf, err := donormfile("TestSetwinsz")
	if err != nil {
		t.Fatal("TestSetwinsz Could not create testfile, err: ", err)
	}
	defer nf.Close()
	wz = &tios.Wz
	var i, y uint16
	for i = 0; i < NUMTEST; i++ {
		for y = 0; y < NUMTEST; y++ {
			wz.WsRow = i
			wz.WsCol = y
			wz.WsXpixel = uint16(rand.Int())
			wz.WsYpixel = uint16(rand.Int())
			xp, yp := wz.WsXpixel, wz.WsYpixel
			if err = tios.Setwinsz(pty.Slave); err != nil {
				t.Errorf("Setwinsz could not set row: %d col: %d err: %v", i, y, err)
				t.Errorf("Setwinsz could not set x: %d y: %d err: %v", xp, yp, err)
			}
			if err = tios.Winsz(pty.Slave); err != nil {
				t.Error("Winsz failed: ", err)
			}
			if !(wz.WsRow == i && wz.WsCol == y && wz.WsXpixel == xp && wz.WsYpixel == yp) {
				t.Errorf("Setwinsz got row: %d col: %d want row: %d col: %d", i, y, wz.WsRow, wz.WsCol)
				t.Errorf("Setwinsz got x: %d y: %d want x: %d y: %d", xp, yp, wz.WsXpixel, wz.WsYpixel)
			}
		}
	}
	if err = tios.Setwinsz(nf); err == nil {
		t.Error("Setwinsz should not work for std. file")
	}
}
Beispiel #9
0
func TestChecksum(t *testing.T) {
	// Test even-size checksum
	buf := make([]byte, 2+40)
	for i := 2; i < len(buf); i++ {
		buf[i] = byte(rand.Int())
	}
	csumUint16ToBytes(
		csumDone(csumSum(buf)),
		buf[0:2],
	)
	if csumDone(csumSum(buf)) != 0 {
		t.Errorf("csum")
	}

	// Test odd-size checksum
	buf = make([]byte, 41+2)
	for i := 2; i < len(buf); i++ {
		buf[i] = byte(rand.Int())
	}
	csumUint16ToBytes(
		csumDone(csumSum(buf)),
		buf[0:2],
	)
	if csumDone(csumSum(buf)) != 0 {
		t.Errorf("csum")
	}

}
Beispiel #10
0
func (i *chunkRecord) Create(file string) (count int64, err error) {
	tmpFilePath := fmt.Sprintf("%s/temp/%d%d.idx", conf.Conf["data-path"], rand.Int(), rand.Int())

	f, err := os.Create(tmpFilePath)
	if err != nil {
		return
	}
	defer f.Close()

	curr := int64(0)
	count = 0
	for {
		n, er := i.r.SeekChunk(curr)
		if er != nil {
			if er != io.EOF {
				err = er
				return
			}
			binary.Write(f, binary.LittleEndian, curr)
			binary.Write(f, binary.LittleEndian, i.size-curr)
			count += 1
			break
		} else {
			binary.Write(f, binary.LittleEndian, curr)
			binary.Write(f, binary.LittleEndian, n)
			curr += int64(n)
			count += 1
		}
	}
	err = os.Rename(tmpFilePath, file)

	return
}
Beispiel #11
0
func mixedArray(size int) []int32 {
	var list = make([]int32, size)

	const bits_of_int = uint(unsafe.Sizeof(list[0])) * 8
	var tmp = uint(size)
	var cnt uint = 0
	for cnt < bits_of_int && tmp != 0 {
		cnt++
		tmp >>= 1
	}
	cnt = bits_of_int - cnt - 11
	var mask = ^((^0) << cnt)

	var num = int32(0)
	rand.Seed(time.Now().Unix())
	for i := 0; i < size; i++ {
		if i%32 == 0 { //局部摻入有序数列
			num += int32(rand.Int() & mask)
			list[i] = num
		} else {
			list[i] = int32(rand.Int())
		}
	}
	return list
}
Beispiel #12
0
func testInt(t *testing.T, n int) {
	values := make([]int, n)
	for i := range values {
		if i%2 == 0 {
			values[i] = rand.Int()
		} else {
			values[i] = -rand.Int()
		}
	}

	var buf bytes.Buffer
	w := bit.NewWriter(&buf)
	for _, v := range values {
		WriteInt(w, v)
	}

	err := w.Close()
	if err != nil {
		t.Errorf("w.Close: %v", err)
		return
	}

	r := bit.NewReader(&buf)
	for i, exp := range values {
		got, err := ReadInt(r), r.Error()
		if err != nil {
			t.Errorf("ReadInt: %v", err)
			return
		}
		if got != exp {
			t.Errorf("%v: %d got %v expected %v", values, i, got, exp)
			return
		}
	}
}
Beispiel #13
0
func doit(name string) bool {
	if os.Getenv("GOSSAHASH") == "" {
		// Default behavior is yes.
		return true
	}
	// Check the hash of the name against a partial input hash.
	// We use this feature to do a binary search within a
	// package to find a function that is incorrectly compiled.
	hstr := ""
	for _, b := range sha1.Sum([]byte(name)) {
		hstr += fmt.Sprintf("%08b", b)
	}
	if strings.HasSuffix(hstr, os.Getenv("GOSSAHASH")) {
		for i := 7 & rand.Int(); i >= 0; i-- {
			fmt.Printf("GOSSAHASH triggered %s\n", name)
		}
		return true
	}
	// Iteratively try additional hashes to allow tests for
	// multi-point failure.
	for i := 0; true; i++ {
		ev := fmt.Sprintf("GOSSAHASH%d", i)
		evv := os.Getenv(ev)
		if evv == "" {
			break
		}
		if strings.HasSuffix(hstr, evv) {
			for i := 7 & rand.Int(); i >= 0; i-- {
				fmt.Printf("%s triggered %s\n", ev, name)
			}
			return true
		}
	}
	return false
}
Beispiel #14
0
func TestSlotNum(t *testing.T) {
	tests := [][]string{
		[]string{"", ""},
		[]string{"{", "{"},
		[]string{"{test", "{test"},
		[]string{"{test{0}", "test{0"},
		[]string{"test{a}", "a"},
		[]string{"{b}test", "b"},
		[]string{"}test{c}", "c"},
		[]string{"}test", "}test"},
		[]string{"}test1{test2{d}}{e}", "test2{d"},
	}
	for _, p := range tests {
		key, tag := []byte(p[0]), []byte(p[1])
		checkerror(t, nil, bytes.Equal(HashTag(key), tag))
	}
	const n = MaxSlotNum * 32
	for i := 0; i < n; i++ {
		key := []byte(fmt.Sprintf("key_%d_%d", rand.Int(), rand.Int()))
		checkerror(t, nil, bytes.Equal(HashTag(key), key))
	}
	for i := 0; i < n; i++ {
		v := rand.Int()
		tag := []byte(fmt.Sprintf("%d", v))
		key := []byte(fmt.Sprintf("key_{%d}_%d", v, rand.Int()))
		checkerror(t, nil, bytes.Equal(HashTag(key), tag))
	}
}
Beispiel #15
0
// helper function to create a node from an http data post
func DataUpload(r *http.Request) (params map[string]string, files node.FormFiles, err error) {
	params = make(map[string]string)
	files = make(node.FormFiles)
	tmpPath := fmt.Sprintf("%s/temp/%d%d", conf.Conf["data-path"], rand.Int(), rand.Int())

	files["upload"] = node.FormFile{Name: "filename", Path: tmpPath, Checksum: make(map[string]string)}
	if tmpFile, err := os.Create(tmpPath); err == nil {
		defer tmpFile.Close()
		md5c := make(chan checkSumCom)
		writeChecksum(md5.New, md5c)
		for {
			buffer := make([]byte, 32*1024)
			n, err := r.Body.Read(buffer)
			if n == 0 || err != nil {
				md5c <- checkSumCom{n: 0}
				break
			}
			md5c <- checkSumCom{buf: buffer[0:n], n: n}
			tmpFile.Write(buffer[0:n])
		}
		md5r := <-md5c
		files["upload"].Checksum["md5"] = md5r.checksum
	} else {
		return nil, nil, err
	}

	return
}
Beispiel #16
0
func (s *testStoreSuite) TestSlotNum(c *C) {
	tests := [][]string{
		[]string{"", ""},
		[]string{"{", "{"},
		[]string{"{test", "{test"},
		[]string{"{test{0}", "test{0"},
		[]string{"test{a}", "a"},
		[]string{"{b}test", "b"},
		[]string{"}test{c}", "c"},
		[]string{"}test", "}test"},
		[]string{"}test1{test2{d}}{e}", "test2{d"},
	}
	for _, p := range tests {
		key, tag := []byte(p[0]), []byte(p[1])
		c.Assert(bytes.Equal(HashTag(key), tag), Equals, true)
	}

	const n = MaxSlotNum * 32
	for i := 0; i < n; i++ {
		key := []byte(fmt.Sprintf("key_%d_%d", rand.Int(), rand.Int()))
		c.Assert(bytes.Equal(HashTag(key), key), Equals, true)
	}

	for i := 0; i < n; i++ {
		v := rand.Int()
		tag := []byte(fmt.Sprintf("%d", v))
		key := []byte(fmt.Sprintf("key_{%d}_%d", v, rand.Int()))
		c.Assert(bytes.Equal(HashTag(key), tag), Equals, true)
	}
}
Beispiel #17
0
func main() {
	fmt.Println("The fill factor test:")
	size := 100
	factor := 10n 

	for ; factor <= size; factor = factor + 10 {
		ch := ClosedHash.NewHashTable(size)
		oh := OpenHash.NewHashTable(size)
		ofh := OverflowHash.NewHashTable(size)
		rand.Seed(time.Now().Unix())
		for i := 0; i < factor; i++ {
			k := rand.Int() / 100
			d := rand.Int()
			ce := ClosedHash.NewElem(k, d)
			oe := OpenHash.NewElem(k, d)
			ofe := OverflowHash.NewElem(k, d)
			ch.Insert(ce)
			oh.Insert(oe)
			ofh.Insert(ofe)
		}
		ft := time.Now()
		for i := 0; i < 10000; i++{
			ch.Find(rand.Int()/100)
		}
	}
}
Beispiel #18
0
func (s *testStoreSuite) TestHDel(c *C) {
	ss := []string{}
	for i := 0; i < 32; i++ {
		k := strconv.Itoa(i)
		v := strconv.Itoa(rand.Int())
		ss = append(ss, k, v)
	}
	s.hmset(c, 0, "hash", ss...)
	s.hgetall(c, 0, "hash", ss...)

	s.hdel(c, 0, "hash", 2, "0", "1")
	s.hdel(c, 0, "hash", 1, "2", "2", "2")
	s.hdel(c, 0, "hash", 0, "0", "1", "2", "0", "1", "2")

	s.hlen(c, 0, "hash", int64(len(ss)/2)-3)
	s.hgetall(c, 0, "hash", ss[6:]...)
	s.kpexpire(c, 0, "hash", 100, 1)
	sleepms(200)
	s.hdelall(c, 0, "hash", 0)

	for i := 0; i < 10; i++ {
		s.hset(c, 0, "hash", strconv.Itoa(i), strconv.Itoa(rand.Int()), 1)
	}
	for i := 0; i < 10; i++ {
		s.hdel(c, 0, "hash", 1, strconv.Itoa(i))
		s.hdel(c, 0, "hash", 0, strconv.Itoa(i))
	}
	s.hgetall(c, 0, "hash")
	s.checkEmpty(c)
}
Beispiel #19
0
func randomLevel() int {
	randomBits := rand.Int()
	randomsLeft := BitsInRandom / 2
	level := 0
	b := 0

	for b == 0 {
		b = randomBits & 3
		if b == 0 {
			level = level + 1
		}

		randomBits = randomBits >> 2
		if randomsLeft = randomsLeft - 1; randomsLeft == 0 {
			randomBits = rand.Int()
			randomsLeft = BitsInRandom / 2
		}
	}

	if level > MaxLevel {
		return MaxLevel
	}

	return level
}
Beispiel #20
0
// setKeys sets n random keys and values across each machine in a
// cluster and returns these values to later be checked with checkKeys.
// If all the values don't get set due to a machine that is down and
// error is NOT returned. An error is returned if no keys are able to be
// set.
func SetKeys(cluster platform.Cluster, n int) (map[string]string, error) {
	var written = map[string]string{}
	for _, m := range cluster.Machines() {
		for i := 0; i < n; i++ {
			// random key and value, may overwrwite previous sets if
			// collision which is fine
			key := strconv.Itoa(rand.Int())[0:3]
			value := strconv.Itoa(rand.Int())[0:3]

			b, err := m.SSH(fmt.Sprintf("curl -s -w %%{http_code} -s http://127.0.0.1:2379/v2/keys/%v -XPUT -d value=%v", key, value))
			if err != nil {
				return nil, err
			}

			// check for 201 or 200 resp header
			if !bytes.HasSuffix(b, []byte("200")) && !bytes.HasSuffix(b, []byte("201")) {
				continue
			}

			written[key] = value
		}
	}
	if len(written) == 0 {
		return nil, fmt.Errorf("failed to write any keys")
	}

	plog.Infof("wrote %v keys", len(written))
	return written, nil
}
Beispiel #21
0
func TestSearchSmall(t *testing.T) {

	rand.Seed(0)

	const limit = 10000

	var ints []int

	for i := 0; i < limit; i++ {
		ints = append(ints, rand.Int())
	}

	sort.Ints(ints)

	for want, q := range ints {
		if idx := Search(ints, q); idx != want {
			t.Errorf("Search(ints, %v)=%v, want %v", q, idx, want)
		}
	}

	for i := 0; i < 10000; i++ {

		q := rand.Int()

		want := sort.SearchInts(ints, q)

		if idx := Search(ints, q); idx != want {
			t.Errorf("Search(ints, %v)=%v, want %v", q, idx, want)
		}
	}
}
Beispiel #22
0
func randColor() SimpleColor {
	return SimpleColor{
		uint8(rand.Int()%256 + 30),
		uint8(rand.Int()%256 + 30),
		uint8(rand.Int()%256 + 30),
	}
}
Beispiel #23
0
func (s *DockerServer) createContainer(w http.ResponseWriter, r *http.Request) {
	var config docker.Config
	defer r.Body.Close()
	err := json.NewDecoder(r.Body).Decode(&config)
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	image, err := s.findImage(config.Image)
	if err != nil {
		http.Error(w, err.Error(), http.StatusNotFound)
		return
	}
	w.WriteHeader(http.StatusCreated)
	ports := map[docker.Port][]docker.PortBinding{}
	for port := range config.ExposedPorts {
		ports[port] = []docker.PortBinding{{
			HostIp:   "0.0.0.0",
			HostPort: strconv.Itoa(mathrand.Int() % 65536),
		}}
	}

	//the container may not have cmd when using a Dockerfile
	var path string
	var args []string
	if len(config.Cmd) == 1 {
		path = config.Cmd[0]
	} else if len(config.Cmd) > 1 {
		path = config.Cmd[0]
		args = config.Cmd[1:]
	}

	container := docker.Container{
		ID:      s.generateID(),
		Created: time.Now(),
		Path:    path,
		Args:    args,
		Config:  &config,
		State: docker.State{
			Running:   false,
			Pid:       mathrand.Int() % 50000,
			ExitCode:  0,
			StartedAt: time.Now(),
		},
		Image: image,
		NetworkSettings: &docker.NetworkSettings{
			IPAddress:   fmt.Sprintf("172.16.42.%d", mathrand.Int()%250+2),
			IPPrefixLen: 24,
			Gateway:     "172.16.42.1",
			Bridge:      "docker0",
			Ports:       ports,
		},
	}
	s.cMut.Lock()
	s.containers = append(s.containers, &container)
	s.cMut.Unlock()
	s.notify(&container)
	var c = struct{ ID string }{ID: container.ID}
	json.NewEncoder(w).Encode(c)
}
Beispiel #24
0
func TestCreateNodeUpload(t *testing.T) {
	fmt.Println("in TestCreateNodeUpload()")

	u := &user.User{Uuid: ""}

	params := make(map[string]string)
	params["key1"] = "value1"
	params["key2"] = "value2"
	fmt.Println("params=", params)

	files := make(FormFiles)
	tmpPath := fmt.Sprintf("%s/temp/%d%d", conf.DATA_PATH, rand.Int(), rand.Int())
	fmt.Println("tmpPath=", tmpPath)
	formfile1 := FormFile{Name: "./testdata/10kb.fna", Path: tmpPath, Checksum: make(map[string]string)}
	files["file1"] = formfile1
	fmt.Println("files=", formfile1)

	node, err := CreateNodeUpload(u, params, files)
	fmt.Printf("node=%#v\n", node)

	if err != nil {
		fmt.Errorf("CreateNodeUpload error: %v ", err)
	}

}
Beispiel #25
0
// genRanges generates ordered, non-overlaping ranges with values in [0 and valRange).
func genRanges(num int, valRange int) [][2]int {
	// Generate num _distinct_ values. We do this by generating a partial permutation.
	perm := make([]int, valRange)
	for i := 0; i < valRange; i++ {
		perm[i] = i
	}
	for i := 0; i < num; i++ {
		// Choose a random element starting at i.
		pos := rand.Int() % (num - i)
		perm[i], perm[i+pos] = perm[i+pos], perm[i]
	}
	perm = perm[:num]
	// Sort the values. These distinct values will be the starts of our ranges.
	sort.Ints(perm)
	res := make([][2]int, num)
	for i := 0; i < num; i++ {
		res[i][0] = perm[i]
		next := valRange
		if i < num-1 {
			next = perm[i+1]
		}
		// Pick a random end in the range [perm[i], next).
		res[i][1] = perm[i] + rand.Int()%(next-perm[i])
	}
	return res
}
Beispiel #26
0
func TestAUC(t *testing.T) {
	predictions := []*LabelPrediction{}
	for i := 0; i < 1000; i++ {
		predictions = append(predictions, &(LabelPrediction{Label: rand.Int() % 2, Prediction: rand.Float64()}))
	}
	auc := AUC(predictions)
	if math.Abs(auc-0.5) > 0.05 {
		t.Error("Random predictions should have auc arround 0.5")
	}

	predictions = nil
	for i := 0; i < 1000; i++ {
		label := rand.Int() % 2
		prediction := rand.Float64()
		if label == 1 {
			prediction += 1.0
		}
		predictions = append(predictions, &(LabelPrediction{Label: label, Prediction: prediction}))
	}
	auc = AUC(predictions)
	if auc < 0.6 {
		t.Error("Asending predictions should have auc > 0.5")
	}

}
Beispiel #27
0
func (w *Writer) ExecuteBatch(batch store.KVBatch) error {

	emulatedBatch, ok := batch.(*store.EmulatedBatch)
	if !ok {
		return fmt.Errorf("wrong type of batch")
	}

	w.s.m.Lock()
	for k, mergeOps := range emulatedBatch.Merger.Merges {
		kb := []byte(k)
		var existingVal []byte
		existingItem := w.s.t.Get(&Item{k: kb})
		if existingItem != nil {
			existingVal = w.s.t.Get(&Item{k: kb}).(*Item).v
		}
		mergedVal, fullMergeOk := w.s.mo.FullMerge(kb, existingVal, mergeOps)
		if !fullMergeOk {
			return fmt.Errorf("merge operator returned failure")
		}
		w.s.t = w.s.t.Upsert(&Item{k: kb, v: mergedVal}, rand.Int())
	}

	for _, op := range emulatedBatch.Ops {
		if op.V != nil {
			w.s.t = w.s.t.Upsert(&Item{k: op.K, v: op.V}, rand.Int())
		} else {
			w.s.t = w.s.t.Delete(&Item{k: op.K})
		}
	}
	w.s.m.Unlock()

	return nil
}
Beispiel #28
0
func main() {
	flag.Parse()
	//	prime()
	var blocks [1]struct {
		base *byte
		siz  uintptr
	}
	for i := 0; i < 1<<10; i++ {
		if i%(1<<10) == 0 && *chatty {
			println(i)
		}
		b := rand.Int() % len(blocks)
		if blocks[b].base != nil {
			//	println("Free", blocks[b].siz, blocks[b].base)
			runtime.Free(blocks[b].base)
			blocks[b].base = nil
			allocated -= uint64(blocks[b].siz)
			continue
		}
		siz := uintptr(rand.Int() >> (11 + rand.Uint32()%20))
		base := runtime.Alloc(siz)
		//	ptr := uintptr(syscall.BytePtr(base))+uintptr(siz/2)
		//	obj, size, ref, ok := allocator.find(ptr)
		//	if obj != base || *ref != 0 || !ok {
		//		println("find", siz, obj, ref, ok)
		//		panic("fail")
		//	}
		blocks[b].base = base
		blocks[b].siz = siz
		allocated += uint64(siz)
		//	println("Alloc", siz, base)
		memset(base, 0xbb, siz)
		bigger()
	}
}
Beispiel #29
0
func (c Test) initData(userId int, fieldGroup FieldGroup, masterData *map[string]interface{}) {
	dateUtil := DateUtil{}
	if fieldGroup.FieldDataType == "STRING" {
		(*masterData)[fieldGroup.Id] = "user" + fmt.Sprint(userId) + "_data_" + fmt.Sprint(rand.Int())
	} else if fieldGroup.FieldDataType == "FLOAT" {
		(*masterData)[fieldGroup.Id] = fmt.Sprint(rand.Float64())[:10]
	} else if fieldGroup.FieldNumberType == "YEAR" {
		(*masterData)[fieldGroup.Id] = dateUtil.GetCurrentYyyyMMdd() / (100 * 100)
	} else if fieldGroup.FieldNumberType == "YEARMONTH" {
		(*masterData)[fieldGroup.Id] = dateUtil.GetCurrentYyyyMMdd() / 100
	} else if fieldGroup.FieldNumberType == "DATE" {
		(*masterData)[fieldGroup.Id] = dateUtil.GetCurrentYyyyMMdd()
	} else if fieldGroup.FieldNumberType == "TIME" {
		(*masterData)[fieldGroup.Id] = 180605
	} else if fieldGroup.FieldNumberType == "DATETIME" {
		(*masterData)[fieldGroup.Id] = dateUtil.GetCurrentYyyyMMddHHmmss()
	} else { // int
		if fieldGroup.Id == "billTypeId" {
			(*masterData)[fieldGroup.Id] = 1
		} else if fieldGroup.Id == "billTypeParameterId" {
			(*masterData)[fieldGroup.Id] = 1
		} else if fieldGroup.Id == "currencyTypeId" {
			(*masterData)[fieldGroup.Id] = 1
		} else {
			(*masterData)[fieldGroup.Id] = rand.Int()
		}
	}
}
Beispiel #30
0
func genWinLog(l *logger.Log) {
	m := make(map[string]interface{})

	m["v"] = "1"
	m["log_type"] = "32"
	m["time_stamp"] = currentTimeString()
	m["ad_id"] = "cafefeed"
	m["order_id"] = "deadbeaf"
	m["exchange_user_id"] = "9"
	//m["dsp_user_id"] = ?
	m["media_type"] = "2"
	m["uuid"] = uuid()
	m["adexchange_id"] = "9" // yesky
	m["user_id"] = "abcd"
	m["user_agent"] = ""
	m["strike_price"] = strconv.Itoa(rand.Int() % 200)
	m["region_id"] = ""
	m["browser"] = "chrome"
	m["operation"] = "MacOS"
	m["language"] = "zh"
	m["agent_price"] = "110"
	m["advertiser_price"] = "120"
	m["reffer"] = ""
	m["adslot_id"] = strconv.Itoa(rand.Int() % 10)
	//m["adslot_position_relative"] = ?
	m["bid_id"] = uuid()
	m["price"] = m["strike_price"]
	m["key"] = "abcdef1234567"
	if b, e := json.Marshal(m); e != nil {
		return
	} else {
		l.Log(logger.INFO, string(b))
	}
}