Пример #1
0
func init() {
	rand.Seed(time.Now().UnixNano())
	http.HandleFunc("/dirtexto", directorioTexto)
	//http.HandleFunc("/carr", carr)
	http.HandleFunc("/carr", carrVip)
	rand.Seed(time.Now().UnixNano())
}
Пример #2
0
// Start the agent-based model
func (m *Model) Start() error {
	if m.running {
		return errors.New("Model: Start() failed: model already running")
	}
	m.running = true
	if m.RNGRandomSeed {
		rand.Seed(time.Now().UnixNano())
	} else {
		rand.Seed(m.RNGSeedVal)
	}
	timestamp := fmt.Sprintf("%s", time.Now())
	m.popCpPrey = GenerateCpPreyPopulation(m.CpPreyPopulationStart, m.numCpPreyCreated, m.Turn, m.ConditionParams, timestamp)
	m.numCpPreyCreated += m.CpPreyPopulationStart
	m.popVisualPredator = GenerateVPredatorPopulation(m.VpPopulationStart, m.numVpCreated, m.Turn, m.ConditionParams, timestamp)
	m.numVpCreated += m.VpPopulationStart
	if m.Logging {
		go m.log(m.e)
	}
	if m.Visualise {
		go m.vis(m.e)
	}
	time.Sleep(pause)
	go m.run(m.e)
	return nil
}
Пример #3
0
func main() {
	fmt.Println("My favortie number is ", rand.Intn(10))
	fmt.Println("Another random int", rand.Intn(10))

	// Try to Seed with 1
	rand.Seed(1)
	fmt.Println("First sequence")
	for i := 0; i < 10; i++ {
		fmt.Println(rand.Intn(10))
	}

	// Seed again with 1: Numbers are the same
	rand.Seed(1)
	fmt.Println("Second sequence")
	for i := 0; i < 10; i++ {
		fmt.Println(rand.Intn(10))
	}

	// Seed with 2
	rand.Seed(2)
	fmt.Println("Third sequence")
	for i := 0; i < 10; i++ {
		fmt.Println(rand.Intn(10))
	}
}
Пример #4
0
Файл: main.go Проект: apg/spew
func main() {
	var i = 0
	var buf []byte

	// Repeatable payloads.
	if seed, err := strconv.ParseInt(os.Getenv("SEED"), 10, 32); err == nil {
		rand.Seed(seed)
	} else {
		rand.Seed(defaultSeed)
	}

	sleepTime, err := parseRate(os.Getenv("RATE"))
	if err != nil {
		log.Println("Duration Parsing: ", err)
		log.Println("Continuing w/o duration")
	}

	mlen, err := strconv.ParseInt(os.Getenv("MSGSIZE"), 10, 32)
	if err == nil && mlen > 0 {
		buf = make([]byte, mlen)
	} else {
		log.Println("Unable to parse MSGSIZE, defaulting to MSGSIZE of", defaultMsgSize)
		buf = make([]byte, defaultMsgSize)
	}

	for {
		i++
		if sleepTime > 0 {
			time.Sleep(sleepTime)
		}

		fmt.Println(i, "spews", randStr(buf))
	}
}
Пример #5
0
// seed PRNG to value given, if it is 0 seed to current time
func seedPRNG(seed int64) {
	if seed == 0 {
		rand.Seed(time.Now().UTC().UnixNano())
	} else {
		rand.Seed(seed)
	}
}
Пример #6
0
//pada fungsi ini akan menyimpan data yang digunakan sebagai input
func main() {
	// change "64" to anything else to see
	rand.Seed(8)
	sl := New()
	sl.Set(Int(6), 1)
	sl.Set(Int(5), 2)
	sl.Set(Int(4), 4)
	sl.Set(Int(9), 0)
	sl.draw() // 4-5-6-9-

	valuenya, ketemu := sl.Search(Int(5)) // Found! = 5
	fmt.Println(valuenya)                 //2
	fmt.Println(ketemu)                   // true
	valuenya, ketemu = sl.Search(Int(4))  // Found! = 4
	fmt.Println(valuenya)                 //4
	fmt.Println(ketemu)                   // true
	valuenya, ketemu = sl.Search(Int(6))  // Found! = 6
	fmt.Println(valuenya)                 //1
	fmt.Println(ketemu)                   // true
	valuenya, ketemu = sl.Search(Int(9))  // Found! = 9
	fmt.Println(valuenya)                 //0
	fmt.Println(ketemu)                   // true

	sl.Delete(Int(5))
	sl.draw()                            // 4---6-9-
	valuenya, ketemu = sl.Search(Int(5)) //  No Match Found!
	fmt.Println(valuenya)                //<nil>
	fmt.Println(ketemu)                  // false
	sl.draw()                            // 4---6-9-

	rand.Seed(8)
	s2 := New()
	s2.Set(String("h"), 1)
	s2.Set(String("c"), 2)
	s2.Set(String("i"), 4)
	s2.Set(String("s"), 0)
	s2.draw() // c-h-i-s-

	valuenya, ketemu = s2.Search(String("c")) // Found! = c
	fmt.Println(valuenya)                     //2
	fmt.Println(ketemu)                       // true
	valuenya, ketemu = s2.Search(String("i")) // Found! = i
	fmt.Println(valuenya)                     //4
	fmt.Println(ketemu)                       // true
	valuenya, ketemu = s2.Search(String("s")) // Found! = s
	fmt.Println(valuenya)                     //0
	fmt.Println(ketemu)                       // true
	valuenya, ketemu = s2.Search(String("h")) // Found! = h
	fmt.Println(valuenya)                     //1
	fmt.Println(ketemu)                       // true

	s2.Delete(String("i"))
	s2.draw()                                 // c-h---s-
	valuenya, ketemu = s2.Search(String("i")) // No Match Found!
	fmt.Println(valuenya)                     //<nil>
	fmt.Println(ketemu)                       // false
	s2.draw()                                 // c-h---s-

}
Пример #7
0
func main() {
	IntSlice := make(IntArr, 12)
	fmt.Print("Awal : ")
	for i := 0; i < 12; i++ {
		rand.Seed(time.Now().UTC().UnixNano())
		IntSlice[i] = rand.Intn(50)
		fmt.Print(IntSlice[i], " ")
	}
	fmt.Println()
	CocktailSort(IntSlice)
	fmt.Print("Sesudah Sorting : ")
	for i := 0; i < 12; i++ {
		fmt.Print(IntSlice[i], " ")
	}
	fmt.Println("\n")

	StringSlice := StringArr{"nama", "saya", "adalah", "alvreda", "ivena"}
	fmt.Print("Awal : ")
	for i := 0; i < 5; i++ {
		fmt.Print(StringSlice[i], " ")
	}
	fmt.Println()
	CocktailSort(StringSlice)
	fmt.Print("Sesudah Sorting : ")
	for i := 0; i < 5; i++ {
		fmt.Print(StringSlice[i], " ")
	}
	fmt.Println("\n")

	Float32Slice := make(Float32Arr, 6)
	fmt.Print("Awal : ")
	for i := 0; i < 6; i++ {
		rand.Seed(time.Now().UTC().UnixNano())
		Float32Slice[i] = rand.Float32()
		fmt.Print(Float32Slice[i], " ")
	}
	fmt.Println()
	CocktailSort(Float32Slice)
	fmt.Print("Sesudah Sorting : ")
	for i := 0; i < 6; i++ {
		fmt.Print(Float32Slice[i], " ")
	}
	fmt.Println("\n")

	Float64Slice := make(Float64Arr, 6)
	fmt.Print("Awal : ")
	for i := 0; i < 6; i++ {
		rand.Seed(time.Now().UTC().UnixNano())
		Float64Slice[i] = rand.Float64()
		fmt.Print(Float64Slice[i], " ")
	}
	fmt.Println()
	CocktailSort(Float64Slice)
	fmt.Print("Sesudah Sorting : ")
	for i := 0; i < 6; i++ {
		fmt.Print(Float64Slice[i], " ")
	}
	fmt.Println()
}
Пример #8
0
func TestReserveOneVolume(t *testing.T) {
	topo := setup(topologyLayout)
	rand.Seed(time.Now().UnixNano())
	rand.Seed(1)
	ret, node, vid := topo.RandomlyReserveOneVolume()
	fmt.Println("assigned :", ret, ", node :", node, ", volume id:", vid)

}
Пример #9
0
func randomDate() time.Time {
	rand.Seed(time.Now().Unix())
	randomMonth := rand.Intn(108)
	rand.Seed(time.Now().Unix() + int64(randomMonth))
	randomDay := rand.Intn(30)

	return time.Now().AddDate(0, -randomMonth, -randomDay)
}
Пример #10
0
func TestRetry(t *testing.T) {
	defer func() {
		timeAfter = time.After
	}()
	rh := &Helper{
		Backoff:   2,
		Retries:   5,
		Delay:     300 * time.Millisecond,
		MaxDelay:  2 * time.Second,
		MaxJitter: 5 * time.Millisecond,
	}
	durations := []time.Duration{
		300 * time.Millisecond,
		600 * time.Millisecond,
		1200 * time.Millisecond,
		2 * time.Second,
		2 * time.Second,
	}
	rand.Seed(1)
	for i := range durations {
		jitter := rand.Int63n(int64(rh.MaxJitter))
		durations[i] += time.Duration(jitter)
	}
	actualRetries := 0
	timeAfter = func(d time.Duration) <-chan time.Time {
		if actualRetries >= len(durations) {
			t.Fatalf("Maximum retry attempts exceeded: got %d", actualRetries)
		}
		if d != durations[actualRetries] {
			t.Errorf("Mismatched duration: got %s; want %s", d, durations[actualRetries])
		}
		actualRetries++
		c := make(chan time.Time, 1)
		c <- time.Now().Add(d)
		return c
	}
	noErrFunc := func() error { return nil }
	rand.Seed(1)
	retries, err := rh.RetryFunc(noErrFunc)
	if err != nil {
		t.Errorf("RetryFunc returned error for non-error function: %s", err)
	}
	if retries != 0 {
		t.Errorf("Mismatched retry attempt count: got %d", retries)
	}
	lastErr := &retryErr{5, true}
	errFunc := func() (err error) {
		return lastErr
	}
	rand.Seed(1)
	retries, err = rh.RetryFunc(errFunc)
	if retries != actualRetries {
		t.Errorf("Mismatched retry attempt count: got %d; want %d", retries, actualRetries)
	}
	if err != lastErr {
		t.Errorf("Unexpected retry error: got %q; want %q", err, lastErr)
	}
}
Пример #11
0
// Seed sequential random with crypto or math/random and current time
// and generate crypto prefix.
func init() {
	r, err := rand.Int(rand.Reader, big.NewInt(math.MaxInt64))
	if err != nil {
		prand.Seed(time.Now().UnixNano())
	} else {
		prand.Seed(r.Int64())
	}
	globalNUID = &lockedNUID{NUID: New()}
	globalNUID.RandomizePrefix()
}
Пример #12
0
func seedRand() {
	n, err := rand.Int(rand.Reader, big.NewInt(9223372036854775806))
	if err != nil {
		mathrand.Seed(time.Now().UTC().UnixNano())
		return
	}

	mathrand.Seed(n.Int64())
	return
}
Пример #13
0
func initGo() {
	fmt.Printf("Initializing Go System (%d threads)\n", numProcs)
	if debug {
		rt.GOMAXPROCS(2)
		rand.Seed(0)
	} else {
		rt.GOMAXPROCS(numProcs)
		rand.Seed(rand.Int63())
	}
}
Пример #14
0
func init() {
	// Seed the math/rand RNG from crypto/rand.
	s := make([]byte, 8)
	if _, err := crand.Read(s); err == nil {
		rand.Seed(int64(binary.BigEndian.Uint64(s)))
		return
	}
	// Fall back to system time, boo hoo.
	rand.Seed(time.Now().UnixNano())
}
Пример #15
0
/**
 * Tests that the key is correctly updated in each node's storage system.
 */
