text
stringlengths
11
4.05M
package storage import ( "context" "errors" "io/ioutil" "log" "os" "path" "time" "github.com/sirupsen/logrus" "github.com/minio/minio-go/v7" "github.com/minio/minio-go/v7/pkg/credentials" ) type MinIO struct { *minio.Client root string } func newMinIO(addr string) (*MinIO, error) { s3Client, err := mi...
package pool import ( "sync" . "github.com/rainmyy/easyDB/library/res" ) const ( defaultRuntineNumber = 10 defailtTotal = 10 ) type Pool struct { //mutex sync.WaitGroup RuntineNumber int Total int taskQuery chan *Queue taskResult chan map[string]*Reponse taskResponse map[st...
package logpusher import ( "bytes" "crypto/md5" "encoding/base64" "encoding/json" "fmt" "io/ioutil" "net/http" "time" ) const ( // PostActionURL API endpoint of logpusher PostActionURL = "https://api.logpusher.com/api/agent/savelog" ) // PushResult model type PushResult struct { Message string `json:"mes...
package main import ( "sort" "fmt" "runtime/pprof" "flag" "os" "runtime" "log" ) var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to `file`") var memprofile = flag.String("memprofile", "", "write memory profile to `file`") func threeSum(nums []int) [][]int { ret := make([][]int, 0) retu...
/* * Copyright (c) 2018 Juniper Networks, Inc. All rights reserved. * * file: request.go * details: Deals with the validity of the request or any other processing of the request before * passing to the actual handler * */ package request import ( "encoding/json" "net/http" res "github.com/Junipe...
package sdk import ( "context" "net/http" rm "github.com/brigadecore/brigade/sdk/v3/internal/restmachinery" "github.com/brigadecore/brigade/sdk/v3/restmachinery" ) // AuthnClient is the root of a tree of more specialized API clients for dealing // with identity and authentication. type AuthnClient interface { /...
package user import ( "fmt" "github.com/10gen/realm-cli/internal/cli" "github.com/10gen/realm-cli/internal/cli/user" "github.com/10gen/realm-cli/internal/terminal" "github.com/10gen/realm-cli/internal/utils/flags" ) // CommandMetaCreate is the command meta for the `user create` command var CommandMetaCreate = c...
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package main import ( "errors" "fmt" "os" "time" "github.com/luci/luci-go/client/archiver" "github.com/luci/luci-go/client/internal/common" "gith...
package bgControllers import ( "github.com/astaxie/beego" "strconv" "GiantTech/models" "GiantTech/controllers/tools" ) type BgProjectFileController struct { beego.Controller } func (this *BgProjectFileController) Prepare() { s := this.StartSession() username = s.Get("login") beego.Informational(username) if...
package resources import "github.com/go-redis/redis" func NewRedisResource(config *RedisConfig) (ResourceInterface, error) { return &RedisResource{config: config}, nil } type RedisResource struct { config *RedisConfig client *redis.Client } type RedisConfig struct { Address string } func (this *RedisResource) ...
package dddshop import ( "fmt" "github.com/sueken5/golang-ddd/pkg/dddshop/interfaces/http" ) func Execute() error { //di... srv := http.NewServer() if err := srv.Run(); err != nil { fmt.Errorf("dddshop exec err: %v", err) } return nil }
package lambdacalculus import ( "testing" ) func TestPair_First(t *testing.T) { res := Tuple2Struct(1)(2)(First) if res != 1 { t.Errorf("First of pair(1)(2) should be 1 instead is %v", res) } } func TestPair_Second(t *testing.T) { res := Tuple2Struct(1)(2)(Second) if res != 2 { t.Errorf("Second of pair(1)(2...
package student type student struct{ Name string Age int score float64 } // 写一个方法,传入数据,然后返回一个student func NewStu(n string,a int,s float64) *student{ return &student{ Name : n, Age : a, score : s, // 这里score首字母小写,在其他包就没法正常用,处理方式是给他单独一个方法 } } func (stu *student)GetScore() float64{ return stu.s...
package main import ( "bufio" "encoding/json" "fmt" "os" "strings" ) func main() { var name string fmt.Print("Input the name: ") fmt.Scanln(&name) fmt.Print("Input the address: ") inputReader := bufio.NewReader(os.Stdin) address, _ := inputReader.ReadString('\n') address = strings.TrimSuffix(address, "\r...
package deploy import ( "github.com/devspace-cloud/devspace/cmd" "github.com/devspace-cloud/devspace/cmd/flags" "github.com/devspace-cloud/devspace/e2e/utils" "github.com/devspace-cloud/devspace/pkg/util/log" "github.com/pkg/errors" ) //Test 1 - default //1. deploy (without profile & var) //2. deploy --force-bui...
/** * @Author xieed * @Description 版本号工具类 * @Date 2020/9/24 19:33 **/ package utils import "strings" type Version struct { versions []int } var defaultVersionSeparator = "." // 版本号自增 func IncrementVersion(versionStr string) (res string) { versionArray := ToIntArrayBySeparator(versionStr, defaultVersionSepara...
/* * Copyright 2017 StreamSets Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed...
package main import ( "bufio" "encoding/csv" "fmt" "io" "os" "path" "path/filepath" "strconv" "strings" ) const ( TIME_IDX int = 7 PERIOD_IDX int = 8 PLAYER_IDX int = 13 HOME_DESC_IDX int = 5 AWAY_DESC_IDX int = 32 QUARTER_TIME_SEC int = 12 * 60 ) type Season struct { Id ...
package gonigsberg import ( "os" "errors" "bufio" "strings" "strconv" "stringSet" ) /* Immutable graph */ type ImmutableGraph struct { adj [][]int nodes map[string]int idxToID []string } /* Creates a new Immutable graph from an edge list where edge list has the format: # comment nodeid nodei...
package main import ( "github.com/gin-gonic/gin" "github.com/kataras/iris" "github.com/iris-contrib/template/pug" _ "github.com/youkyll/goat/app/endpoint" "github.com/youkyll/goat/app/view" "github.com/youkyll/goat/app/endpoint/api" "os" ) func main() { iris.UseTemplate(pug.New()).Directory("clients/templates...
package main import ( "log" "sync" "time" ) const ( epoch = int64(1577808000000) // 设置起始时间(时间戳/毫秒):2020-01-01 00:00:00,有效期69年 timestampBits = uint(41) // 时间戳占用位数 datacenteridBits = uint(2) // ...
package main import ( "fmt" "net/http" ) func httpSuccess(w http.ResponseWriter, req *http.Request) { fmt.Fprintf(w, "{ \"code\": 200 }") } func httpAPIError(w http.ResponseWriter, req *http.Request) { fmt.Fprintf(w, "{\"code\":401, \"message\": \"Invalid API key.\"}") } func httpWrongCity(w http.ResponseWriter...
package main import ( "flag" "fmt" "github.com/IMQS/updater/updater" "os" ) const usageTxt = `commands: buildmanifest <dir> Update manifest in <dir> run Run in foreground (in console) service Run as a Windows Service download Check for new content, and download ...
package router import ( "github.com/bqxtt/book_online/api/auth" "github.com/bqxtt/book_online/api/handler" "github.com/bqxtt/book_online/api/router/middleware" "github.com/gin-gonic/gin" swaggerFiles "github.com/swaggo/files" ginSwagger "github.com/swaggo/gin-swagger" "log" "net/http" ) func Init() { router ...
// Copyright 2021 Google LLC. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applica...
package util import ( "encoding/json" "log" "net" "net/rpc" "os" "github.com/fatih/color" ) // Contains - - func Contains(vals []string, aVal string) bool { for _, v := range vals { if v == aVal { return true } } return false } // Remove - - func Remove(vals []string, aVal string) []string { newVal...
package main import ( "github.com/adampresley/webframework/server" "github.com/gobucket/gobucketserver/application" ) func setupMiddleware(httpListener *server.HTTPListener, app *application.Application) { httpListener. AddMiddleware(app.Logger). AddMiddleware(app.AccessControl). AddMiddleware(app.OptionsHan...
package nodenormal import ( "fmt" "time" "github.com/fananchong/go-xserver/common" "github.com/fananchong/go-xserver/common/utils" nodecommon "github.com/fananchong/go-xserver/internal/components/node/common" "github.com/fananchong/go-xserver/internal/db" "github.com/fananchong/go-xserver/internal/protocol" "...
package manager import( "download" "stockdb" "parser" "handler" "config" //"fmt" "os" //"encoding/json" ) type StockListManager struct { config config.StockListConfig download *download.StockDownloader db *stockdb.StockListDB } func (s *StockListManager) Init() { const...
package main import ( "context" "goimpulse/conf" "net/http" "goimpulse/lib" "goimpulse/sender" "time" "fmt" "io/ioutil" "github.com/coreos/etcd/client" "github.com/facebookgo/grace/gracehttp" "github.com/labstack/echo" log "github.com/sirupsen/logrus" ) var masterHost string func main() { masterHost...
package main import ( "flag" "log" "runtime" nc "github.com/gered/nats-cli" "github.com/nats-io/nats" ) func usage() { log.Fatalf("nats-sub [-s server] [-ts] [-tls] [-tlscert CERT_FILE] [-tlskey KEY_FILE] [-tlscacert CA_FILE] [-tlsverify] <subject>") } func main() { log.SetFlags(0) var url = flag.String("...
package chapter4 import ( "fmt"; "strconv" "strings" "unicode/utf8" ) //注意 单个字符仍与C++一样使用单引号 //字符串是UTF-8字符的一个序列 //当字符是ASCII码时占用一个字节,其他字符根据需要占用2-4个字节 //UTF-8是被广泛使用的编码格式,包括xml JSON //与C++ JAVA Python不同,Java始终使用2个字节 //GO不仅减少内存与硬盘的空间占用,并且不需要对UTF-8进行编码解码 // //字符串是一种值类型,且值不可变,即创建某个文本后无法再次修改这个文本的内容 //这与Java有点类似,字符串是字节的数组 ...
/* Copyright 2021 The KodeRover Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, s...
package pipeline import ( "log" "testing" ) func TestPipelineProcess(t *testing.T) { inFunc := func(proc PipelineProcess, msg PipelineMessage) PipelineMessage { val, ok := msg.Content.(int) if ok { msg.Content = val + 1 } else { t.Error("Message Content is not int") } return msg } outChannel := ...
package card type Card struct { CardType int //牌类型 CardNo int //牌编号 CardId int //牌唯一标识符 } //是否同一类型的牌 func (card *Card) SameCardTypeAs(other *Card) bool { if other == nil || card == nil { return false } return other.CardType == card.CardType } func (card *Card) SameCardNoAs(other *Card) bool { if other =...
package main import ( "context" "log" "net" "google.golang.org/grpc" "github.com/GreatLaboratory/go-grpc-example/data" postpb "github.com/GreatLaboratory/go-grpc-example/protos/v1/post" userpb "github.com/GreatLaboratory/go-grpc-example/protos/v1/user" user_client "github.com/GreatLaboratory/go-grpc-example/...
// Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package logtail import ( "context" "testing" "time" ) func TestFastShutdown(t *testing.T) { ctx, cancel := context.WithCancel(context.Backgrou...
package payment import "context" type ReceiptRepository interface { Put(ctx context.Context, src *Receipt) error }
package dict import ( "encoding/json" "errors" "fmt" "strconv" "strings" "github.com/Kretech/xgo/encoding" ) var ( ErrNotDict = errors.New(`parsed object is not map[string]interface{}`) ) type MapDict struct { data map[string]interface{} } func (d *MapDict) String() string { return "" } func NewMapDict()...
package gohs import ( "bytes" "encoding/json" "errors" "fmt" "io/ioutil" "net/http" "net/url" "strconv" "time" ) var hsAPIkey string var errThreshold = 1 var cl = &http.Client{} const coreURL = "https://api.hubapi.com" //SetAPIKey Sets the API key for all subsequent functions to use fu...
package timeout_test import ( "testing" "time" "github.com/etf1/kafka-transformer/internal/timeout" ) func TestWithoutTimeout(t *testing.T) { f := func() interface{} { time.Sleep(2 * time.Second) return true } res := timeout.WithTimeout(5*time.Second, f) if res == nil { t.Errorf("unexpected result, s...
// // Copyright 2020 The AVFS authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or ag...
package arrays func findDisappearedNumbers(nums []int) []int { retNums := make([]int, len(nums)+1) for _, n := range nums { retNums[n] = 1 } var j int for i, r := range retNums[1:] { if r == 0 { retNums[j] = i + 1 j++ } } return retNums[:j] }
package main import ( "fmt" ) // Gorra : Tipo de dato personalizado type Gorra struct { marca string color string precio float32 plana bool } func main() { //time.Sleep(time.Second * 5) user := "Diego Abanto" pais := "Rusia" var suma = 8 + 9 var resta = 6 - 4 var nombre = "Diego " var apellidos = "A...
package lcd import ( "fmt" "net/http" "github.com/gorilla/mux" "github.com/irisnet/irishub/app/protocol" "github.com/irisnet/irishub/app/v2/coinswap" "github.com/irisnet/irishub/client/context" "github.com/irisnet/irishub/client/utils" "github.com/irisnet/irishub/codec" ) func queryLiquidity(cliCtx context.C...
package dummy import ( "encoding/json" "fmt" "io/ioutil" "net/http" "github.com/gorilla/mux" "github.com/harriklein/pBE/pBEServer/log" "github.com/harriklein/pBE/pBEServer/utils" ) // swagger:route GET /dummies Dummy dummyList // Return a dummy list from the database // responses: // 200: dummyListResponse ...
package main // import github.com/HuiOnePos/flysnow import ( "net/http" _ "net/http/pprof" "github.com/HuiOnePos/flysnow/fly" "github.com/HuiOnePos/flysnow/tmp" "github.com/HuiOnePos/flysnow/utils" "github.com/sirupsen/logrus" ) func main() { logrus.SetLevel(logrus.DebugLevel) utils.LoacConfig() tmp.Init() ...
package main var input = `6-10 p: ctpppjmdpppppp 17-19 l: llllllllllllllllllll 14-19 z: zrzzzzzztzzzzwzzzzk 1-8 k: qkkkkkkxkkkkkkkkk 5-6 x: xxxxvxx 8-14 n: nnnnnnnnnnnnkfnnnnnn 18-19 t: ttttttttfttttttttwtt 3-13 w: wwwqwwwwrqwtzwvw 1-3 b: bbrbb 8-14 q: mqwmqvfqqqsqqqqqwb 5-7 c: lxrvdcch 1-5 v: mvdrkmrrcjnjpv 2-8 j: jw...
package cfmysql_test import ( "errors" . "github.com/andreasf/cf-mysql-plugin/cfmysql" "github.com/andreasf/cf-mysql-plugin/cfmysql/cfmysqlfakes" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" "os" ) var _ = Describe("MysqlRunner", func() { Context("RunMysql", func() { var exec *cfmysqlfakes.FakeEx...
package main import ( "github.com/beevik/ntp" log "github.com/sirupsen/logrus" "os" "time" ) func errorWrapper(e error, message string) { if e != nil { log.Errorf("Message %s. Error: %v", e, message) os.Exit(1) } } func GetNtpTime(host string) (time.Time, error) { t, err := ntp.Time(host) if err != nil {...
package server import ( "testing" "github.com/CyCoreSystems/ari-proxy/internal/integration" ) func TestChannelData(t *testing.T) { integration.TestChannelData(t, &srv{}) } func TestChannelAnswer(t *testing.T) { integration.TestChannelAnswer(t, &srv{}) } func TestChannelBusy(t *testing.T) { integration.TestCha...
package flags import ( "encoding/csv" "fmt" "github.com/saucelabs/saucectl/internal/config" "strings" ) // Simulator represents the simulator configuration. type Simulator struct { config.Simulator Changed bool } // String returns a string represenation of the simulator. func (e Simulator) String() string { i...
// publicly availble code for cargo entry package cargo import ( "fmt" "sync" "github.com/ArmadaStore/cargo/pkg/lib" ) func Run(cargoMgrIP string, cargoMgrPort string, cargoPort string, volSize string) error { cargoInfo := lib.Init(cargoMgrIP, cargoMgrPort, cargoPort, volSize) cargoInfo.Register() var wg syn...
package db import ( "context" "fmt" "log" "time" "github.com/letrannhatviet/my_framework/config" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" "go.mongodb.org/mongo-driver/mongo/readpref" ) var ( dbName = config.Config.MongoDB.Name dbCol = "Student" ) var Client *mongo.C...
package main import ( "log" "net/http" "github.com/julienschmidt/httprouter" linkRouter "github.com/wicoady1/gtdr-score-parser/router" ) func main() { router := httprouter.New() router.GET("/", linkRouter.Index) router.POST("/uploadfile", linkRouter.UploadFile) router.GET("/resultimage", linkRouter.ResultIma...
package utils import ( "errors" "fmt" "math" "strconv" "time" "github.com/golang191119/nc_crm/db" "github.com/golang191119/nc_crm/model" "github.com/golang191119/nc_crm/model/request" ) func TimeFormat(t time.Time) string { month := strconv.Itoa(int(t.Month())) if len(month) == 1 { month = "0" + month }...
// 找零钱问题 // 假设有1元、2元、5元、10元、20元、50元、100元、200元面额的硬币或者纸币。现在需要N元钱,有多少种零钱组合方式 package main import ( "fmt" "strconv" ) // 动态规划 func dp(A []int, money int) int { dp := make([]int, money+1) dp[0] = 1 for i:=0; i<len(A); i++ { for j:= A[i]; j<= money; j++ { dp[j] = dp[j] + dp[j - A[i]] } } return dp[money]...
package main import ( "crypto/md5" "crypto/sha256" "encoding/base64" "encoding/hex" "hash" "io" "io/ioutil" "net/http" "os" ) func hashFile(filePath string, hashCreator func() hash.Hash, encodeMethod func([]byte) string) (string, error) { //Initialize variable hashString now in case an error has to be retur...
package adabas import ( "os" "testing" "github.com/stretchr/testify/assert" ) const exportFileName = "/tmp/go-test-export.json" func TestExportMap(t *testing.T) { os.Remove(exportFileName) url, _ := NewURL("23") dbURL := DatabaseURL{URL: *url, Fnr: 4} repository := NewMapRepositoryWithURL(dbURL) ada, _ := N...
// /* // Copyright 2017 The Rook Authors. All rights reserved. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applica...
package main import ( "fmt" "math" ) var totalUniversalSubarrays int var uniSubarrList [][]int func main() { // fmt.Println("LongestStablePriceCountArr => ", fetchLongestStablePrices([]int{3, 1,2,1,2,2,1,3,1,1,2,2,2,2}, 1)) // fmt.Println("NoOfUniversalArray => ", countingUniversalSubarrays([]int{4,4,2,2,4,2}))...
package service import ( "bytes" "fmt" "github.com/go-ocf/cloud/portal-webapi/uri" "github.com/go-ocf/kit/log" "github.com/ugorji/go/codec" "github.com/valyala/fasthttp" router "github.com/buaazp/fasthttprouter" pbRA "github.com/go-ocf/cloud/resource-aggregate/pb" pbDD "github.com/go-ocf/cloud/resource-dire...
// Copyright 2020-2021 Buf Technologies, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law...
package core import ( "context" "encoding/json" "errors" "time" "github.com/google/uuid" ) type Namespace struct { ID uuid.UUID Name string Config string RootsInfo string CreatedAt time.Time UpdatedAt time.Time } type RootInfo struct { Name string RootID uuid.UUID } type RootsInfo struct { Def...
package main import ( "context" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/mongo" "golang.org/x/crypto/bcrypt" ) func emptyCollection(c *mongo.Collection) (int64, error) { deleteResult, err := c.DeleteMany(context.Background(), bson.D{{}}) if e...
package echo import ( "net" "sync" "github.com/korylprince/go-icmpv4/v2" ) //Send sends an ICMPv4 Echo Request to raddr from laddr with the given identifier and sequence func Send(laddr, raddr *net.IPAddr, identifier, sequence uint16) (err error) { p := NewEchoRequest(identifier, sequence) return icmpv4.Send(la...
// Package protobuf implements Protocol Buffers reflectively // using Go types to define message formats. // // This approach provides convenience similar to Gob encoding, // but with a widely-used and language-neutral wire format. // For general information on Protocol buffers see // https://developers.google.com/prot...
package uuid import ( "fmt" "strings" "testing" ) func TestPrefixedUUID(t *testing.T) { type args struct { prefix string } tests := []struct { name string args args wantErr bool }{ { name: "Test with Happy Path", args: args{ prefix: "ab", }, wantErr: true, }, { name: "Tes...
package main import ( "encoding/json" "fmt" ) type User struct { Id string Phone []string } func main() { user:=User{ Id:"123", Phone:[]string{"A","B","C","D"}, } bytes,err:=json.Marshal(&user) if err!=nil{ panic(err) } user1:=User{} json.Unmarshal(bytes,&user1) fmt.Println("user1",user1) var A...
package render import ( "io/ioutil" "regexp" "strings" "github.com/devspace-cloud/devspace/cmd" "github.com/devspace-cloud/devspace/cmd/flags" "github.com/devspace-cloud/devspace/e2e/utils" "github.com/devspace-cloud/devspace/pkg/devspace/deploy/deployer/helm" "github.com/devspace-cloud/devspace/pkg/util/log"...
// Copyright 2017 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable...
package statics /* BPAsset satisfies AssetEmbedder interface This one is namespaced for root of the boilerplate directory see boilerplate directory in bootstrap to see the content. */ import ( "github.com/getcouragenow/core-bs/sdk/pkg/common/embed" _ "github.com/getcouragenow/core-bs/statiks/bp" "github.com/rakyll...
package templates import ( "text/template" "github.com/lithammer/dedent" ) var ( HarborConfigTempl = template.Must(template.New("harbor").Parse(dedent.Dedent(` ## Configuration file of Harbor #This attribute is for migrator to detect the version of the .cfg file, DO NOT MODIFY! _version = 1.5.0 #The IP a...
package contruntime import ( "encoding/json" . "github.com/onsi/gomega" "github.com/werf/werf/integration/pkg/utils" "github.com/werf/werf/test/pkg/thirdparty/contruntime/manifest" ) func NewDockerRuntime() ContainerRuntime { return &DockerRuntime{} } type DockerRuntime struct { BaseContainerRuntime } func (...
package main import "errors" import "fmt" func f1(arg int) (int, error) { if arg == 42 { return -1, errors.New("the number 42 is unlucky man") } return arg + 3, nil } type argError struct { arg int prob string } func (e argError) Error() string { return fmt.Sprintf("%d - %s", e.arg, e.prob) } func f2(arg i...
package requests import ( "encoding/json" "testing" "github.com/mitchellh/mapstructure" "github.com/stretchr/testify/assert" ) func TestDecodeWalletAddRequest(t *testing.T) { encoded := `{"action":"wallet_add","key":"1234","wallet":"1234"}` var decoded WalletAddRequest json.Unmarshal([]byte(encoded), &decoded...
package main import "fmt" func main() { funcionarios := map[string]float64{ "José de Arimateia": 7564.15, "Maria Madalena": 5461.3, "João Batista": 10000.0, } fmt.Println(funcionarios["João Batista"]) /* Não há erros ao tentar acessar um elemento inexistente ou ainda Também não ocorre erros ao...
package orm import ( "database/sql" "testing" ) func TestDelete(t *testing.T) { _, got, _, _ := Delete(nil, "", nil) want := "db can't be nil" if got != nil && got.Error() != want { t.Errorf("got %q; want %q", got, want) } db := &sql.DB{} _, got2, _, _ := Delete(db, "", nil) want2 := "table can't be empt...
package controllers import ( "github.com/go-pg/pg" "github.com/go-pg/pg/orm" "github.com/goadesign/goa" "github.com/odiak/MoneyForest/app" "github.com/odiak/MoneyForest/constants" "github.com/odiak/MoneyForest/store" uuid "github.com/satori/go.uuid" ) // AccountController implements the user resource. type Acc...
package main import ( "fmt" "log" T "gorgonia.org/gorgonia" "gorgonia.org/tensor" ) func main() { g := T.NewGraph() x := T.NewMatrix(g, T.Float32, T.WithName("x"), T.WithShape(100, 100)) y := T.NewMatrix(g, T.Float32, T.WithName("y"), T.WithShape(100, 100)) xpy := T.Must(T.Add(x, y)) xpy2 := T.Must(T.Tanh(x...
import ( "math/rand" ) type Solution struct { nums []int } func Constructor(nums []int) Solution { s := Solution{nums} return s } func (this *Solution) Pick(target int) int { selected, count := 0, 1 for idx, v := range this.nums{ if v != target{ continue } if ...
package main import ( "fmt" "math" ) // Go is not object-based. // However, structural types such as struct (or any complex types, user-defined or otherwise) // can be the recipient of method signatures. type Vertex struct { X, Y float64 } // type Vertex receives method Scale. // Note the receiver is specified as...
package integration import ( "fmt" "os" . "gopkg.in/check.v1" ) func (s *RunSuite) TestFields(c *C) { p := s.CreateProjectFromText(c, ` hello: image: tianon/true cpuset: 1,2 mem_limit: 4194304 `) name := fmt.Sprintf("%s_%s_1", p, "hello") cn := s.GetContainerByNam...
// Copyright 2014 Gyepi Sam. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package redux import ( "encoding/json" "path/filepath" ) func decodePrerequisite(b []byte) (Prerequisite, error) { var p Prerequisite return p, json.Unmarshal(...
package app import ( "github.com/swipely/iam-docker/src/docker" "github.com/swipely/iam-docker/src/iam" "net/url" "time" ) // App holds the state of the application. type App struct { Config *Config DockerClient docker.RawClient STSClient iam.STSClient } // Config holds application configuration type...
package metre import ( "fmt" "errors" "github.com/satori/go.uuid" ) type Scheduler struct { Queue Queue Cache Cache } func NewScheduler(q Queue, c Cache) Scheduler { return Scheduler{q, c} } // Schedule schedules a task in the cache and queue if no task is actively waiting to be processed f...
package main func canConstruct(ransomNote string, magazine string) bool { ransomMap := make(map[int32]int) for _, c := range ransomNote { ransomMap[c]++ } magazineMap := make(map[int32]int) for _, c := range magazine { magazineMap[c]++ } for c, rCnt := range ransomMap { mCnt, ok := magazineMap[c] if !...
package app const ( SUCCESS = "ok" ERROR = "请求失败" INVALID_PARAMS = "请求参数错误" SERVER_ERROR = "服务错误" )
package main import ( "fmt" "time" "github.com/dymm/orchestrators/messageQ/pkg/config" "github.com/dymm/orchestrators/messageQ/pkg/workflow" ) func main() { myMessageQueue := config.CreateMQMessageQueueOrDie() allWorflows := getTheWorkflowsOrDie() workflow.StartSessionTimeoutChecking(myMessag...
// Copyright 2022 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to i...
package things import "fmt" type Reader struct {} func (r Reader) Init() { fmt.Println("New Reader") } func (r Reader) Read() string { return "read value" }
package preoblem /* 给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。 为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。 说明:不允许修改给定的链表 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/linked-list-cycle-ii 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 解题思路: 快慢指针, 快指针的速度为2, 慢指针的速度为1。 * 设链表到环的入口距离为 L, 其快慢指针的相遇点距离链...
package scheduler import ( "types" "github.com/golang/glog" ) var ( usersShare map[string]float64 usersAllocatedRes map[string]types.Resource usersWeight map[string]float64 totalCpu, totalMemory int64 ) func init() { usersShare = make(map[string]float64) usersAllocatedRes = make(map...
package ibeplus import ( "encoding/xml" "fmt" "time" "github.com/otwdev/ibepluslib/models" "github.com/otwdev/galaxylib" "github.com/asaskevich/govalidator" ) const bookingURL = "http://ibeplus.travelsky.com/ota/xml/AirBook" type PNRBooking struct { Order *models.OrderInfo PNR string } func NewPNRBooki...
package phase import ( "bufio" "bytes" "encoding/json" "fmt" "github.com/pmezard/go-difflib/difflib" "io" "log" "net/http" "os" "path/filepath" "reflect" "strconv" "strings" ) type Phase struct { answers Answers f *os.File r *bufio.Reader } type CheckOpts struct { MaxErrors int } func N...
/* * winnow: weighted point selection * * input: * matrix: an integer matrix, whose values are used as masses * mask: a boolean matrix showing which points are eligible for * consideration * nrows, ncols: the number of rows and columns * nelts: the number of points to select * * output: * point...
package main import ( "SoftwareGoDay1/humanity" ) func main() { // data.ReadFile("./test.csv") // data.LineToCSV("abc,def,ghi") // humanity.NewHumanFromCsvFile("./test.csv") // humanity.NewHumanFromJsonFile("./medium.json") pilotList := []humanity.Preparer{ &humanity.Pilot{ Human: &humanity.Human{ Name...
// Package main - пакет поискового робота для задания 7 package main import ( "fmt" "go.core/lesson7/pkg/cache/local" "go.core/lesson7/pkg/crawler" "go.core/lesson7/pkg/crawler/spider" "go.core/lesson7/pkg/engine" "go.core/lesson7/pkg/index" "go.core/lesson7/pkg/storage" "strings" ) // Сервер поисковика GoSea...
package main import ( "flag" "fmt" "image" _ "image/gif" _ "image/jpeg" _ "image/png" "os" ) var in string func init() { flag.StringVar(&in, "in", "", "input file") } func main() { flag.Parse() reader := os.Stdin if in != "" { file, err := os.Open(in) if err != nil { fatal(err.Error()) } read...
package handler import ( "github.com/micro/go-micro/errors" "golang.org/x/crypto/bcrypt" "golang.org/x/net/context" "github.com/dgrijalva/jwt-go" "github.com/dakstudios/auth-srv/db" auth "github.com/dakstudios/auth-srv/proto/auth" ) const ( jwtSecret = "some_secure_secret" ) type userClaims struct { ID str...