本文整理汇总了Golang中rand.Int63函数的典型用法代码示例。如果您正苦于以下问题:Golang Int63函数的具体用法?Golang Int63怎么用?Golang Int63使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Int63函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestKeyBitcountAddAndRemove
func TestKeyBitcountAddAndRemove(t *testing.T) {
const loopsz = 1000
bset := Make()
for i := 0; i < loopsz; i++ {
bset.Add(i)
checkbitcount(bset, "add(sequence)", t)
}
for i := 0; i < loopsz; i++ {
bset.Add(rand.Int63())
checkbitcount(bset, "add(random(spread))", t)
}
for i := 0; i < loopsz; i++ {
bset.Add(rand.Int63n(loopsz * 2))
checkbitcount(bset, "add(random(focussed))", t)
}
for i := 0; i < loopsz; i++ {
bset.Remove(rand.Int63())
checkbitcount(bset, "remove(random(spread))", t)
}
for i := 0; i < loopsz; i++ {
bset.Remove(rand.Int63n(loopsz * 2))
checkbitcount(bset, "remove(random(focussed))", t)
}
for i := 0; i < loopsz; i++ {
bset.Remove(i)
checkbitcount(bset, "remove(sequence)", t)
}
}
示例2: CreatePath
func (p *FileResource) CreatePath(req Request, cxt Context) (string, Request, Context, int, os.Error) {
frc := cxt.(FileResourceContext)
if frc.IsDir() {
newPath := filepath.Join(frc.FullPath(), string(rand.Int63()))
frc2 := NewFileResourceContextWithPath(newPath)
for frc2.Exists() {
newPath = filepath.Join(frc.FullPath(), string(rand.Int63()))
frc2 = NewFileResourceContextWithPath(newPath)
}
frc = frc2
} else if frc.Exists() {
p := frc.FullPath()
dir, tail := path.Split(p)
ext := path.Ext(tail)
basename := tail
uniquify := time.UTC().Format(".20060102.150405")
if len(ext) > 0 {
basename = tail[:len(tail)-len(ext)] + uniquify
frc.SetFullPath(path.Join(dir, basename+ext))
for counter := 1; frc.Exists(); counter++ {
frc.SetFullPath(path.Join(dir, basename+"."+strconv.Itoa(counter)+ext))
}
} else {
basename = basename + uniquify
frc.SetFullPath(path.Join(dir, basename))
for counter := 1; frc.Exists(); counter++ {
frc.SetFullPath(path.Join(dir, basename+"."+strconv.Itoa(counter)))
}
}
}
log.Print("[FileResource]: Will use path ", frc.FullPath())
return frc.FullPath(), req, frc, 0, nil
}
示例3: TestKeyMappingInt64
func TestKeyMappingInt64(t *testing.T) {
for i := 0; i < 10000; i++ {
num := rand.Int63()
if i%5 != 0 {
num = -num
}
key, mask := sbitlocation(num)
if bitcount(mask) != 1 {
t.Errorf("Expected exactly one bit in mask; found %v", bitcount(mask))
}
dcnum := imemberval(key, getbits(mask)[0])
switch tp := dcnum.(type) {
case int64:
if num >= 0 {
t.Errorf("Expected type \"uint64\": got %v", reflect.Typeof(tp))
}
if num != tp {
t.Errorf("Expected type %v: got %v (%v,%v)", num, tp, key, mask)
}
case uint64:
if num < 0 {
t.Errorf("Expected type \"int64\": got %v", reflect.Typeof(tp))
}
if uint64(num) != tp {
t.Errorf("Expected type %v: got %v", num, tp)
}
default:
t.Errorf("Expected type \"(u)int64\": got %v", reflect.Typeof(tp))
}
}
}
示例4: MakeRequest
func (c *AuthClient) MakeRequest(url string, additional_params map[string]string, token_secret string, protected bool) (r *http.Response, finalURL string, err os.Error) {
log.Stderrf("make_request:url:%s:", url);
for k,v := range additional_params {
log.Stderrf("make_request:%s:%s:", k, v);
}
params := make(map[string]string);
params["oauth_consumer_key"] = c.consumer_key;
params["oauth_signature_method"] = "HMAC-SHA1";
params["oauth_timestamp"] = strconv.Itoa64(time.Seconds());
params["oauth_nonce"] = strconv.Itoa64(rand.Int63());
params["oauth_version"] = "1.0";
//if token != "" {
// params["oauth_token"] = token;
//}
//else {
// params["oauth_callback"] = c.callback_url;
//}
// typically: oauth_token, oauth_callback, and/or oauth_verifier
for k,v := range additional_params {
params[k] = v;
}
for k,v := range params {
log.Stderrf("param:%s:%s:", k, v);
}
m := BuildMessage(url, params);
key := c.consumer_secret + "&" + token_secret;
log.Stderrf("key:%s", key);
digest_str := Digest(key, m);
params["oauth_signature"] = digest_str;
log.Stderrf("digest_str:%s", digest_str);
sparams := urllib.Urlencode(params);
log.Stderrf("sparams:%s", sparams);
rurl := strings.Join([]string{url,sparams}, "?");
log.Stderrf("make_request:rurl:%s", rurl);
// TODO: no easy way to add header for Authorization:OAuth when protected...?
return http.Get(rurl);
}
示例5: BenchmarkRollsum
func BenchmarkRollsum(b *testing.B) {
bytesSize := int64(1024 * 1024 * 5)
rs := New()
bits := 0
for i := 0; i < b.N; i++ {
for j := int64(0); j < bytesSize; j++ {
rs.Roll(byte(rand.Int63() & 0xff))
if rs.OnSplit() {
bits = rs.Bits()
}
}
}
b.SetBytes(bytesSize)
_ = bits
}
示例6: K
func (a *Authorizer) K(method, uri string) string {
rr := a.HA1() + ":" + a.nonce
if a.qop == "auth" {
// so we can have predictable test results
if !a.debug {
cni := rand.Int63()
cnib := make([]byte, 8)
binary.LittleEndian.PutUint64(cnib, uint64(cni))
a.cnonce = hex.EncodeToString(cnib)
a.cn += 1
}
rr += fmt.Sprintf(":%08d:%s:%s", a.cn, a.cnonce, a.qop)
}
rr += ":" + a.HA2(method, uri)
return rr
}
示例7: main
func main() {
rand.Seed(time.Nanoseconds())
web.Config.CookieSecret = "7C19QRmwf3mHZ9CPAaPQ0hsWeufKd"
web.Get("/said", func() string { return form })
web.Post("/say", func(ctx *web.Context) string {
uid := strconv.Itoa64(rand.Int63())
ctx.SetSecureCookie("user", uid, 3600)
users[uid] = ctx.Request.Params["said"]
return `<a href="/final">Click Here</a>`
})
web.Get("/final", func(ctx *web.Context) string {
uid, _ := ctx.GetSecureCookie("user")
return "You said " + users[uid]
})
web.Run("0.0.0.0:9999")
}
示例8: putSession
func putSession(ctx *web.Context, key string, value interface{}) {
sessionid, _ := ctx.GetSecureCookie("sessionid")
if sessionid == "" {
sessionid = strconv.Itoa64(rand.Int63())
//ctx.SetSecureCookie("sessionid", sessionid, 3600)
cookie := fmt.Sprintf("%s=%s;path=/;", key, sessionid)
ctx.SetHeader("Set-Cookie", cookie, false)
log.Printf("create session:session id=%v", sessionid)
}
if sessionMap == nil {
sessionMap = map[string]map[string]interface{}{sessionid: nil}
}
if sessionMap[sessionid] == nil {
sessionMap[sessionid] = map[string]interface{}{key: value}
} else {
sessionMap[sessionid][key] = value
}
}
示例9: TestEye64
func TestEye64(t *testing.T) {
fmt.Printf("--> Print some would be addresses for looks:\n")
for i := 0; i < 5; i++ {
fmt.Printf("http://xyz/%s/\n", U64ToEye(uint64(rand.Int63())))
}
fmt.Printf("\n")
fmt.Printf("--> Print 0, 1, 3, ...\n")
for i := 0; i < 2*base+1; i++ {
fmt.Printf("%d = %s\n", i, U64ToEye(uint64(i)))
}
fmt.Printf("\n")
x := int64(-1234)
u1 := uint64(x)
u2 := uint64(1234567890)
u3 := uint64(12345678901234)
u4 := uint64(1<<64 - 1)
fmt.Printf("%d = %s\n", u1, U64ToEye(u1))
fmt.Printf("%d = %s\n", u2, U64ToEye(u2))
fmt.Printf("%d = %s\n", u3, U64ToEye(u3))
fmt.Printf("%d = %s\n", u4, U64ToEye(u4))
f1 := U64ToEye(u1)
f2 := U64ToEye(u2)
if v, err := EyeToU64(f1); v != u1 {
t.Errorf("U->E->U mismatch: expect %d vs. seen %d, err: %s", u1, v, err)
}
if v, err := EyeToU64(f2); v != u2 {
t.Errorf("U->E->U mismatch: expect %d vs. seen %d, err: %s", u2, v, err)
}
/*
e1 := "ab678"
e2 := "ghkp8k"
w1, _ := EyeToU64(e1)
w2, _ := EyeToU64(e2)
if U64ToEye(w1) != e1 {
t.Errorf("E->U->E mismatch: expect %s vs. seen %s", e1, U64ToEye(w1))
}
if U64ToEye(w2) != e2 {
t.Errorf("E->U->E mismatch: expect %s vs. seen %s", e2, U64ToEye(w2))
}
*/
}
示例10: SigninPost
func SigninPost(ctx *web.Context, val string) string {
username := ctx.Params["Username"]
password := ctx.Params["Password"]
user := NewUser()
if db, err := util.GetDB(); err == nil {
if _, err = db.Retrieve("User_"+username, &user); err == nil {
if string(util.PasswordHash(password, user.Password.Version).Hash) == string(user.Password.Hash) {
num := rand.Int63()
key := username + "_" + strconv.Itoa64(num)
util.SetUserKey(key, username)
ctx.SetSecureCookie("UserKey", key, 6000000)
return util.MessagePage("You are now signed in.", ctx)
}
return util.MessagePage("Invalid username and password combination.", ctx)
}
return util.MessagePage("Error: Username may not exist.", ctx)
}
return util.MessagePage("Could not access the database.", ctx)
}
示例11: CreatePermaBlob
func (self *Grapher) CreatePermaBlob(mimeType string) (node AbstractNode, err os.Error) {
// Create the JSON to compute the hash
permaJson := map[string]interface{}{"signer": self.userID, "random": fmt.Sprintf("%v", rand.Int63()), "mimeType": mimeType}
permaBlob, err := json.Marshal(permaJson)
if err != nil {
panic(err.String())
}
permaBlob = append([]byte(`{"type":"permanode",`), permaBlob[1:]...)
log.Printf("Storing perma %v\n", string(permaBlob))
permaBlobRef := newBlobRef(permaBlob)
// Process it
var schema superSchema
schema.Type = "permanode"
schema.Signer = self.userID
schema.Random = fmt.Sprintf("%v", rand.Int63())
schema.MimeType = mimeType
_, node, err = self.handleSchemaBlob(&schema, permaBlobRef)
return
}
示例12: Handle
// Attaches a handler to a page, and returns a link to it.
func (self *AnonymousPageServer) Handle(h http.Handler) string {
return self.a.Schedule(func() interface{} {
// clear cache
for self.items.Len() >= self.limit {
e := self.items.Back()
self.paths[e.Value.(int64)] = nil, false
self.items.Remove(e)
}
// generate a key
var key int64
done := false
for !done {
key = rand.Int63()
if _, ok := self.paths[key]; !ok {
done = true
}
}
// add new item
self.items.PushFront(key)
self.paths[key] = h
// and return the path
return self.prefix + strconv.Itoa64(key)
}).(string)
}
示例13: updateChoice
package main
import (
"github.com/mattn/go-gtk/gdkpixbuf"
"github.com/mattn/go-gtk/gtk"
"os"
"path"
"rand"
"state"
)
//Setting up the universe shamelessly lifted from Kevin's textui example.
var u = state.NewSampleUniverse()
var s = u.Instantiate()
var r = rand.New(rand.NewSource(rand.Int63()))
var log = s.Now()
var choices = s.ChosenTransitions()
func updateChoice(k int, buttons []*gtk.GtkButton, textview *gtk.GtkTextView) {
var end gtk.GtkTextIter
buffer := textview.GetBuffer()
// buffer.GetStartIter(&start)
buffer.GetEndIter(&end)
// buffer.Delete(&start, &end)
choices = s.ChosenTransitions()
if !(k-1 < len(choices)) {
return
}
示例14: GetRequestAuthorizationURL
// GetRequestAuthorizationURL Returns the URL for the visitor to Authorize the Access
func (oc *OAuthConsumer) GetRequestAuthorizationURL() (string, *RequestToken, os.Error) {
// Gather the params
p := Params{}
// Add required OAuth params
p.Add(&Pair{Key: "oauth_version", Value: "1.0"})
p.Add(&Pair{Key: "oauth_timestamp", Value: strconv.Itoa64(time.Seconds())})
p.Add(&Pair{Key: "oauth_consumer_key", Value: oc.ConsumerKey})
p.Add(&Pair{Key: "oauth_callback", Value: oc.CallBackURL})
p.Add(&Pair{Key: "oauth_nonce", Value: strconv.Itoa64(rand.Int63())})
p.Add(&Pair{Key: "oauth_signature_method", Value: "HMAC-SHA1"})
// Sort the collection
sort.Sort(p)
// Generate string of sorted params
sigBaseCol := make([]string, len(p)+len(oc.AdditionalParams))
for i := range p {
sigBaseCol[i] = Encode(p[i].Key) + "=" + Encode(p[i].Value)
}
buf := &bytes.Buffer{}
i := len(p)
for _, kv := range oc.AdditionalParams {
buf.Write([]byte(kv.Key + "=" + Encode(kv.Value) + ""))
sigBaseCol[i] = kv.Key + "=" + Encode(kv.Value)
i++
}
sigBaseStr := "GET&" +
Encode(oc.RequestTokenURL) + "&" +
Encode(strings.Join(sigBaseCol, "&"))
// Generate Composite Signing key
key := Encode(oc.ConsumerSecret) + "&" + "" // token secrect is blank on the Request Token
// Generate Signature
d := oc.digest(key, sigBaseStr)
// Build Auth Header
authHeader := "OAuth "
for i := range p {
authHeader += p[i].Key + "=\"" + Encode(p[i].Value) + "\", "
}
// Add the signature
authHeader += "oauth_signature=\"" + Encode(d) + "\""
headers := map[string]string{
"Content-Type": "text/plain",
"Authorization": authHeader,
}
lAddParams := len(oc.AdditionalParams)
if lAddParams > 0 {
oc.RequestTokenURL += "?" + string(buf.Bytes())
}
r, err := get(oc.RequestTokenURL, headers)
if err != nil {
return "", nil, err
}
if r.StatusCode != 200 {
// OAuth service returned an error
return "", nil, os.NewError("OAuth Service returned an error : " + r.Status)
}
b, _ := ioutil.ReadAll(r.Body)
s := string(b)
rt := &RequestToken{}
if strings.Index(s, "&") == -1 {
// Body is empty
return "", nil, os.NewError("Empty response from server")
}
vals := strings.Split(s, "&", 10)
for i := range vals {
if strings.Index(vals[i], "=") > -1 {
kv := strings.Split(vals[i], "=", 2)
if len(kv) > 0 { // Adds the key even if there's no value.
switch kv[0] {
case "oauth_token":
if len(kv) > 1 {
rt.Token = kv[1]
}
break
case "oauth_token_secret":
if len(kv) > 1 {
rt.Secret = kv[1]
}
break
}
}
//.........这里部分代码省略.........
示例15: oAuthRequest
func (oc *OAuthConsumer) oAuthRequest(url string, fparams Params, at *AccessToken, method string) (r *http.Response, err os.Error) {
// Gather the params
p := Params{}
hp := Params{}
// Add required OAuth params
p.Add(&Pair{Key: "oauth_token", Value: at.Token})
p.Add(&Pair{Key: "oauth_signature_method", Value: "HMAC-SHA1"})
p.Add(&Pair{Key: "oauth_consumer_key", Value: oc.ConsumerKey})
p.Add(&Pair{Key: "oauth_timestamp", Value: strconv.Itoa64(time.Seconds())})
p.Add(&Pair{Key: "oauth_nonce", Value: strconv.Itoa64(rand.Int63())})
p.Add(&Pair{Key: "oauth_version", Value: "1.0"})
// Add the params to the Header collection
for i := range p {
hp.Add(&Pair{Key: p[i].Key, Value: p[i].Value})
}
fparamsStr := ""
// Add any additional params passed
for i := range fparams {
k, v := fparams[i].Key, fparams[i].Value
p.Add(&Pair{Key: k, Value: v})
fparamsStr += k + "=" + Encode(v) + "&"
}
// Sort the collection
sort.Sort(p)
// Generate string of sorted params
sigBaseCol := make([]string, len(p))
for i := range p {
sigBaseCol[i] = Encode(p[i].Key) + "=" + Encode(p[i].Value)
}
sigBaseStr := method + "&" +
Encode(url) + "&" +
Encode(strings.Join(sigBaseCol, "&"))
sigBaseStr = strings.Replace(sigBaseStr, Encode(Encode(at.Token)), Encode(at.Token), 1)
// Generate Composite Signing key
key := Encode(oc.ConsumerSecret) + "&" + at.Secret
// Generate Signature
d := oc.digest(key, sigBaseStr)
// Build Auth Header
authHeader := "OAuth "
for i := range hp {
if strings.Index(hp[i].Key, "oauth") == 0 {
//Add it to the authHeader
authHeader += hp[i].Key + "=\"" + Encode(hp[i].Value) + "\", "
}
}
// Add the signature
authHeader += "oauth_signature=\"" + Encode(d) + "\""
authHeader = strings.Replace(authHeader, Encode(at.Token), at.Token, 1)
// Add Header & Buffer for params
buf := bytes.NewBufferString(fparamsStr)
headers := map[string]string{
"Authorization": authHeader,
}
if method == "GET" {
// return Get response
return get(url+"?"+fparamsStr, headers)
}
// return POSTs response
return post(url, headers, buf)
}