func testSingleProposerUpdateKey(doneChan chan bool) {
	key := "b"

	// send first proposal
	randint, _ := crand.Int(crand.Reader, big.NewInt(math.MaxInt64))
	rand.Seed(randint.Int64())
	value := rand.Uint32()
	if _, ok := pt.cliMap[1]; !ok {
		LOGE.Println("FAIL: missing node 1")
		doneChan <- false
		return
	}

	pnum, err := pt.GetNextProposalNumber(key, 1)
	reply, err := pt.Propose(key, value, pnum.N, 1)

	if err != nil {
		printFailErr("Propose", err)
		doneChan <- false
		return
	}

	// send second proposal
	randint, _ = crand.Int(crand.Reader, big.NewInt(math.MaxInt64))
	rand.Seed(randint.Int64())
	value = rand.Uint32()

	pnum2, err := pt.GetNextProposalNumber(key, 1)
	// the proposal numbers should be monotonically increasing
	if pnum.N >= pnum2.N {
		LOGE.Println("FAIL: newer proposal number is less than or equal to older proposal number")
		doneChan <- false
		return
	}

	reply, err = pt.Propose(key, value, pnum2.N, 1)
	if err != nil {
		printFailErr("Propose", err)
		doneChan <- false
		return
	}

	if !checkProposeReply(reply, key, value) {
		doneChan <- false
		return
	}

	if !checkGetValueAll(key, value) {
		doneChan <- false
		return
	}

	doneChan <- true
}
Пример #16
0
// SeedMathRand provides weak, but guaranteed seeding, which is better than
// running with Go's default seed of 1.  A call to SeedMathRand() is expected
// to be called via init(), but never a second time.
func SeedMathRand() {
	once.Do(func() {
		n, err := crand.Int(crand.Reader, big.NewInt(math.MaxInt64))
		if err != nil {
			rand.Seed(time.Now().UTC().UnixNano())
			return
		}
		rand.Seed(n.Int64())
		SeededSecurely = true
	})
}
Пример #17
0
Файл: model.go Проект: hqr/surge
func __init() {
	allModels = make(map[ModelName]ModelInterface, maxModels)
	allModelProps = make(map[ModelName]map[string]interface{}, maxModels)

	if config.srand == 0 {
		rand.Seed(time.Now().UTC().UnixNano())
	} else {
		rand.Seed(int64(config.srand))
	}
	inited = true
}
Пример #18
0
func beer(t time.Time) string {
	if t.Weekday().String() == "Friday" && t.Hour() >= 16 {
		rand.Seed(time.Now().UnixNano())
		yup := ayes[rand.Intn(len(ayes))]
		return yup
	} else if t.Month().String() == "December" && t.Day() == 24 {
		return "Merry Beermas!"
	} else {
		rand.Seed(time.Now().UnixNano())
		nope := nays[rand.Intn(len(nays))]
		return nope
	}
}
Пример #19
0
func testDeterm(i int, t *testing.T) {
	var length = 500000
	if testing.Short() {
		length = 100000
	}
	rand.Seed(1337)
	t1 := make([]byte, length)
	for idx := range t1 {
		t1[idx] = byte(65 + rand.Intn(8))
	}

	br := bytes.NewBuffer(t1)
	var b1 bytes.Buffer
	w, err := NewWriterLevel(&b1, i)
	if err != nil {
		t.Fatal(err)
	}
	_, err = io.Copy(w, br)
	if err != nil {
		t.Fatal(err)
	}
	w.Flush()
	w.Close()

	// We
	rand.Seed(1337)
	t2 := make([]byte, length)
	for idx := range t2 {
		t2[idx] = byte(65 + rand.Intn(8))
	}

	br2 := bytes.NewBuffer(t2)
	var b2 bytes.Buffer
	w2, err := NewWriterLevel(&b2, i)
	if err != nil {
		t.Fatal(err)
	}
	_, err = io.Copy(w2, br2)
	if err != nil {
		t.Fatal(err)
	}
	w2.Flush()
	w2.Close()

	b1b := b1.Bytes()
	b2b := b2.Bytes()

	if bytes.Compare(b1b, b2b) != 0 {
		t.Fatalf("Level %d did not produce deterministric result, len(a) = %d, len(b) = %d", i, len(b1b), len(b2b))
	}
}
Пример #20
0
func (ts *AtomicWriteTestSuite) TestAtomicWriteFileNoOverwriteTmpExisting(c *C) {
	tmpdir := c.MkDir()
	// ensure we always get the same result
	rand.Seed(1)
	expectedRandomness := strutil.MakeRandomString(12)
	// ensure we always get the same result
	rand.Seed(1)

	p := filepath.Join(tmpdir, "foo")
	err := ioutil.WriteFile(p+"."+expectedRandomness, []byte(""), 0644)
	c.Assert(err, IsNil)

	err = AtomicWriteFile(p, []byte(""), 0600, 0)
	c.Assert(err, ErrorMatches, "open .*: file exists")
}
Пример #21
0
// create the space needed by the grid. This is the same for all grid
// implementations. The cellType is expected to be allFloors or allWalls.
func (g *grid) create(width, height int, cellType bool) {
	gridWidth, gridHeight := g.validateSize(width), g.validateSize(height)
	g.cells = make([][]*cell, gridWidth)
	for x, _ := range g.cells {
		g.cells[x] = make([]*cell, gridHeight)
		for y, _ := range g.cells[x] {
			g.cells[x][y] = &cell{x, y, cellType}
		}
	}
	if g.seed == 0 {
		rand.Seed(time.Now().UnixNano())
	} else {
		rand.Seed(g.seed)
	}
}
Пример #22
0
func NewStressLattice(L uint16, dim uint8) *StressLattice {
	sys := new(StressLattice)
	sys.L = L
	sys.dim = dim
	sys.failureStress = 1.0
	sys.residualStress = 0.625
	rand.Seed(time.Now().UTC().UnixNano())
	sys.seed = rand.Int63()
	rand.Seed(sys.seed)
	sys.N = powInteger(L, dim)
	sys.lattice = make([]float32, sys.N, sys.N)
	sys.randomSysInit()
	sys.failedSites = mapset.NewSet()
	return sys
}
Пример #23
0
func TestShuffleNil(t *testing.T) {
	a := sort.StringSlice{"foo", "bar", "baz", "quux"}
	b := make(sort.StringSlice, len(a))
	copy(b, a)

	rand.Seed(42)
	Shuffle(a, nil)
	rand.Seed(42)
	Shuffle(b, nil)
	for i := range a {
		if a[i] != b[i] {
			t.Errorf("mismatch at %d: %q != %q", i, a[i], b[i])
		}
	}
}
Пример #24
0
func main() {
	// Generate a number between 0 and max
	max := 10
	rand.Seed(time.Now().Unix())
	for i := 0; i < 6; i++ {
		fmt.Print(rand.Intn(max), " / ")
	}
	fmt.Println()
	// float
	times := int64(time.Now().Nanosecond())
	rand.Seed(times)
	for i := 0; i < 6; i++ {
		fmt.Printf("%2.2f / ", 100*rand.Float32())
	}
}
Пример #25
0
func TestRetryAttempt(t *testing.T) {
	defer func() {
		timeAfter = time.After
	}()
	timeAfter = func(d time.Duration) <-chan time.Time {
		c := make(chan time.Time, 1)
		c <- time.Now().Add(d)
		return c
	}
	rh := &Helper{
		Backoff:   3,
		Retries:   5,
		Delay:     150 * time.Millisecond,
		MaxDelay:  5 * time.Second,
		MaxJitter: 300 * time.Millisecond,
	}
	expectedDelays := []time.Duration{
		150 * time.Millisecond,
		450 * time.Millisecond,
		1350 * time.Millisecond,
		4050 * time.Millisecond,
		5 * time.Second,
	}
	// Add expected jitter.
	rand.Seed(1)
	for i := range expectedDelays {
		expectedDelays[i] += time.Duration(rand.Int63n(int64(rh.MaxJitter)))
	}
	rand.Seed(1)
	for i, expected := range expectedDelays {
		attempt := i + 1
		actual, ok := rh.RetryAttempt(attempt, 1, nil)
		if !ok {
			t.Errorf("Retry attempt %d failed: %s", attempt, actual)
		}
		if actual != expected {
			t.Errorf("Wrong delay for attempt %d: got %d; want %d", attempt, actual, expected)
		}
	}
	// Exceeds maximum retry attempts; should return immediately.
	delay, ok := rh.RetryAttempt(6, 1, nil)
	if ok {
		t.Errorf("Retry attempt 6 succeeded")
	}
	if delay != 0 {
		t.Errorf("Got delay %s for retry attempt 6", delay)
	}
}
Пример #26
0
func getRandomString() string {
	rand.Seed(time.Now().Unix())

	maxLength := 4
	strLen := rand.Intn(maxLength-1) + 1
	return randStringBytes(strLen)
}
Пример #27
0
/*
if first line from client == LOGIN, reconnect to old bot
if its something else, create new bot
return true on LOGIN, false on any other command so it can be processed further
*/
func (c *Client) registerBot(cmd string, msg string) bool {
	if cmd == "LOGIN" {
		if bot, ok := bots[msg]; ok {
			c.ID = msg
			c.bot = bot
			c.bot.client.toClient = c.toClient
			close(c.join)
			c.join = make(chan string, 50000)
			go c.joinChannels()
			c.bot.clientConnected = true
			Log.Debug("old bot reconnected", msg)
			return true
		}
		c.bot = newBot(c)
		c.ID = msg
		c.bot.ID = msg
		c.bot.clientConnected = true
		bots[msg] = c.bot
		return true
	}
	c.bot = newBot(c)
	// generate random ID
	if c.bot.ID == "" {
		rand.Seed(int64(time.Now().Nanosecond()))
		r := rand.Int31n(123456)
		ID := fmt.Sprintf("%s%d", c.bot.nick, r)
		bots[ID] = c.bot
		c.ID = ID
	}
	return false
}
Пример #28
0
func main() {
	worker, _ := zmq.NewSocket(zmq.REQ)
	defer worker.Close()

	//  Set random identity to make tracing easier
	rand.Seed(time.Now().UnixNano())
	identity := fmt.Sprintf("%04X-%04X", rand.Intn(0x10000), rand.Intn(0x10000))
	worker.SetIdentity(identity)
	worker.Connect("tcp://localhost:5556")

	//  Tell broker we're ready for work
	fmt.Printf("I: (%s) worker ready\n", identity)
	worker.Send(WORKER_READY, 0)

	for cycles := 0; true; {
		msg, err := worker.RecvMessage(0)
		if err != nil {
			break //  Interrupted
		}

		//  Simulate various problems, after a few cycles
		cycles++
		if cycles > 3 && rand.Intn(5) == 0 {
			fmt.Printf("I: (%s) simulating a crash\n", identity)
			break
		} else if cycles > 3 && rand.Intn(5) == 0 {
			fmt.Printf("I: (%s) simulating CPU overload\n", identity)
			time.Sleep(3 * time.Second)
		}

		fmt.Printf("I: (%s) normal reply\n", identity)
		time.Sleep(time.Second) //  Do some heavy work
		worker.SendMessage(msg)
	}
}
Пример #29
0
func Test_Tree(t *testing.T) {
	defer guard_ut(t)

	var tree Tree
	var cnt = 0
	const size = 2000
	var list = new([size]int32)

	rand.Seed(time.Now().Unix())
	for i := 0; i < size; i++ {
		list[i] = int32(rand.Int())
	}

	for i := 0; i < size; i++ {
		if tree.Insert(list[i]) {
			cnt++
		}
	}
	for i := 0; i < size; i++ {
		assert(t, tree.Search(list[i]))
		assert(t, !tree.Insert(list[i]))
	}
	for i := 0; i < size; i++ {
		if tree.Remove(list[i]) {
			cnt--
		}
		assert(t, !tree.Search(list[i]))
	}
	assert(t, tree.IsEmpty() && cnt == 0)
	assert(t, !tree.Remove(0))
}
Пример #30
0
func testMultiplex(t *testing.T, multi func(output SimpleInChannel, inputs ...SimpleOutChannel)) {
	a := NewNativeChannel(None)
	b := NewNativeChannel(None)

	multi(b, a)

	testChannelPair(t, "simple multiplex", a, b)

	a = NewNativeChannel(None)
	inputs := []Channel{
		NewNativeChannel(None),
		NewNativeChannel(None),
		NewNativeChannel(None),
		NewNativeChannel(None),
	}

	multi(a, inputs[0], inputs[1], inputs[2], inputs[3])

	go func() {
		rand.Seed(time.Now().Unix())
		for i := 0; i < 1000; i++ {
			inputs[rand.Intn(len(inputs))].In() <- i
		}
		for i := range inputs {
			inputs[i].Close()
		}
	}()
	for i := 0; i < 1000; i++ {
		val := <-a.Out()
		if i != val.(int) {
			t.Fatal("multiplexing expected", i, "but got", val.(int))
		}
	}
}