コード例 #1
0
ファイル: knapsack.go プロジェクト: spaghetty/spagh_lib
func (g *GeneticElement) Crossover(m *GeneticElement, f *GeneticElement) {
	var mMask uint64
	var fMask uint64
	if m.initialized && f.initialized {
		guess := rand.Int() % 10
		if guess < 6 { //euristic value for ricombination
			cxIndex := uint(rand.Int() % len(f.tRef))
			mMask = 0xFFFFFFFFFFFFFFFF << cxIndex
			fMask = 0xFFFFFFFFFFFFFFFF ^ mMask
			g.chromosome = (fMask & f.chromosome) | (mMask & m.chromosome)
		} else {
			g.chromosome = f.chromosome
		}
		guess = rand.Int() % 100 // generate a mutation into genoma
		if guess <= 1 {
			mutatedbit := uint(rand.Int() % len(f.tRef))
			mMask = 0x1 << mutatedbit
			g.chromosome = g.chromosome ^ mMask
		}

		g.tRef = f.tRef
		g.target = f.target
		g.value, g.weight = evalutate(g.chromosome, g.tRef)
		g.fitness = generate_fitness(g.weight, g.target)
		g.initialized = true
	}
}
コード例 #2
0
func (nv StrValue) Create() string {
	if nv.size == 128 {
		substrs := [...]string{"ning", "izzy", "ariel", "nick",
			"mazur", "ryan", "hugg", "yankeesfan", "volt", "runs",
			"with", "scissors", "blue", "awesome", "weak", "sauce",
			"chicken", "strength", "vikram", "bobbi", "jarr", "bungee",
			"banjo", "arrow", "trinity", "coffee", "pvc"}
		cnt := (rand.Int() % 10) + 1
		vals := make([]string, cnt)

		for i := 0; i < cnt; i++ {
			vals[i] = substrs[rand.Int()%len(substrs)]
		}
		return strings.Join(vals, "")
	} else if nv.size == 4 {
		substrs := [...]string{"a", "b", "c", "d"}
		cnt := 4
		vals := make([]string, cnt)

		for i := 0; i < cnt; i++ {
			vals[i] = substrs[rand.Int()%len(substrs)]
		}
		return strings.Join(vals, "")
	}
	panic("Invalid string size.")
}
コード例 #3
0
ファイル: genetic.go プロジェクト: spaghetty/spagh_lib
func (g *GeneticElement) Crossover(m *GeneticElement, f *GeneticElement) {
	var mMask uint64
	var fMask uint64
	if m.initialized && f.initialized {
		guess := rand.Int() % 10
		if guess < 6 { //euristic value for ricombination
			cxIndex := uint(rand.Int() % 36)
			mMask = 0xFFFFFFFFFFFFFFFF << cxIndex
			fMask = 0xFFFFFFFFFFFFFFFF ^ mMask
			g.chromosome = (fMask & f.chromosome) | (mMask & m.chromosome)
		} else {
			g.chromosome = f.chromosome
		}
		guess = rand.Int() % 100 // generate a mutation into genoma
		if guess <= 1 {
			mutatedbit := uint(rand.Int() % 36)
			mMask = 0x1 << mutatedbit
			g.chromosome = g.chromosome ^ mMask
		}

		g.maptable = f.maptable
		g.computeFitness()
		g.initialized = true
	}
}
コード例 #4
0
ファイル: mallocrand.go プロジェクト: ivanwyc/google-go
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 {
		//		panicln("find", siz, obj, ref, ok);
		//	}
		blocks[b].base = base
		blocks[b].siz = siz
		allocated += uint64(siz)
		//	println("Alloc", siz, base);
		memset(base, 0xbb, siz)
		bigger()
	}
}
コード例 #5
0
ファイル: main.go プロジェクト: shxiao/algo
func randInts() []int {
	r := rand.Int() % 30
	d := make([]int, r)
	for i := 0; i < r; i++ {
		d[i] = rand.Int() % 30
	}
	return d
}
コード例 #6
0
func createSchema() ([]NValue, []string) {
	schema := make([]NValue, (rand.Int()%maxIdxColumns)+1)
	abbrev := make([]string, len(schema))
	for ii := 0; ii < len(schema); ii++ {
		schemaType := voltIdxTypes[rand.Int()%len(voltIdxTypes)]
		schema[ii] = nvalueFactory(schemaType)
		abbrev[ii] = schemaType
	}
	return schema, abbrev
}
コード例 #7
0
ファイル: main.go プロジェクト: jbeshir/OddComm
func addHorde() {
	src := rand.NewSource(time.Nanoseconds())
	rng := rand.New(src)
	horde := make([]*core.User, 20000)

	// Add the horde.
	for i, _ := range horde {
		data := make([]core.DataChange, 4)
		data[0].Name, data[0].Data = "ip", fmt.Sprintf("%d.%d.%d.%d", rng.Int()%255, rng.Int()%255, rng.Int()%255, rng.Int()%255)
		data[1].Name, data[1].Data = "hostname", fmt.Sprintf("%d.Horde.FakeUsers.PsuedoUserUnion.org", rng.Int()%1000000)
		data[2].Name, data[2].Data = "ident", fmt.Sprintf("horde-%d", rng.Int()%1000000)
		data[3].Name, data[3].Data = "account", fmt.Sprintf("horde-%d", rng.Int()%1000000)

		horde[i] = core.NewUser("oddcomm/modules/dev/horde", nil, true, "", data)
		horde[i].SetNick(me, fmt.Sprintf("horde-%d", rng.Int()%1000000), -1)
		horde[i].PermitRegistration(me)
	}

	// Make a huge channel containing the entire horde.
	core.GetChannel("", "huge").Join(me, horde)

	// Make 100 channels containing roughly a twentieth of the horde each.
	// Each horde user is in an average of roughly five.
	for i := 0; i < 100; i++ {
		joiners := make([]*core.User, len(horde)/20)
		for i, _ := range joiners {
			joiners[i] = horde[rand.Int()%len(horde)]
		}
		name := fmt.Sprintf("big_%d", i)
		core.GetChannel("", name).Join(me, joiners)
	}

	// Make 2000 channels containing roughly 1/400th of the horde each.
	// Each horde user is in an average of roughly five.
	for i := 0; i < 2000; i++ {
		joiners := make([]*core.User, len(horde)/400)
		for i, _ := range joiners {
			joiners[i] = horde[rand.Int()%len(horde)]
		}
		name := fmt.Sprintf("medium_%d", i)
		core.GetChannel("", name).Join(me, joiners)
	}

	// Make horde*2 channels containing roughly four of the horde each.
	// Each horde user is in an average of roughly eight.
	for i := 0; i < len(horde)*2; i++ {
		joiners := make([]*core.User, 4)
		for i, _ := range joiners {
			joiners[i] = horde[rand.Int()%len(horde)]
		}
		name := fmt.Sprintf("small_%d", i)
		core.GetChannel("", name).Join(me, joiners)
	}
}
コード例 #8
0
ファイル: knapsack.go プロジェクト: spaghetty/spagh_lib
func (p *GeneticElement) InitRand(e []Element, target int) {
	bitNum := rand.Int() % len(e)
	p.chromosome = uint64(0)
	for i := 0; i <= bitNum; i++ {
		tmp := uint64(1) << uint(rand.Int()%len(e))
		p.chromosome = p.chromosome | tmp
	}
	p.tRef = e[0:]
	p.target = target
	p.value, p.weight = evalutate(p.chromosome, e[0:])
	p.fitness = generate_fitness(p.weight, target)
	p.initialized = true
}
コード例 #9
0
func TestKeyValue(t *testing.T) {
	look_up_table := Make(true)
	for i := 0; i < 2000; i++ {
		look_up_table.Insert(key_value{rand.Int(), rand.Int()})
	}
	for kvi := range look_up_table.Iter(IN_ORDER) {
		kv := kvi.(key_value)
		val, found := look_up_table.Find(key_value{kv.key, 0})
		if !found || kv.value != val.(key_value).value {
			t.Errorf("Bad value: %v : %v != %v\n", kv, kv.value, val.(key_value).value)
		}
	}
}
コード例 #10
0
func sign() int {
	sign := rand.Int() % 2
	if sign == 0 {
		return 1
	}
	return -1
}
コード例 #11
0
ファイル: mysql_test.go プロジェクト: ipeet/camlistore
func insert1000Records(t *testing.T, db *Client) map[uint64][]string {
	stmt, err := db.InitStmt()
	if err != nil {
		t.Fatalf("InitStmt: %v", err)
	}

	err = stmt.Prepare(INSERT_SIMPLE_STMT)
	if err != nil {
		t.Logf("Prepare insert: %v", err)
	}

	t.Logf("Insert 1000 records")
	rowMap := make(map[uint64][]string)
	for i := 0; i < 1000; i++ {
		num, str1, str2 := rand.Int(), randString(32), randString(128)
		err = stmt.BindParams(num, str1, str2)
		if err != nil {
			t.Fatalf("Error %s", err)
		}
		err = stmt.Execute()
		if err != nil {
			t.Fatalf("Error %s", err)
		}
		row := []string{fmt.Sprintf("%d", num), str1, str2}
		rowMap[stmt.LastInsertId] = row
	}
	return rowMap
}
コード例 #12
0
ファイル: config.go プロジェクト: paulbellamy/skynet
// This is simple today - it returns the first listed service that matches the request
// Load balancing needs to be applied here somewhere.
func GetRandomClientByProvides(provides string) (*rpc.Client, os.Error) {
	var providesList = make([]*Service, 0)

	var newClient *rpc.Client
	var err os.Error

	for _, v := range NS.Services {
		if v != nil {
			if v.Provides == provides {
				providesList = append(providesList, v)
			}

		}
	}

	if len(providesList) > 0 {
		random := rand.Int() % len(providesList)
		s := providesList[random]

		portString := fmt.Sprintf("%s:%d", s.IPAddress, s.Port)
		newClient, err = rpc.DialHTTP("tcp", portString)
		if err != nil {
			LogError(WARN, fmt.Sprintf("Found %d Clients to service %s request.", len(providesList), provides))
			return nil, NewError(NO_CLIENT_PROVIDES_SERVICE, provides)
		}

	} else {
		return nil, NewError(NO_CLIENT_PROVIDES_SERVICE, provides)
	}
	return newClient, nil
}
コード例 #13
0
ファイル: mysql_test.go プロジェクト: eden/mysqlgo
func findRand(t *testing.T, conn *db.Connection, ch chan *vector.Vector) {
	stmt, sErr := conn.Prepare(
		"SELECT * FROM t WHERE i != ? ORDER BY RAND()")
	if sErr != nil {
		error(t, sErr, "Couldn't prepare")
	}

	rs, cErr := conn.Execute(stmt, rand.Int())
	if cErr != nil {
		error(t, cErr, "Couldn't select")
	}

	vout := new(vector.Vector)
	for res := range rs.Iter() {
		if res.Error() != nil {
			error(t, res.Error(), "Couldn't fetch")
		}
		vout.Push(res.Data())
	}

	if vout.Len() != len(tableT) {
		t.Error("Invalid length")
	}

	stmt.Close()
	ch <- vout
}
コード例 #14
0
func serveTestFiles(t *testing.T) (l net.Listener, err os.Error) {
	foundValidPort := false
	var port_str string
	for !foundValidPort {
		port := (rand.Int() & 0x7FFF) + 0x08000
		port_str = strconv.Itoa(port)
		addr, err := net.ResolveTCPAddr("127.0.0.1:" + port_str)
		if err != nil {
			t.Error("Create TCP Address: ", err.String())
			return nil, err
		}
		l, err = net.ListenTCP("tcp4", addr)
		if err != nil {
			if err == os.EADDRINUSE || strings.LastIndex(err.String(), os.EADDRINUSE.String()) != -1 {
				continue
			}
			t.Error("Unable to listen on TCP port: ", err.String())
			return l, err
		}
		foundValidPort = true
	}
	OverrideRapleafHostPort("127.0.0.1", port_str)
	go http.Serve(l, http.HandlerFunc(ServeTestHTTP))
	return l, err
}
コード例 #15
0
ファイル: conn.go プロジェクト: mloughran/doozer
// DialUri connects to one of the doozer servers given in `uri`. If `uri`
// contains a secret key, then DialUri will call `Access` with the secret.
func DialUri(uri string) (*Conn, os.Error) {
	if !strings.HasPrefix(uri, uriPrefix) {
		return nil, ErrInvalidUri
	}

	q := uri[len(uriPrefix):]
	p, err := http.ParseQuery(q)
	if err != nil {
		return nil, err
	}

	addrs, ok := p["ca"]
	if !ok {
		return nil, ErrInvalidUri
	}

	c, err := Dial(addrs[rand.Int()%len(addrs)])
	if err != nil {
		return nil, err
	}

	secret, ok := p["sk"]
	if ok {
		err = c.Access(secret[0])
		if err != nil {
			c.Close()
			return nil, err
		}
	}

	return c, nil
}
コード例 #16
0
ファイル: gntp.go プロジェクト: andradeandrey/go-gntp
func (c *client) send(method string, stm string) ([]byte, os.Error) {
	conn, err := net.Dial("tcp", "", c.server)
	if err != nil {
		return nil, err
	}
	if len(c.password) > 0 {
		salt := make([]byte, 8)
		for n := 0; n < len(salt); n++ {
			salt[n] = uint8(rand.Int() % 256)
		}
		d := md5.New()
		d.Write([]byte(c.password))
		d.Write(salt)
		hash := d.Sum()
		d.Reset()
		d.Write(hash)
		s := fmt.Sprintf("%x.%x", d.Sum(), salt)
		conn.Write([]byte(
			"GNTP/1.0 " + method + " NONE MD5:" + s + "\r\n" + stm + "\r\n"))
	} else {
		conn.Write([]byte(
			"GNTP/1.0 " + method + " NONE\r\n" + stm + "\r\n"))
	}
	return ioutil.ReadAll(conn)
}
コード例 #17
0
ファイル: bench_test.go プロジェクト: xushiwei/timsort
func makeVector(size int, shape string) vector.Vector {

	var v vector.Vector

	switch shape {

	case "xor":
		for i := 0; i < size; i++ {
			v.Push(&record{0xff & (i ^ 0xab), i})
		}

	case "sorted":
		for i := 0; i < size; i++ {
			v.Push(&record{i, i})
		}

	case "revsorted":
		for i := 0; i < size; i++ {
			v.Push(&record{size - i, i})
		}

	case "random":
		rand.Seed(1)

		for i := 0; i < size; i++ {
			v.Push(&record{rand.Int(), i})
		}

	default:
		panic(shape)
	}

	return v
}
コード例 #18
0
ファイル: registry.go プロジェクト: andradeandrey/skynet
// This is simple today - it returns the first listed service that matches the request
// Load balancing needs to be applied here somewhere.
func GetRandomClientByService(classname string) (*rpc.Client, os.Error) {
	var newClient *rpc.Client
	var err os.Error
	serviceList := GetAllServiceProviders(classname)

	if len(serviceList) > 0 {
		chosen := rand.Int() % len(serviceList)
		s := serviceList[chosen]

		hostString := fmt.Sprintf("%s:%d", s.IPAddress, s.Port)
		protocol := strings.ToLower(s.Protocol) // to be safe
		switch protocol {
		default:
			newClient, err = rpc.DialHTTP("tcp", hostString)
		case "json":
			newClient, err = jsonrpc.Dial("tcp", hostString)
		}

		if err != nil {
			LogWarn(fmt.Sprintf("Found %d nodes to provide service %s requested on %s, but failed to connect.",
				len(serviceList), classname, hostString))
			return nil, NewError(NO_CLIENT_PROVIDES_SERVICE, classname)
		}

	} else {
		LogWarn(fmt.Sprintf("Found no node to provide service %s.", classname))
		return nil, NewError(NO_CLIENT_PROVIDES_SERVICE, classname)
	}
	return newClient, nil
}
コード例 #19
0
ファイル: main.go プロジェクト: taysom/tau
func rndName(n int) string {
	b := make([]byte, n)
	for i := 0; i < n; i++ {
		b[i] = byte('a' + rand.Int()%26)
	}
	return string(b)
}
コード例 #20
0
ファイル: writer_test.go プロジェクト: Quantumboost/gcc
func TestWriter(t *testing.T) {
	largeData := make([]byte, 1<<17)
	for i := range largeData {
		largeData[i] = byte(rand.Int())
	}
	writeTests[1].Data = largeData
	defer func() {
		writeTests[1].Data = nil
	}()

	// write a zip file
	buf := new(bytes.Buffer)
	w := NewWriter(buf)

	for _, wt := range writeTests {
		testCreate(t, w, &wt)
	}

	if err := w.Close(); err != nil {
		t.Fatal(err)
	}

	// read it back
	r, err := NewReader(sliceReaderAt(buf.Bytes()), int64(buf.Len()))
	if err != nil {
		t.Fatal(err)
	}
	for i, wt := range writeTests {
		testReadFile(t, r.File[i], &wt)
	}
}
コード例 #21
0
ファイル: rect_test.go プロジェクト: mostafah/pdf.go
func TestRect(t *testing.T) {
	const n = 10
	// testing with float64
	for i := 0; i < n; i++ {
		llx, lly := rand.NormFloat64(), rand.NormFloat64()
		urx, ury := rand.NormFloat64(), rand.NormFloat64()
		r := newRect(llx, lly, urx, ury)
		a := []float64{llx, lly, urx, ury}
		if bytes.Compare(r.output(), output(a)) != 0 {
			t.Errorf("newRect(%f, %f, %f, %f) doesn't work",
				llx, lly, urx, ury)
		}
	}
	// testing with int
	for i := 0; i < n; i++ {
		// random function that returns both positive and negative
		rnd := func() int {
			sign := 1
			if rand.Intn(2) == 0 {
				sign = -1
			}
			return sign * rand.Int()
		}

		llx, lly, urx, ury := rnd(), rnd(), rnd(), rnd()
		r := newRectInt(llx, lly, urx, ury)
		a := []int{llx, lly, urx, ury}
		if bytes.Compare(r.output(), output(a)) != 0 {
			t.Errorf("newRect(%d, %d, %d, %d) doesn't work",
				llx, lly, urx, ury)
		}
	}
}
コード例 #22
0
ファイル: queue.go プロジェクト: c141charlie/ds
func main() {
	runtime.GOMAXPROCS(2) //Dual core
	args := flag.Args()

	if len(args) < 4 {
		fmt.Println("Usage: CallGenerator <numberOfAgents> <numberOfCalls> <maxCallDuration> <maxCallInterval>")
		return
	}
	num_agents, _ := strconv.Atoi(args[0])
	num_calls, _ := strconv.Atoi(args[1])
	max_dur, _ := strconv.Atoi(args[2])
	max_int, _ := strconv.Atoi(args[3])

	queue := make(chan *Call, 10000)
	clock_in := make(chan bool)
	clock_out := make(chan bool)

	call_center := &CallCenter{num_agents, queue, clock_in, clock_out}

	begin := time.Nanoseconds()

	call_center.Open()

	for i := 0; i < num_calls; i++ {
		time.Sleep(int64(max_int))
		queue <- &Call{i, rand.Int() * max_dur, time.Nanoseconds()}
	}

	call_center.Close()

	end := time.Nanoseconds()

	fmt.Printf("Simulation elapsed time: %d seconds\n", (end-begin)/1000000000)
}
コード例 #23
0
ファイル: server.go プロジェクト: welterde/gohttptun
func genKey() string {
	key := make([]byte, keyLen)
	for i := 0; i < keyLen; i++ {
		key[i] = byte(rand.Int())
	}
	return string(key)
}
コード例 #24
0
func root(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	clientTemplate := template.Must(template.ParseFile("client.html"))
	token_value := strconv.Itoa(rand.Int())
	token_key, _ := channel.Create(c, token_value)
	clientTemplate.Execute(w, token_key)
	map_clients[token_key] = token_value
}
コード例 #25
0
ファイル: raptordb_test.go プロジェクト: QBui/raptordb
// Test rand module
func TestRandModule(t *testing.T) {
	rand.Seed(1234567890)
	var p int
	for i := 0; i < 10; i++ {
		p = rand.Int()
		println("Rand.Int() returns ", p)
	}
}
コード例 #26
0
ファイル: set_test.go プロジェクト: tensorpudding/set
func randomizeSet(n int) *IntTreap {
	s := Init([]int{})
	for i := 0; i < n; i++ {
		p := rand.Int()
		s = s.Insert(p)
	}
	return s
}
コード例 #27
0
ファイル: set.go プロジェクト: tensorpudding/set
func NewIntLeaf(x int) *IntTreap {
	l := new(IntTreap)
	l.x = x
	l.p = rand.Int()
	l.left = nil
	l.right = nil
	return l
}
コード例 #28
0
func (nv DecValue) Create() string {
	vals := make([]string, 3)
	lhs := rand.Int() * sign()
	vals[0] = fmt.Sprint(lhs)
	vals[1] = "."
	vals[2] = fmt.Sprint(rand.Intn(99999999))
	return strings.Join(vals, "")
}
コード例 #29
0
func randomize(x [][]int, row, col int) {
	for i := 0; i < row; i++ {
		//x[i]=make([]int,col)
		for j := 0; j < col; j++ {
			x[i][j] = rand.Int() % 10
		}
	}
}
コード例 #30
0
ファイル: db.go プロジェクト: fedgrant/tonika
func (db *buttress) UnusedSlot() int {
	for {
		s := rand.Int()
		if _, ok := db.recs[s]; !ok {
			return s
		}
	}
	panic("unreach")
}