// This example demonstrates creating a script which pays to a bitcoin address. // It also prints the created script hex and uses the DisasmString function to // display the disassembled script. func ExamplePayToAddrScript() { // Parse the address to send the coins to into a btcutil.Address // which is useful to ensure the accuracy of the address and determine // the address type. It is also required for the upcoming call to // PayToAddrScript. addressStr := "12gpXQVcCL2qhTNQgyLVdCFG2Qs2px98nV" address, err := btcutil.DecodeAddress(addressStr, &btcnet.MainNetParams) if err != nil { fmt.Println(err) return } // Create a public key script that pays to the address. script, err := btcscript.PayToAddrScript(address) if err != nil { fmt.Println(err) return } fmt.Printf("Script Hex: %x\n", script) disasm, err := btcscript.DisasmString(script) if err != nil { fmt.Println(err) return } fmt.Println("Script Disassembly:", disasm) // Output: // Script Hex: 76a914128004ff2fcaf13b2b91eb654b1dc2b674f7ec6188ac // Script Disassembly: OP_DUP OP_HASH160 128004ff2fcaf13b2b91eb654b1dc2b674f7ec61 OP_EQUALVERIFY OP_CHECKSIG }
func TestSecureSecretoxKey(t *testing.T) { key1, ok := secretbox.GenerateKey() if !ok { fmt.Println("pwkey: failed to generate test key") t.FailNow() } skey, ok := SecureSecretboxKey(testPass, key1) if !ok { fmt.Println("pwkey: failed to secure secretbox key") t.FailNow() } key, ok := RecoverSecretboxKey(testPass, skey) if !ok { fmt.Println("pwkey: failed to recover box private key") t.FailNow() } if !bytes.Equal(key[:], key1[:]) { fmt.Println("pwkey: recovered key doesn't match original") t.FailNow() } if _, ok = RecoverBoxKey([]byte("Password"), skey); ok { fmt.Println("pwkey: recover should fail with bad password") t.FailNow() } }
func TestVersion(t *testing.T) { v := new(Version) v.Version = uint16(1) v.Timestamp = time.Unix(0, 0) v.IpAddress = net.ParseIP("1.2.3.4") v.Port = uint16(4444) v.UserAgent = "Hello World!" verBytes := v.GetBytes() if len(verBytes) != verLen+12 { fmt.Println("Incorrect Byte Length: ", verBytes) t.Fail() } v2 := new(Version) err := v2.FromBytes(verBytes) if err != nil { fmt.Println("Error Decoding: ", err) t.FailNow() } if v2.Version != 1 || v2.Timestamp != time.Unix(0, 0) || v2.IpAddress.String() != "1.2.3.4" || v2.Port != 4444 || v2.UserAgent != "Hello World!" { fmt.Println("Incorrect decoded version: ", v2) t.Fail() } }
func getUberCost(start locationStruct, end locationStruct) (int, int, float64, string) { uberURL := strings.Replace(uberRequestURL, startLatitude, strconv.FormatFloat(start.Coordinate.Lat, 'f', -1, 64), -1) uberURL = strings.Replace(uberURL, startLongitude, strconv.FormatFloat(start.Coordinate.Lng, 'f', -1, 64), -1) uberURL = strings.Replace(uberURL, endLatitude, strconv.FormatFloat(end.Coordinate.Lat, 'f', -1, 64), -1) uberURL = strings.Replace(uberURL, endLongitude, strconv.FormatFloat(end.Coordinate.Lng, 'f', -1, 64), -1) res, err := http.Get(uberURL) if err != nil { //w.Write([]byte(`{ "error": "Unable to parse data from Google. Error at res, err := http.Get(url) -- line 75"}`)) fmt.Println("Unable to parse data from Google. Error at res, err := http.Get(url) -- line 75") panic(err.Error()) } body, err := ioutil.ReadAll(res.Body) if err != nil { //w.Write([]byte(`{ "error": "Unable to parse data from Google. body, err := ioutil.ReadAll(res.Body) -- line 84"}`)) fmt.Println("Unable to parse data from Google. Error at res, err := http.Get(url) -- line 84") panic(err.Error()) } var uberResult UberResults _ = json.Unmarshal(body, &uberResult) return uberResult.Prices[0].LowEstimate, uberResult.Prices[0].Duration, uberResult.Prices[0].Distance, uberResult.Prices[0].ProductID }
func ExampleLambda_CreateFunction() { svc := lambda.New(session.New()) params := &lambda.CreateFunctionInput{ Code: &lambda.FunctionCode{ // Required S3Bucket: aws.String("S3Bucket"), S3Key: aws.String("S3Key"), S3ObjectVersion: aws.String("S3ObjectVersion"), ZipFile: []byte("PAYLOAD"), }, FunctionName: aws.String("FunctionName"), // Required Handler: aws.String("Handler"), // Required Role: aws.String("RoleArn"), // Required Runtime: aws.String("Runtime"), // Required Description: aws.String("Description"), MemorySize: aws.Int64(1), Publish: aws.Bool(true), Timeout: aws.Int64(1), } resp, err := svc.CreateFunction(params) if err != nil { // Print the error, cast err to awserr.Error to get the Code and // Message from an error. fmt.Println(err.Error()) return } // Pretty-print the response data. fmt.Println(resp) }
func main() { file, err := os.Create("samp.txt") if err != nil { log.Fatal(err) } file.WriteString("This is some random text") file.Close() stream, err := ioutil.ReadFile("samp.txt") if err != nil { log.Fatal(err) } readString := string(stream) fmt.Println(readString) randInt := 5 // randFloat := 10.5 randString := "100" // randString2 := "250.5" fmt.Println(float64(randInt)) newInt, _ := strconv.ParseInt(randString, 0, 64) newFloat, _ := strconv.ParseFloat(randString, 64) fmt.Println(newInt, newFloat) }
func main() { consumer := consumer.New(dopplerAddress, &tls.Config{InsecureSkipVerify: true}, nil) consumer.SetDebugPrinter(ConsoleDebugPrinter{}) messages, err := consumer.RecentLogs(appGuid, authToken) if err != nil { fmt.Printf("===== Error getting recent messages: %v\n", err) } else { fmt.Println("===== Recent logs") for _, msg := range messages { fmt.Println(msg) } } fmt.Println("===== Streaming metrics") msgChan, errorChan := consumer.Stream(appGuid, authToken) go func() { for err := range errorChan { fmt.Fprintf(os.Stderr, "%v\n", err.Error()) } }() for msg := range msgChan { fmt.Printf("%v \n", msg) } }
func main() { var opts struct { ClientID string `long:"client_id" required:"true"` ClientSecret string `long:"client_secret" required:"true"` } _, err := flags.Parse(&opts) if err != nil { log.Fatalln(err) return } config := &oauth2.Config{ ClientID: opts.ClientID, ClientSecret: opts.ClientSecret, RedirectURL: "urn:ietf:wg:oauth:2.0:oob", Scopes: []string{"https://www.googleapis.com/auth/gmail.send"}, Endpoint: oauth2.Endpoint{ AuthURL: "https://accounts.google.com/o/oauth2/auth", TokenURL: "https://accounts.google.com/o/oauth2/token", }, } var code string url := config.AuthCodeURL("") fmt.Println("ブラウザで以下のURLにアクセスし、認証してCodeを取得してください。") fmt.Println(url) fmt.Println("取得したCodeを入力してください") fmt.Scanf("%s\n", &code) token, err := config.Exchange(context.Background(), code) if err != nil { log.Fatalln("Exchange: ", err) } fmt.Println("RefreshToken: ", token.RefreshToken) }
func initDir(args *argContainer) { err := checkDirEmpty(args.cipherdir) if err != nil { fmt.Printf("Invalid cipherdir: %v\n", err) os.Exit(ERREXIT_INIT) } // Create gocryptfs.conf cryptfs.Info.Printf("Choose a password for protecting your files.\n") password := readPasswordTwice(args.extpass) err = cryptfs.CreateConfFile(args.config, password, args.plaintextnames, args.scryptn) if err != nil { fmt.Println(err) os.Exit(ERREXIT_INIT) } if args.diriv && !args.plaintextnames { // Create gocryptfs.diriv in the root dir err = cryptfs.WriteDirIV(args.cipherdir) if err != nil { fmt.Println(err) os.Exit(ERREXIT_INIT) } } cryptfs.Info.Printf(colorGreen + "The filesystem has been created successfully.\n" + colorReset) cryptfs.Info.Printf(colorGrey+"You can now mount it using: %s %s MOUNTPOINT\n"+colorReset, PROGRAM_NAME, args.cipherdir) os.Exit(0) }
// txnCommandFunc executes the "txn" command. func txnCommandFunc(c *cli.Context) { if len(c.Args()) != 0 { panic("unexpected args") } reader := bufio.NewReader(os.Stdin) next := compareState txn := &pb.TxnRequest{} for next != nil { next = next(txn, reader) } conn, err := grpc.Dial("127.0.0.1:12379") if err != nil { panic(err) } etcd := pb.NewEtcdClient(conn) resp, err := etcd.Txn(context.Background(), txn) if err != nil { fmt.Println(err) } if resp.Succeeded { fmt.Println("executed success request list") } else { fmt.Println("executed failure request list") } }
func TestNew(t *testing.T) { config.SetHome(filepath.Join("..", "..", "cmd", "roy", "data")) mi, err := newMIMEInfo() if err != nil { t.Error(err) } tpmap := make(map[string]struct{}) for _, v := range mi { //fmt.Println(v) //if len(v.Magic) > 1 { // fmt.Printf("Multiple magics (%d): %s\n", len(v.Magic), v.MIME) //} for _, c := range v.Magic { for _, d := range c.Matches { tpmap[d.Typ] = struct{}{} if len(d.Mask) > 0 { if d.Typ == "string" { fmt.Println("MAGIC: " + d.Value) } else { fmt.Println("Type: " + d.Typ) } fmt.Println("MASK: " + d.Mask) } } } } /* for k, _ := range tpmap { fmt.Println(k) } */ if len(mi) != 1495 { t.Errorf("expecting %d MIMEInfos, got %d", 1495, len(mi)) } }
func main() { { errChan := make(chan error) go func() { errChan <- nil }() select { case v := <-errChan: fmt.Println("even if nil, it still receives", v) case <-time.After(time.Second): fmt.Println("time-out!") } // even if nil, it still receives <nil> } { errChan := make(chan error) errChan = nil go func() { errChan <- nil }() select { case v := <-errChan: fmt.Println("even if nil, it still receives", v) case <-time.After(time.Second): fmt.Println("time-out!") } // time-out! } }
func main() { if Same(tree.New(1), tree.New(1)) && !Same(tree.New(1), tree.New(2)) { fmt.Println("PASSED") } else { fmt.Println("FAILED") } }
// This example demonstrates extracting information from a standard public key // script. func ExampleExtractPkScriptAddrs() { // Start with a standard pay-to-pubkey-hash script. scriptHex := "76a914128004ff2fcaf13b2b91eb654b1dc2b674f7ec6188ac" script, err := hex.DecodeString(scriptHex) if err != nil { fmt.Println(err) return } // Extract and print details from the script. scriptClass, addresses, reqSigs, err := btcscript.ExtractPkScriptAddrs( script, &btcnet.MainNetParams) if err != nil { fmt.Println(err) return } fmt.Println("Script Class:", scriptClass) fmt.Println("Addresses:", addresses) fmt.Println("Required Signatures:", reqSigs) // Output: // Script Class: pubkeyhash // Addresses: [12gpXQVcCL2qhTNQgyLVdCFG2Qs2px98nV] // Required Signatures: 1 }
func NewWatcher(paths []string) { watcher, err := fsnotify.NewWatcher() if err != nil { log.Fatal(err) } go func() { for { select { case e := <-watcher.Event: fmt.Println(e) go Autobuild() case err := <-watcher.Error: log.Fatal("error:", err) } } }() for _, path := range paths { fmt.Println(path) err = watcher.Watch(path) if err != nil { log.Fatal(err) } } }
func ExampleCloudFormation_EstimateTemplateCost() { svc := cloudformation.New(nil) params := &cloudformation.EstimateTemplateCostInput{ Parameters: []*cloudformation.Parameter{ { // Required ParameterKey: aws.String("ParameterKey"), ParameterValue: aws.String("ParameterValue"), UsePreviousValue: aws.Bool(true), }, // More values... }, TemplateBody: aws.String("TemplateBody"), TemplateURL: aws.String("TemplateURL"), } resp, err := svc.EstimateTemplateCost(params) if err != nil { // Print the error, cast err to awserr.Error to get the Code and // Message from an error. fmt.Println(err.Error()) return } // Pretty-print the response data. fmt.Println(resp) }
func Autobuild() { defer func() { if err := recover(); err != nil { str := "" for i := 1; ; i += 1 { _, file, line, ok := runtime.Caller(i) if !ok { break } str = str + fmt.Sprintf("%v,%v", file, line) } builderror <- str } }() fmt.Println("Autobuild") path, _ := os.Getwd() os.Chdir(path) bcmd := exec.Command("go", "build") var out bytes.Buffer var berr bytes.Buffer bcmd.Stdout = &out bcmd.Stderr = &berr err := bcmd.Run() if err != nil { fmt.Println("run error", err) } if out.String() == "" { Kill() } else { builderror <- berr.String() } }
func main() { // Open device handle, err = pcap.OpenLive(device, snapshot_len, promiscuous, timeout) if err != nil { log.Fatal(err) } defer handle.Close() bpfInstructions := []pcap.BPFInstruction{ {0x20, 0, 0, 0xfffff038}, // ld rand {0x54, 0, 0, 0x00000004}, {0x15, 0, 1, 0x00000004}, {0x06, 0, 0, 0x0000ffff}, {0x06, 0, 0, 0000000000}, } err = handle.SetBPFInstructionFilter(bpfInstructions) if err != nil { log.Fatal(err) } fmt.Println("Capturing ~4th packet (randomly).") packetSource := gopacket.NewPacketSource(handle, handle.LinkType()) for packet := range packetSource.Packets() { // Do something with a packet here. fmt.Println(packet) } }
func ExampleLogAndNotFound() { // Note: The LogAnd* functions all work in a similar fashion. // Create an appengine context (in this case a mock one). c, err := appenginetesting.NewContext(nil) if err != nil { fmt.Println("creating context", err) return } defer c.Close() // Make the request and writer. w := httptest.NewRecorder() r, err := http.NewRequest("GET", "/example/test", nil) if err != nil { fmt.Println("creating request", err) return } // Simulate an error err = fmt.Errorf("WHERE ARE THEY TRYING TO GO? LOL") LogAndNotFound(c, w, r, err) // Print out what would be returned down the pipe. fmt.Println("Response Code:", w.Code) fmt.Println("Response Body:", w.Body.String()) // Output: // Response Code: 404 // Response Body: {"Type":"error","Message":"Not found."} }
func writeInput(conn *net.TCPConn) { fmt.Print("Enter username: "******"username": string(username)}) if err != nil { fmt.Println("It is not property name") return } err = common.WriteMsg(conn, string(str)) if err != nil { log.Println(err) } fmt.Println("Enter text: ") for { text, err := reader.ReadString('\n') if err != nil { log.Fatal(err) } err = common.WriteMsg(conn, username+": "+text) if err != nil { log.Println(err) } } }
func main() { arr := [15]int{23, 3, 21, 5, 78, 52, 46, 73, 46, 73, 62, 77, 43, 48, 25} fmt.Println(arr) smallest := arr[0] var secondSmallest int for _, i := range arr { if i < smallest { smallest = i } } if smallest == arr[0] { secondSmallest = arr[1] } else { secondSmallest = arr[0] } for _, i := range arr { if i == smallest { continue } if i < secondSmallest { secondSmallest = i } } fmt.Println("The second smallest is ", secondSmallest) }
func main() { scanner := bufio.NewScanner(os.Stdin) Loop: for scanner.Scan() { args := strings.SplitN(scanner.Text(), " ", 3) cmd, key, val := parseArgs(args) switch cmd { case "SET": set(key, val) case "UNSET": unset(key) case "GET": get(key) case "NUMEQUALTO", "NEQ": fmt.Println(count[key]) case "BEGIN": begin() case "ROLLBACK": rollback() case "COMMIT": commit() case "END": break Loop case "": continue Loop default: fmt.Println("INVALID COMMAND") } } if err := scanner.Err(); err != nil { fmt.Fprintln(os.Stderr, "I/0 ERROR:", err) } fmt.Println("HAVE A NICE DAY") }
func getTripDetails(w http.ResponseWriter, r *http.Request) { tripID := r.URL.Query().Get(":tripID") fmt.Println(tripID) var result UberResponse c, s := getMongoCollection("trips") defer s.Close() err := c.Find(bson.M{"_id": bson.ObjectIdHex(tripID)}).One(&result) if err != nil { fmt.Println("err = c.Find(bson.M{\"id\": bson.M{\"$oid\":", tripID, "}}).One(&result)") log.Fatal(err) } fmt.Println(result) //Returning the result to user w.WriteHeader(http.StatusOK) w.Header().Set("Content-Type", "application/json") outputJSON, err := json.Marshal(result) if err != nil { w.Write([]byte(`{ "error": "Unable to marshal response. body, outputJSON, err := json.Marshal(t) -- line 110"}`)) panic(err.Error()) } w.Write(outputJSON) }
func main() { flag.Usage = usage flag.Parse() if *f_version { fmt.Println("miniccc", version.Revision, version.Date) fmt.Println(version.Copyright) os.Exit(0) } logSetup() // signal handling sig := make(chan os.Signal, 1024) signal.Notify(sig, os.Interrupt, syscall.SIGTERM) // start a ron client var err error c, err = ron.NewClient(*f_port, *f_parent, *f_serial, *f_path) if err != nil { log.Fatal("creating ron node: %v", err) } log.Debug("starting ron client with UUID: %v", c.UUID) go client() <-sig // terminate }
func NewServer() *Server { s := &Server{ port: common.GetConfInt("server", "port", 8080), maxClients: common.GetConfInt("server", "max_clients", 100000), clientNum: 0, acceptTimeout: common.GetConfSecond("server", "accept_timeout", 60*5), connTimeout: common.GetConfSecond("server", "connection_timeout", 60*3), headerLen: common.GetConfInt("server", "header_length", 10), maxBodyLen: common.GetConfInt("server", "max_body_length", 102400), running: false, heartbeat: time.Now().Unix(), workerNum: common.WorkerNum, currentWorker: -1, logger: common.NewLogger("server"), } if s == nil { fmt.Println("new server failed") return nil } if s.logger == nil { fmt.Println("new server logger failed") return nil } ip, err := common.Conf.String("server", "bind") if err != nil { ip = "" } s.ip = ip return s }
func main() { starttime := time.Now() max := 1500000 set := make(map[int]int) for m := 1; (2*m*m)+(2*m) < max; m++ { for n := m%2 + 1; n < m; n += 2 { if euler.GCD(int64(m), int64(n)) == 1 && (m-n)%2 == 1 { for k := 1; k*((2*m*m)+(2*m*n)) < max; k++ { set[k*((2*m*m)+(2*m*n))]++ } } } } total := 0 for _, sum := range set { if sum == 1 { total++ } } fmt.Println(total) fmt.Println("Elapsed time:", time.Since(starttime)) }
func TestMessage(t *testing.T) { log := make(chan string, 100) priv, x, y := encryption.CreateKey(log) pub := elliptic.Marshal(elliptic.P256(), x, y) address := encryption.GetAddress(log, x, y) msg := new(Message) msg.AddrHash = MakeHash(address) msg.TxidHash = MakeHash([]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}) msg.Timestamp = time.Now().Round(time.Second) msg.Content = *encryption.Encrypt(log, pub, "Hello World!") mBytes := msg.GetBytes() if mBytes == nil { fmt.Println("Error Encoding Message!") t.FailNow() } msg2 := new(Message) msg2.FromBytes(mBytes) if string(msg2.AddrHash.GetBytes()) != string(msg.AddrHash.GetBytes()) || string(msg2.TxidHash.GetBytes()) != string(msg.TxidHash.GetBytes()) || msg2.Timestamp.Unix() != msg.Timestamp.Unix() { fmt.Println("Message Header incorrect: ", msg2) t.FailNow() } if string(encryption.Decrypt(log, priv, &msg.Content)[:12]) != "Hello World!" { fmt.Println("Message content incorrect: ", string(encryption.Decrypt(log, priv, &msg.Content)[:12])) t.Fail() } }
func main() { message := "Hello Go World!" fmt.Println(a) fmt.Println(message) fmt.Println(b) fmt.Println(c) }
func TestObj(t *testing.T) { o := new(Obj) o.HashList = make([]Hash, 2, 2) o.HashList[0] = MakeHash([]byte{'a', 'b', 'c', 'd'}) o.HashList[1] = MakeHash([]byte{'e', 'f', 'g', 'h'}) o2 := new(Obj) oBytes := o.GetBytes() if len(oBytes) != 2*hashLen { fmt.Println("Incorrect Obj Length! ", oBytes) t.FailNow() } err := o2.FromBytes(oBytes) if err != nil { fmt.Println("Error while decoding obj: ", err) t.FailNow() } if string(o2.HashList[0].GetBytes()) != string(o.HashList[0].GetBytes()) || string(o2.HashList[1].GetBytes()) != string(o.HashList[1].GetBytes()) { fmt.Println("Incorrect decoding of obj: ", o2) t.Fail() } }
func main() { var fName string = "Shekhar" var lName = "Gulati" var fullName = fName + " " + lName fmt.Println(fullName) fmt.Println(fName, lName) }