Ejemplo n.º 1
0
Archivo: util.go Proyecto: lumjjb/rabin
func MakeRandom(gen *rand.Rand, degree int) *Polynomial {
	if degree == 0 {
		return NewPolynomialFromInt(gen.Int63n(2))
	}

	coeffs := new(big.Int)
	// x^0 + x^1 + ... + x^n => n + 1 terms
	// However, only the first n terms are variable.  (x^n is fixed to
	// have degree n.)  Thus, we randomly generate the first n terms
	// and fix the final term x^n.
	numBits := degree
	numBlocks := numBits / 32
	for ii := 0; ii < numBlocks; ii++ {
		v := gen.Uint32()

		// Merge.
		bigV := big.NewInt(int64(v))
		coeffs.Lsh(coeffs, 32).Or(coeffs, bigV)
	}
	// Handle the remainder.
	numRemainingBits := uint(numBits % 32)
	if numRemainingBits > 0 {
		mask := (int64(1) << numRemainingBits) - 1
		v := int64(gen.Uint32()) & mask
		coeffs.Lsh(coeffs, numRemainingBits).Or(coeffs, big.NewInt(v))
	}
	coeffs.SetBit(coeffs, degree, 1)
	return NewPolynomial(uint(degree), coeffs)
}
Ejemplo n.º 2
0
func NewIOContext(r *rand.Rand, oldContext store.IOContext) store.IOContext {
	randomNumDocs := r.Intn(4192)
	size := r.Int63n(512) * int64(randomNumDocs)
	if oldContext.FlushInfo != nil {
		// Always return at least the estimatedSegmentSize of the
		// incoming IOContext:
		if size < oldContext.FlushInfo.EstimatedSegmentSize {
			size = oldContext.FlushInfo.EstimatedSegmentSize
		}
		return store.NewIOContextForFlush(&store.FlushInfo{randomNumDocs, size})
	} else if oldContext.MergeInfo != nil {
		// Always return at least the estimatedMergeBytes of the
		// incoming IOContext:
		if size < oldContext.MergeInfo.EstimatedMergeBytes {
			size = oldContext.MergeInfo.EstimatedMergeBytes
		}
		return store.NewIOContextForMerge(
			&store.MergeInfo{randomNumDocs, size, r.Intn(2) == 0, NextInt(r, 1, 100)})
	} else {
		// Make a totally random IOContext:
		switch r.Intn(5) {
		case 1:
			return store.IO_CONTEXT_READ
		case 2:
			return store.IO_CONTEXT_READONCE
		case 3:
			return store.NewIOContextForMerge(&store.MergeInfo{randomNumDocs, size, true, -1})
		case 4:
			return store.NewIOContextForFlush(&store.FlushInfo{randomNumDocs, size})
		default:
			return store.IO_CONTEXT_DEFAULT
		}
	}
}
Ejemplo n.º 3
0
//Determine a read or a write operation
func insertRWKey(q *Query, k Key, rr float64, rnd *rand.Rand) {
	x := float64(rnd.Int63n(100))
	if x < rr {
		q.rKeys = append(q.rKeys, k)
	} else {
		q.wKeys = append(q.wKeys, k)
	}
}
Ejemplo n.º 4
0
// GenerateCursor generates a cursor with a random data.
func GenerateCursor(tmin, step int64, ascending bool, rand *rand.Rand) *Cursor {
	key := tmin + rand.Int63n(10)
	items := make([]CursorItem, 0)
	for i, n := 0, rand.Intn(100); i < n; i++ {
		items = append(items, CursorItem{
			Key:   key,
			Value: int64(0),
		})
		key += rand.Int63n(10)
	}
	return NewCursor(items, ascending)
}
Ejemplo n.º 5
0
// GeneratePointsSlice randomly generates a slice of slice of points.
func GeneratePointsSlice(rand *rand.Rand) PointsSlice {
	var pointsSlice PointsSlice
	for i, pointsN := 0, rand.Intn(100); i < pointsN; i++ {
		var points Points
		for j, pointN := 0, rand.Intn(1000); j < pointN; j++ {
			points = append(points, Point{
				Name:   strconv.Itoa(rand.Intn(10)),
				Fields: models.Fields{"value": rand.Int63n(100000)},
				Time:   time.Unix(0, rand.Int63n(int64(24*time.Hour))).UTC(),
			})
		}
		pointsSlice = append(pointsSlice, points)
	}
	return pointsSlice
}
Ejemplo n.º 6
0
func readShuffled(in io.Reader, rand *rand.Rand) []TrainingInstance {
	reader, err := input.NewTrainDataReader(in)
	common.ExitIfError("Error reading data: ", err)

	instances := make([]TrainingInstance, 0)

	for {
		err := reader.Scan()
		if err == io.EOF {
			break
		} else {
			common.ExitIfError("Error reading data: ", err)
		}

		instance := TrainingInstance{
			X: reader.InputVector().Dup(),
			Y: reader.Label(),
		}

		idx := rand.Int63n(int64(len(instances)) + 1)
		if int(idx) == len(instances) {
			instances = append(instances, instance)
		} else {
			instances = append(instances, instances[idx])
			instances[idx] = instance
		}
	}

	return instances
}
Ejemplo n.º 7
0
func testConn(c *RCConn, rng *rand.Rand, newRegion regionFunc) {
	c.SetTimeout(rng.Int63n(maxTimeout))
	var err error
	var errError string
	nmessages := rng.Intn(10)
	for i := 0; i < nmessages; i++ {
		mr := newRegion(rng)
		switch rng.Intn(3) {
		case 0:
			fmt.Printf("reading %v\n", mr)
			// Because timeout errors also continue the loop, two
			// readers connected to each other will also eventually
			// make progress.
			err = c.Read(mr)
		case 1:
			fmt.Printf("writing %v\n", mr)
			err = c.Write(mr)
		case 2:
			fmt.Printf("sleeping for up to maxTimeout\n")
			time.Sleep(time.Duration(rng.Int63n(maxTimeout)))
		default:
			panic("invalid mode")
		}
		if err != nil {
			// Save error string now so that it doesn't refer to a
			// closed memory region when it is printed later.
			errError = err.Error()
		}
		if err := mr.Close(); err != nil {
			panic(err)
		}
		if err != nil {
			if t, ok := err.(timeout); ok && t.Timeout() {
				continue
			}
			break
		}
	}
	if err == nil {
		fmt.Printf("SUCCESSFUL EXCHANGE of %d MESSAGES\n", nmessages)
	} else {
		fmt.Printf("%v\n", errError)
	}
	if err := c.Close(); err != nil {
		panic("close failed: " + err.Error())
	}
}
Ejemplo n.º 8
0
func (t *msgAllTypes) Generate(rand *rand.Rand, size int) reflect.Value {
	m := &msgAllTypes{}
	m.Bool = rand.Intn(2) == 1
	randomBytes(m.Array[:], rand)
	m.Uint64 = uint64(rand.Int63n(1<<63 - 1))
	m.Uint32 = uint32(rand.Intn((1 << 31) - 1))
	m.Uint8 = uint8(rand.Intn(1 << 8))
	m.String = string(m.Array[:])
	m.Strings = randomNameList(rand)
	m.Bytes = m.Array[:]
	m.Int = randomInt(rand)
	m.Rest = m.Array[:]
	return reflect.ValueOf(m)
}
Ejemplo n.º 9
0
func BenchmarkHbaseGet(b *testing.B) {
	var (
		err error
		h   = NewHBaseClient()
		t   int64
		r   *rand.Rand
	)
	if err = Init("172.16.13.90:9090", 5*time.Second, 200, 200); err != nil {
		b.Errorf("Init failed")
		b.FailNow()
	}
	r = rand.New(rand.NewSource(time.Now().UnixNano()))
	b.ResetTimer()
	b.SetParallelism(8)
	b.RunParallel(func(pb *testing.PB) {
		for pb.Next() {
			t = r.Int63n(1000000)
			if _, err = h.Get(t); err != nil {
				b.Errorf("Put() error(%v)", err)
				b.FailNow()
			}
		}
	})
}
Ejemplo n.º 10
0
// Generate returns a randomly generated cursor. Implements quick.Generator.
func (c Cursor) Generate(rand *rand.Rand, size int) reflect.Value {
	c.index = 0
	c.ascending = true

	c.items = make([]CursorItem, rand.Intn(size))
	for i := range c.items {
		c.items[i] = CursorItem{
			Key:   rand.Int63n(int64(size)),
			Value: rand.Int(),
		}
	}

	// Sort items by key.
	sort.Sort(CursorItems(c.items))

	return reflect.ValueOf(c)
}
Ejemplo n.º 11
0
// GenerateFloatIterator creates a FloatIterator with random data.
func GenerateFloatIterator(rand *rand.Rand, valueN int) *FloatIterator {
	const interval = 10 * time.Second

	itr := &FloatIterator{
		Points: make([]influxql.FloatPoint, valueN),
	}

	for i := 0; i < valueN; i++ {
		// Generate incrementing timestamp with some jitter (1s).
		jitter := (rand.Int63n(2) * int64(time.Second))
		timestamp := int64(i)*int64(10*time.Second) + jitter

		itr.Points[i] = influxql.FloatPoint{
			Time:  timestamp,
			Value: rand.Float64(),
		}
	}

	return itr
}
Ejemplo n.º 12
0
// RandDatum generates a random Datum of the given type.
// If null is true, the datum can be DNull.
func RandDatum(rng *rand.Rand, typ ColumnType, null bool) parser.Datum {
	if null && rng.Intn(10) == 0 {
		return parser.DNull
	}
	switch typ.Kind {
	case ColumnType_BOOL:
		return parser.MakeDBool(rng.Intn(2) == 1)
	case ColumnType_INT:
		return parser.NewDInt(parser.DInt(rng.Int63()))
	case ColumnType_FLOAT:
		return parser.NewDFloat(parser.DFloat(rng.NormFloat64()))
	case ColumnType_DECIMAL:
		d := &parser.DDecimal{}
		d.Dec.SetScale(inf.Scale(rng.Intn(40) - 20))
		d.Dec.SetUnscaled(rng.Int63())
		return d
	case ColumnType_DATE:
		return parser.NewDDate(parser.DDate(rng.Intn(10000)))
	case ColumnType_TIMESTAMP:
		return &parser.DTimestamp{Time: time.Unix(rng.Int63n(1000000), rng.Int63n(1000000))}
	case ColumnType_INTERVAL:
		return &parser.DInterval{Duration: duration.Duration{Months: rng.Int63n(1000),
			Days:  rng.Int63n(1000),
			Nanos: rng.Int63n(1000000),
		}}
	case ColumnType_STRING:
		// Generate a random ASCII string.
		p := make([]byte, rng.Intn(10))
		for i := range p {
			p[i] = byte(1 + rng.Intn(127))
		}
		return parser.NewDString(string(p))
	case ColumnType_BYTES:
		p := make([]byte, rng.Intn(10))
		_, _ = rng.Read(p)
		return parser.NewDBytes(parser.DBytes(p))
	case ColumnType_TIMESTAMPTZ:
		return &parser.DTimestampTZ{Time: time.Unix(rng.Int63n(1000000), rng.Int63n(1000000))}
	case ColumnType_COLLATEDSTRING:
		if typ.Locale == nil {
			panic("locale is required for COLLATEDSTRING")
		}
		// Generate a random Unicode string.
		var buf bytes.Buffer
		n := rng.Intn(10)
		for i := 0; i < n; i++ {
			var r rune
			for {
				r = rune(rng.Intn(unicode.MaxRune + 1))
				if !unicode.Is(unicode.C, r) {
					break
				}
			}
			buf.WriteRune(r)
		}
		return parser.NewDCollatedString(buf.String(), *typ.Locale, &parser.CollationEnvironment{})
	case ColumnType_INT_ARRAY:
		// TODO(cuongdo): we don't support for persistence of arrays yet
		return parser.DNull
	default:
		panic(fmt.Sprintf("invalid type %s", typ.String()))
	}
}
Ejemplo n.º 13
0
// choose returns a random unicode character from the given range, using the
// given randomness source.
func (r *charRange) choose(rand *rand.Rand) rune {
	count := int64(r.last - r.first)
	return r.first + rune(rand.Int63n(count))
}
Ejemplo n.º 14
0
func (Points) Generate(rand *rand.Rand, size int) reflect.Value {
	// Generate series with a random number of points in each.
	m := make(map[string][][]byte)
	for i, seriesN := 0, rand.Intn(size); i < seriesN; i++ {
		key := strconv.Itoa(rand.Intn(1000))

		// Generate points for the series.
		for j, pointN := 0, rand.Intn(size); j < pointN; j++ {
			timestamp := time.Date(2000, time.January, 1, 0, 0, 0, 0, time.UTC).Add(time.Duration(rand.Int63n(int64(365 * 24 * time.Hour))))
			data, ok := quick.Value(reflect.TypeOf([]byte(nil)), rand)
			if !ok {
				panic("cannot generate data")
			}
			m[key] = append(m[key], bz1.MarshalEntry(timestamp.UnixNano(), data.Interface().([]byte)))
		}
	}

	return reflect.ValueOf(Points(m))
}
Ejemplo n.º 15
0
Archivo: get.go Proyecto: polluxx/yard
func ReturnRand(volume int64, r *rand.Rand) string {
	return fmt.Sprintf("%v%v", r.Int63n(volume), strings.Replace(fmt.Sprintf("%v", r.Float32()), "0", "", 1))
}
Ejemplo n.º 16
0
func randomSize(r *rand.Rand) Size {
	s := Size(1 << uint(intn(r, 10, 30, 60, 80, 80, 40, 30, 10)<<2))
	s += Size(r.Int63n(int64(s)<<(1<<2) - int64(s)))
	return s
}
Ejemplo n.º 17
0
func NewSpell(r *rand.Rand) *Spell {
	s := &Spell{}

	// randomly executes one or more of the argument functions.
	bits := func(funcs ...func()) {
		// bitfield. lowest bit corresponds to first argument.
		run := r.Intn(1<<uint(len(funcs))-1) + 1

		for i, f := range funcs {
			if (run>>uint(i))&1 == 1 {
				f()
			}
		}
	}

	// returns a random time.Duration within [min, max).
	randTime := func(min, max time.Duration) time.Duration {
		return time.Duration(r.Int63n(int64(max-min+1))) + min
	}

	bits(func() {
		// warmup
		s.Warmup = randTime(time.Second/5, 5*time.Second)
	}, func() {
		// cooldown
		s.Cooldown = randTime(time.Second/5, 5*time.Second)
	})

	initStats := func(m map[BaseSpell]*big.Int, negative bool) {
		max := big.NewInt(100000)

		var statFuncs [BaseSpellCount]func()
		for i := range statFuncs {
			statFuncs[i] = func(s BaseSpell) func() {
				return func() {
					m[s] = (&big.Int{}).Rand(r, max)
					if negative {
						m[s].Neg(m[s])
					}
				}
			}(BaseSpell(i))
		}

		bits(statFuncs[:]...)
	}

	bits(func() {
		// effect
		s.Effect = randTime(time.Second/5, 5*time.Second)

		bits(func() {
			// self
			s.SelfEffect = make(map[BaseSpell]*big.Int)
			initStats(s.SelfEffect, false)
		}, func() {
			// target
			s.TargetEffect = make(map[BaseSpell]*big.Int)
			initStats(s.TargetEffect, true)
		})
	}, func() {
		if r.Intn(2) < 1 {
			// channel
			s.Channel = randTime(time.Second/5, 5*time.Second)
		} // else instant

		bits(func() {
			// self
			s.SelfDirect = make(map[BaseSpell]*big.Int)
			initStats(s.SelfDirect, false)
		}, func() {
			// target
			s.TargetDirect = make(map[BaseSpell]*big.Int)
			initStats(s.TargetDirect, true)
		})
	})

	return s
}
Ejemplo n.º 18
0
// RandDatum generates a random Datum of the given type.
// If null is true, the datum can be DNull.
func RandDatum(rng *rand.Rand, typ ColumnType_Kind, null bool) parser.Datum {
	if null && rng.Intn(10) == 0 {
		return parser.DNull
	}
	switch typ {
	case ColumnType_BOOL:
		return parser.MakeDBool(rng.Intn(2) == 1)
	case ColumnType_INT:
		return parser.NewDInt(parser.DInt(rng.Int63()))
	case ColumnType_FLOAT:
		return parser.NewDFloat(parser.DFloat(rng.NormFloat64()))
	case ColumnType_DECIMAL:
		d := &parser.DDecimal{}
		d.Dec.SetScale(inf.Scale(rng.Intn(40) - 20))
		d.Dec.SetUnscaled(rng.Int63())
		return d
	case ColumnType_DATE:
		return parser.NewDDate(parser.DDate(rng.Intn(10000)))
	case ColumnType_TIMESTAMP:
		return &parser.DTimestamp{Time: time.Unix(rng.Int63n(1000000), rng.Int63n(1000000))}
	case ColumnType_INTERVAL:
		return &parser.DInterval{Duration: duration.Duration{Months: rng.Int63n(1000),
			Days:  rng.Int63n(1000),
			Nanos: rng.Int63n(1000000),
		}}
	case ColumnType_STRING:
		// Generate a random ASCII string.
		p := make([]byte, rng.Intn(10))
		for i := range p {
			p[i] = byte(1 + rng.Intn(127))
		}
		return parser.NewDString(string(p))
	case ColumnType_BYTES:
		p := make([]byte, rng.Intn(10))
		_, _ = rng.Read(p)
		return parser.NewDBytes(parser.DBytes(p))
	case ColumnType_TIMESTAMPTZ:
		return &parser.DTimestampTZ{Time: time.Unix(rng.Int63n(1000000), rng.Int63n(1000000))}
	default:
		panic(fmt.Sprintf("invalid type %s", typ))
	}
}
Ejemplo n.º 19
0
func durationJitter(d time.Duration, r *rand.Rand) time.Duration {
	if d == 0 {
		return 0
	}
	return d + time.Duration(r.Int63n(2*int64(d)))
}