text
stringlengths
11
4.05M
package main /* @Time : 2020-04-01 21:29 @Author : audiRStony @File : 02_反射.go @Software: GoLand */ import ( "fmt" "reflect" ) /*在Go语言的反射机制中,任何接口值都是由一个具体类型和具体类型的值两部分组成的 在Go语言中反射的相关功能由内置的reflect包提供,任意接口值在反射中都可以理解为 由reflect.Type和reflect.Value两部分组成,并且reflect包提供了reflect.TypeOf和reflect.ValueOf 两个函数来获取任意对象的Type和Value*/ //类型反射 func reflectType(x interface{}) { //传递一个可以接收任何类型的空接口 t := reflect.TypeOf(x)//拿到x的动态类型 //fmt.Printf("type is : %v\n",t) fmt.Printf("name is %v,kind is %v\n",t.Name(),t.Kind()) //fmt.Printf("%T\n",x)//本质就是反射 /*ide的代码补全功能也是用的反射原理*/ } type cat struct { name string } type person struct { name string age int } func main() { var c1 = cat{ name:"XiaoHui", } var p1 = person{ name:"Zzh", age:27, } //reflectType(100) reflectType(c1) reflectType(p1) var i int32 = 100 var f float32 = 13.14 /*对于指针类型(引用类型),t.Name()为空*/ reflectType(&i) //name is ,kind is ptr reflectType(&f) //name is ,kind is ptr reflectType(map[string]int{}) //name is ,kind is map reflectType([]int{1,2,3}) //name is ,kind is slice }
package main import ( "fmt" "log" "github.com/piotrpersona/saga/events" "github.com/piotrpersona/saga/config" "github.com/piotrpersona/saga/store" ) func main() { config := config.RedisConfig{ Channel: "order.reserve", URI: "localhost:6379", Password: "topsecret", } client, err := store.NewRedisClient(config) if err != nil { log.Fatal(err) } orderEvent := events.RedisOrderEvent{ OrderID: "111", CustomerID: "111", Amount: 200, Status: "APPROVED", } resp, err := client.Publish(config.Channel, orderEvent).Result() if err != nil { log.Fatal(err) } fmt.Println(resp) }
// DRUNKWATER TEMPLATE(add description and prototypes) // Question Title and Description on leetcode.com // Function Declaration and Function Prototypes on leetcode.com //216. Combination Sum III //Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers. //Example 1: //Input: k = 3, n = 7 //Output: //[[1,2,4]] //Example 2: //Input: k = 3, n = 9 //Output: //[[1,2,6], [1,3,5], [2,3,4]] //Credits: //Special thanks to @mithmatt for adding this problem and creating all test cases. //func combinationSum3(k int, n int) [][]int { //} // Time Is Money
package main import ( "bufio" "errors" "flag" "fmt" "io" "log" "net" "os" "path/filepath" "regexp" "strings" "time" ) const DEFAULT_PORT int = 80 const ROOT = "./static/" const FLAG_PORT_HELP string = "the port to listen for requests" const CANNOT_OPEN_PORT_MSG string = `cannot connect to specified port hint: consider running executable with superuser permission because opening ports <= 1024 typically need more permission` var HEADER_REGEX_1 = regexp.MustCompile( `^(GET) (/[\w\./]*) HTTP/\d\.\d$`) var flagPort *int = flag.Int("port", DEFAULT_PORT, FLAG_PORT_HELP) const NOT_FOUND_MSG = "404 Not Found\r\n" const BAD_REQ_MSG = "400 Bad Request\r\n" type ( HttpRequest struct { Method string Path string } HttpResponse struct { Status int Date time.Time ContentLength int64 Data []byte Reader io.Reader LastModified time.Time Mime string } ) func main() { flag.Parse() address := fmt.Sprintf(":%d", *flagPort) listener, err := net.Listen("tcp", address) if err != nil { log.Fatal(CANNOT_OPEN_PORT_MSG) } defer listener.Close() log.Printf("Server is running on " + address) for { connection, err := listener.Accept() if err != nil { log.Printf("error in connecting [%s]", err) } else { go connectionHandler(connection) // go routine: handle it concurrently } } } func CreateRequest(scanner *bufio.Scanner) (*HttpRequest, error) { req := &HttpRequest{} scanner.Scan() if err := scanner.Err(); err != nil { return nil, err } firstLine := scanner.Text() if firstLine == "" { return nil, errors.New("first line was empty") //return CreateRequest(scanner) } res := HEADER_REGEX_1.FindStringSubmatch(firstLine) if len(res) < 1 { return nil, fmt.Errorf( "[%s] doesn't belong to a valid http request", firstLine) } req.Method = res[1] req.Path = res[2] // read headers for scanner.Scan() { text := strings.TrimSpace(scanner.Text()) if len(text) == 0 { // reached empty line after headers break } } if err := scanner.Err(); err != nil { return nil, err } return req, nil } func httpCodeToStatus(code int) string { switch code { case 200: return "OK" case 400: return "Bad Request" case 403: return "Forbidden" case 404: return "Not Found" default: log.Fatalf("unknown status code [%d]", code) return "501 Not Implemented" } } func writeResponse(res *HttpResponse, writer *bufio.Writer) error { var format = fmt.Sprintf firstLine := format("HTTP/1.1 %d %s\r\n", res.Status, httpCodeToStatus(res.Status)) headers := format("Date: %s\r\n", res.Date.Format(time.RFC1123Z)) headers += "Server: RoozbehAwesomeServer/1.0\r\n" if res.Reader != nil { headers += format("Last-Modified: %s\r\n", res.LastModified.Format(time.RFC1123Z)) } headers += format("Content-Type: %s;\r\n", res.Mime) headers += "Connection: close\r\n" headers += format("Content-Length: %d\r\n", res.ContentLength) _, err := writer.WriteString(firstLine + headers + "\r\n") if err != nil { return err } if res.Reader != nil { lenn, err := writer.ReadFrom(res.Reader) if err != nil { return err } if lenn != res.ContentLength { return errors.New("sent file length wasn't same as file length") } } else { writer.Write(res.Data) } writer.Flush() return nil } func createResponse(req *HttpRequest) (*HttpResponse, *os.File) { response := emptyResponse() response.Status = 200 file, err := os.Open(ROOT + req.Path) if err != nil { log.Printf("404 [%s]", err) return createError404(), nil } response.Reader = bufio.NewReader(file) fileStat, err := file.Stat() if err != nil { log.Printf("404 [%s] (err in reading file stat)", err) return createError404(), nil } if fileStat.IsDir() { req.Path += "/index.html" return createResponse(req) } response.ContentLength = fileStat.Size() response.LastModified = fileStat.ModTime() response.Mime = extensionToMime(filepath.Ext(req.Path)) return response, file } func emptyResponse() *HttpResponse { return &HttpResponse{ ContentLength: 0, Status: 200, Date: time.Now(), Mime: extensionToMime(".txt"), } } func createError400() *HttpResponse { resp := emptyResponse() resp.Status = 400 resp.Data = []byte(BAD_REQ_MSG) resp.ContentLength = int64(len(resp.Data)) return resp } func createError404() *HttpResponse { resp := emptyResponse() resp.Status = 404 resp.Data = []byte(NOT_FOUND_MSG) resp.ContentLength = int64(len(resp.Data)) return resp } func connectionHandler(conn net.Conn) { log.Printf("new connection from [%s]", conn.LocalAddr()) defer conn.Close() writer := bufio.NewWriter(conn) request, err := CreateRequest(bufio.NewScanner(conn)) if err != nil { log.Printf("400 : %s", err) err = writeResponse(createError400(), writer) if err != nil { log.Printf("cannot send 400 because [%s]", err) } return } response, file := createResponse(request) defer file.Close() writeResponse(response, writer) log.Printf("connection from [%s] closed", conn.LocalAddr()) } func extensionToMime(fileExt string) string { switch fileExt { case ".html": return "text/html" case ".htm": return "text/html" case ".js": return "application/javascript" case ".json": return "application/json" case ".xml": return "application/xml" case ".zip": return "application/zip" case ".wma": return "audio/x-ms-wma" case ".txt": return "text/plain" case ".ttf": return "applicatcase ion/x-font-ttf" case ".tex": return "application/x-tex" case ".sh": return "application/x-sh" case ".py": return "text/x-python" case ".png": return "image/png" case ".pdf": return "application/pdf" case ".mpeg": return "video/mpeg" case ".mpa": return "video/mpeg" case ".mp4": return "video/mp4" case ".mp3": return "audio/mpeg" case ".log": return "text/plain" case ".jpg": return "image/jpeg" case ".jpeg": return "image/jpeg" case ".java": return "text/x-java-source" case ".jar": return "application/java-archive" case ".gif": return "image/gif" case ".cpp": return "text/x-c" case ".bmp": return "image/bmp" case ".avi": return "video/x-msvideo" case ".mkv": return "video/x-matroska" case ".ico": return "image/x-icon" default: return "application/octet-stream" } }
package main import ( "fmt" "io/ioutil" "log" "net/http" ) func handler(w http.ResponseWriter, r *http.Request) { data, _ := ioutil.ReadAll(r.Body) serviceName := r.Header.Get("sparrow-service") methodName := r.Header.Get("sparrow-service-method") filterIvk := &filterInvoker{ Invoker: &httpInvoker{}, filters: []Filter{logFilter}, } output, _ := filterIvk.Invoke(&Invocation{ MethodName: methodName, ServiceName: serviceName, Input: data, }) fmt.Fprintf(w, "%s", string(output)) } // 启动服务器 func main() { AddService(&userService{}) AddService(&helloService{}) http.HandleFunc("/", handler) log.Fatal(http.ListenAndServe(":8080", nil)) }
package apis import ( "fmt" "pkg/mod/github.com/golang/protobuf/proto" "zinx/src/mmo_game_zinx/core" "zinx/src/mmo_game_zinx/pb/pb" "zinx/src/zinx/ziface" "zinx/src/zinx/znet" ) // 玩家移动路由 API type MoveApi struct { znet.BaseRouter } func (pM *MoveApi)Handle(request ziface.IRequest) { // 解析客户端传递进来的proto 协议 proto_msg := &pb.Postion{} err := proto.Unmarshal(request.GetData(),proto_msg) if err != nil{ fmt.Println("Move : Postion Unmarshal error ",err) return } // 得到当前发送位置的是哪个玩家 pid,err :=request.GetConnection().GetProperty("pid") if err != nil{ fmt.Println("GetProperty pid error ",err) return } fmt.Println("Player pid = %d ,move (%f,%f,%f,%f)\n",pid,proto_msg.X,proto_msg.Y,proto_msg.Z,proto_msg.V) // 给其他玩家进行当前玩家位置的信息广播 player := core.PWorldMgrObj.GetPlayerByPid(pid.(int32)) // 广播并更新当前玩家的坐标 player.UnpdatePos(proto_msg.X,proto_msg.Y,proto_msg.Z,proto_msg.V) }
package commands import ( "context" "github.com/sirupsen/logrus" "github.com/spf13/cobra" "github.com/yunify/qscamel/model" "github.com/yunify/qscamel/utils" ) // DeleteCmd will provide delete command for qscamel. var DeleteCmd = &cobra.Command{ Use: "delete [task name]", Short: "Delete a task", Args: cobra.ExactArgs(1), PreRunE: func(cmd *cobra.Command, _ []string) error { return initContext(cmd.Flag("config").Value.String()) }, Run: func(cmd *cobra.Command, args []string) { // Start delete. ctx := context.Background() // Load and check task. t, err := model.GetTaskByName(ctx, args[0]) if err != nil { logrus.Panicf("Task load failed for %v.", err) return } if t == nil { logrus.Errorf("Task %s is not exist.", args[0]) return } ctx = utils.NewTaskContext(ctx, t.Name) // Start delete. logrus.Infof("Task %s delete started.", t.Name) err = model.DeleteTask(ctx) if err != nil { logrus.Panicf("Delete task for %v.", err) } logrus.Infof("Task %s has been deleted.", t.Name) }, PostRunE: func(cmd *cobra.Command, args []string) error { return cleanUp() }, }
// Copyright alphaair 2016 // “幸运星座”游戏模拟推演示 package amusing import ( "fmt" "io/ioutil" "math/rand" "net/http" "os" "strconv" "strings" "time" ) // newNum生成一个指定范围内的随机数 func newNum(min int, max int) int { src := rand.NewSource(time.Now().UnixNano() / 1000 / 1000) r := rand.New(src) n := r.Intn(max + 1) for n < min { n = r.Intn(max + 1) } return n } // randomOrgApi 从random.Org生成随机数 func randomOrgApi(num int) []int { url := "https://www.random.org/integers/?num={num}&min=1&max=12&col=1&base=10&format=plain&rnd=new" url = strings.Replace(url, "{num}", strconv.Itoa(num), 1) rsp, err := http.Get(url) if err != nil { fmt.Println("请求random.org随机数失败。") return nil } buffer, err := ioutil.ReadAll(rsp.Body) if err != nil { fmt.Println("读取random.org随机数失败。") return nil } text := string(buffer) result := make([]int, num) ncodes := strings.Split(text, "\n") for i := 0; i < num; i++ { result[i], _ = strconv.Atoi(ncodes[i]) } return result } // LuckyStarSim 幸运星座模拟游戏 func LuckyStarSim(integral, persions, multiple, period int) (wines int, proportion float32, balance int) { fname := strconv.Itoa(integral) + "_" + strconv.Itoa(persions) + "_" + strconv.Itoa(period) + ".log" file, _ := os.OpenFile(fname, os.O_CREATE|os.O_APPEND, os.ModeAppend) text := fmt.Sprintf("=========模拟参数,最多容纳人数:%v,赔率:%v,模拟期数:%v=========\r\n", persions, multiple, period) fmt.Print(text) file.WriteString(text) balance = 0 wines = 0 for i := 1; i <= period; i++ { //num := newNum(1, 12) nums := randomOrgApi(persions + 1) num := nums[0] isw := true text = fmt.Sprintf("%3.f <%2.f> [", float32(i), float32(num)) fmt.Print(text) file.WriteString(text) //time.Sleep(200) for j := 1; j <= persions; j++ { balance += integral pnum := nums[j] //time.Sleep(200) if pnum == num { balance -= integral * multiple isw = false } if j > 1 { fmt.Print(",") file.WriteString(",") } text = fmt.Sprintf("%2.f", float32(pnum)) fmt.Print(text) file.WriteString(text) } if isw { wines++ fmt.Print("] W\r\n") file.WriteString("] W\r\n") } else { fmt.Print("] L\r\n") file.WriteString("] L\r\n") } } fmt.Print("********************************\r\n") file.WriteString("********************************\r\n") text = fmt.Sprintf("* 庄家赢期数:%v\r\n", wines) fmt.Print(text) file.WriteString(text) proportion = float32(wines) / float32(period) * float32(100) text = fmt.Sprintf("* 庄家赢概率:%%%5.2f \r\n", proportion) fmt.Print(text) file.WriteString(text) text = fmt.Sprintf("* 积分结余:%v \r\n", balance) fmt.Print(text) file.WriteString(text) fmt.Print("********************************\r\n") file.WriteString("********************************\r\n") defer file.Close() return }
package module import ( "math" "buddin.us/eolian/dsp" ) func init() { Register("Shape", func(Config) (Patcher, error) { return newShape() }) } type shape struct { multiOutIO gate, trigger, rise, fall, cycle, ratio *In state *shapeState stateFunc shapeStateFunc main, endCycle dsp.Frame } func newShape() (*shape, error) { m := &shape{ gate: NewInBuffer("gate", dsp.Float64(0)), trigger: NewInBuffer("trigger", dsp.Float64(0)), rise: NewInBuffer("rise", dsp.Duration(1)), fall: NewInBuffer("fall", dsp.Duration(1)), cycle: NewInBuffer("cycle", dsp.Float64(0)), ratio: NewInBuffer("ratio", dsp.Float64(0.01)), state: &shapeState{ lastGate: -1, lastTrigger: -1, }, stateFunc: shapeIdle, main: dsp.NewFrame(), endCycle: dsp.NewFrame(), } return m, m.Expose( "Shape", []*In{m.gate, m.trigger, m.rise, m.fall, m.cycle, m.ratio}, []*Out{ {Name: "output", Provider: provideCopyOut(m, &m.main)}, {Name: "endcycle", Provider: provideCopyOut(m, &m.endCycle)}, }, ) } func (s *shape) Process(out dsp.Frame) { s.incrRead(func() { var ( gate = s.gate.ProcessFrame() trigger = s.trigger.ProcessFrame() rise = s.rise.ProcessFrame() fall = s.fall.ProcessFrame() cycle = s.cycle.ProcessFrame() ratio = s.ratio.ProcessFrame() ) for i := range out { s.state.lastGate = s.state.gate s.state.lastTrigger = s.state.trigger s.state.gate = gate[i] s.state.trigger = trigger[i] s.state.rise = rise[i] s.state.fall = fall[i] s.state.cycle = cycle[i] s.state.ratio = ratio[i] s.stateFunc = s.stateFunc(s.state) if s.state.endCycle { s.endCycle[i] = 1 } else { s.endCycle[i] = -1 } s.main[i] = s.state.out } }) } type shapeState struct { out, gate, trigger, rise, fall, cycle, ratio dsp.Float64 base, multiplier, lastGate, lastTrigger dsp.Float64 endCycle bool } type shapeStateFunc func(*shapeState) shapeStateFunc func shapeIdle(s *shapeState) shapeStateFunc { s.endCycle = false s.out = 0 if s.lastGate <= 0 && s.gate > 0 { return prepRise(s) } if s.lastTrigger <= 0 && s.trigger > 0 { return prepRise(s) } return shapeIdle } func shapeRise(s *shapeState) shapeStateFunc { s.endCycle = false s.out = s.base + s.out*s.multiplier if s.out >= 1 { s.out = 1 if s.gate > 0 { return shapeRise } return prepFall(s) } return shapeRise } func shapeFall(s *shapeState) shapeStateFunc { if (s.lastGate <= 0 && s.gate > 0) || (s.lastTrigger <= 0 && s.trigger > 0) { return prepRise(s) } s.out = s.base + s.out*s.multiplier if float64(s.out) <= math.SmallestNonzeroFloat64 { s.endCycle = true s.out = 0 if s.cycle > 0 { return prepRise(s) } return shapeIdle } return shapeFall } func prepRise(s *shapeState) shapeStateFunc { s.base, s.multiplier = shapeCoeffs(s.ratio, s.rise, 1, logCurve) return shapeRise } func prepFall(s *shapeState) shapeStateFunc { s.base, s.multiplier = shapeCoeffs(s.ratio, s.fall, 0, expCurve) return shapeFall }
package main import ( "fmt" "sort" ) func main() { x := []string{"Ali", "Sancho", "Messi", "Bale", "Ronaldo"} y := []string{"Ali", "Sancho", "Messi", "Bale", "Ronaldo"} // 1. here we are converting "[]slice" into type "StringSlice" and then using StringSlice's "Sort" method sort.StringSlice(x).Sort() // 2. when we convert "[]slice" into type "StringSlice", we can see in "https://godoc.org/sort" that // "StringSlice" have built-in methods "Len", "Less" and "Swap" and these three methods are needed for us // to implement "Interface" interface. Hence we can use Interface's "Sort" method sort.Sort(sort.StringSlice(y)) fmt.Println("Sorted x: ", x) fmt.Println("Sorted y: ", y) } /* Since we can't attach method here (as we do not have a type) // works properly type t []string func (z t) something() { fmt.Println(z) } // we'll get unresolved type error s := []string{"AJ", "CJ"} func (z s) something() { fmt.Println(z) } */ // Sorted x: [Ali Bale Messi Ronaldo Sancho] // Sorted y: [Ali Bale Messi Ronaldo Sancho]
package main import ( "fmt" ) func main() { y := []string{"sun", "moon", "star", "rocket", "foot", "face"} fmt.Println(y) fmt.Println(cap(y)) fmt.Println(len(y)) for i, v := range y { fmt.Println(i, v) } fmt.Println("Let's check the alternative method") //alternative method for i := 0; i <= 5; i++ { fmt.Println(i, y[i]) } fmt.Println("How's it? Are you enjoying it?") }
package validator import ( "testing" "github.com/stretchr/testify/assert" ) func TestJSON(t *testing.T) { type User struct { Username string `json:"username" validate:"alphanum"` Email string `json:"email" validate:"email"` } u := &User{ Username: "big_kahuna", Email: "savage_surfer@alabama.....com", } jObject := map[string]string{ "username": `{"field":"username","message":"doesn't validate as alphanum.","value":"` + u.Username + `"}`, "email": `{"field":"email","message":"doesn't validate as email.","value":"` + u.Email + `"}`, } validate := New() err := validate.Struct(u) for _, err := range err.(ValidationErrors) { j, err2 := err.MarshalJSON() assert.NoError(t, err2) assert.Equal(t, jObject[err.JSON()], string(j)) } }
package atomicraceprotect import ( "fmt" "sync" "sync/atomic" "time" ) // This demonstrates the use of teh atomic package functions Store and Load for safe acces // to numeric types var ( //shutdown is a flac to alert goroutines to shutdown shutdown int64 //wg waits for a program to fininsh //this is declared in the atomicprotect wg sync.WaitGroup ) func Mystoreandload() { //Add count of for each gorouting wg.Add(2) //create goroutines go doWork("A") go doWork("B") //Give goroutines time to run time.Sleep(1 * time.Second) //Safely flag time to shutdown fmt.Println("Shutdown nwo") atomic.StoreInt64(&shutdown, 1) //Wait for goroutines to finish wg.Wait() } func doWork(name string) { defer wg.Done() //endlessfor loop for { fmt.Printf("Doing %s Work \n", name) time.Sleep(250 * time.Millisecond) //Do we need to shutdown if atomic.LoadInt64(&shutdown) == 1 { fmt.Printf("Shutting %s Down\n", name) break } } }
package mira const ( // RedditBase is the basic reddit base URL, authed is the base URL for use once authenticated RedditBase = "https://www.reddit.com/" // RedditOauth is the oauth url to pass the tokens to RedditOauth = "https://oauth.reddit.com" // JsonAPI sets the api type to json JsonAPI = "json" // Sorting options Hot = "hot" New = "new" Top = "top" Rising = "rising" Controversial = "controversial" Random = "random" // Duration options Hour = "hour" Day = "day" Week = "week" Year = "year" All = "all" )
/* * Delete a given cross-datacenter firewall policy. */ package main import ( "flag" "fmt" "os" "path" "strings" "github.com/grrtrr/clcv2/clcv2cli" "github.com/grrtrr/exit" ) func main() { flag.Usage = func() { fmt.Fprintf(os.Stderr, "usage: %s [options] <Location> <PolicyID>\n", path.Base(os.Args[0])) flag.PrintDefaults() } flag.Parse() if flag.NArg() != 2 { flag.Usage() os.Exit(1) } client, err := clcv2cli.NewCLIClient() if err != nil { exit.Fatal(err.Error()) } if err := client.DeleteCrossDataCenterFirewallPolicy(flag.Arg(0), flag.Arg(1)); err != nil { exit.Fatalf("failed to delete %s firewall policy %s: %s", flag.Arg(0), flag.Arg(1), err) } fmt.Printf("Successfully deleted cross-datacenter policy %s in %s.\n", flag.Arg(1), strings.ToUpper(flag.Arg(0))) }
package main import ( "os" "testing" "github.com/stretchr/testify/assert" ) func TestSystemEnv(t *testing.T) { setRunAppEnv("KEY1=val1 KEY2=val2") assert.Equal(t, os.Getenv("KEY1"), "val1") assert.Equal(t, os.Getenv("KEY2"), "val2") } func TestSetEnv(t *testing.T) { envs = &Envs{ Mode: "add", Name: "", } assert.NotNil(t, envsValid()) envs = &Envs{ Mode: "delete", Name: "", } assert.NotNil(t, envsValid()) envs = &Envs{ Mode: "add", Name: "test", } assert.Nil(t, envsValid()) envs = &Envs{ Mode: "delete", Name: "test", } assert.Nil(t, envsValid()) }
package custom import ( "io" "path/filepath" "strings" "github.com/bmatcuk/doublestar" "github.com/devspace-cloud/devspace/pkg/devspace/config/generated" "github.com/devspace-cloud/devspace/pkg/devspace/config/versions/latest" "github.com/devspace-cloud/devspace/pkg/util/command" "github.com/devspace-cloud/devspace/pkg/util/hash" logpkg "github.com/devspace-cloud/devspace/pkg/util/log" dockerterm "github.com/docker/docker/pkg/term" "github.com/pkg/errors" "gopkg.in/yaml.v2" ) var ( _, stdout, stderr = dockerterm.StdStreams() ) // Builder holds all the relevant information for a custom build type Builder struct { imageConf *latest.ImageConfig imageConfigName string imageTag string } // NewBuilder creates a new custom builder func NewBuilder(imageConfigName string, imageConf *latest.ImageConfig, imageTag string) *Builder { return &Builder{ imageConfigName: imageConfigName, imageConf: imageConf, imageTag: imageTag, } } // ShouldRebuild implements interface func (b *Builder) ShouldRebuild(cache *generated.CacheConfig, forceRebuild, ignoreContextPathChanges bool) (bool, error) { if b.imageConf.Build.Custom.OnChange == nil || len(b.imageConf.Build.Custom.OnChange) == 0 { return true, nil } // Hash image config configStr, err := yaml.Marshal(*b.imageConf) if err != nil { return false, errors.Wrap(err, "marshal image config") } imageConfigHash := hash.String(string(configStr)) // Loop over on change globs customFilesHash := "" for _, pattern := range b.imageConf.Build.Custom.OnChange { files, err := doublestar.Glob(pattern) if err != nil { return false, err } for _, file := range files { sha256, err := hash.Directory(file) if err != nil { return false, errors.Wrap(err, "hash "+file) } customFilesHash += sha256 } } customFilesHash = hash.String(customFilesHash) imageCache := cache.GetImageCache(b.imageConfigName) // only rebuild Docker image when Dockerfile or context has changed since latest build mustRebuild := imageCache.Tag == "" || imageCache.ImageConfigHash != imageConfigHash || imageCache.CustomFilesHash != customFilesHash imageCache.ImageConfigHash = imageConfigHash imageCache.CustomFilesHash = customFilesHash return mustRebuild, nil } // Build implements interface func (b *Builder) Build(log logpkg.Logger) error { // Build arguments args := []string{} for _, arg := range b.imageConf.Build.Custom.Args { args = append(args, arg) } if len(b.imageConf.Tags) == 0 { if b.imageConf.Build.Custom.ImageFlag != "" { args = append(args, b.imageConf.Build.Custom.ImageFlag) } args = append(args, b.imageConf.Image+":"+b.imageTag) } else { for _, tag := range b.imageConf.Tags { if b.imageConf.Build.Custom.ImageFlag != "" { args = append(args, b.imageConf.Build.Custom.ImageFlag) } args = append(args, b.imageConf.Image+":"+tag) } } for _, arg := range b.imageConf.Build.Custom.AppendArgs { args = append(args, arg) } // Create the command cmd := command.NewStreamCommand(filepath.FromSlash(b.imageConf.Build.Custom.Command), args) // Determine output writer var writer io.Writer if log == logpkg.GetInstance() { writer = stdout } else { writer = log } log.Infof("Build %s:%s with custom command %s %s", b.imageConf.Image, b.imageTag, b.imageConf.Build.Custom.Command, strings.Join(args, " ")) err := cmd.Run(writer, writer, nil) if err != nil { return errors.Errorf("Error building image: %v", err) } log.Done("Done processing image '" + b.imageConf.Image + "'") return nil }
package util import ( "github.com/leonelquinteros/gotext" ) func TR(str string, vars ...interface{}) string { return gotext.Get(str, vars...) } func LoadTranslation(lib, lang, dom string) { gotext.Configure(lib, lang, dom) }
/* Objective Design a modulator/demodulator pair to accurately transmit data as quickly as possible over simulated plain old telephone service (POTS). Steps Generate some random (/dev/random or the like) data that will take 3-4 seconds to transmit Modulate the data with your modulator to produce an audio file Pass the audio file through the POTS simulator. If you don't have Python/Scipy you can upload a file with the form, or do a JSON API request. Demodulate the audio file back to binary data Validate that the input and output are equal-ish* (limit 1 out of every 1000 bits can be corrupted) Score is number of bits transmitted divided by the length of the audio file (bits/second) Rules Input file must be 3-4 seconds, 44.1 kHz, mono. Run the simulator with an SNR of 30 dB (it's default) The demodulator must reconstruct the transmitted data with a bit error rate of no more than 10-3 (1 per thousand bits). No digital compression is allowed (i.e. zipping the data. It's outside the scope of the challenge.) No attempting to shove data into frequencies above 4 kHz. (My filters aren't perfect, but they're reasonably POTS-like with a relatively small number of taps.) If your modem protocol requires a short preamble (no more than 1 second) to synchronize/calibrate the receiver, it isn't penalized. If possible, please host the audio file somewhere accessible so we can listen to a cacophony of beeps and boops. Example Here's an example notebook that demonstrates the modulation/demodulation with simple "on-off keying" (audio samples included!). https://nbviewer.org/github/nicktimko/pots-sim/blob/master/OOK_simple_demo.ipynb It would score 100 (bits/second). Note that it's transmitting with a much worse 5 dB SNR. */ package main import ( "flag" "fmt" "math" "math/rand" "os" "time" ) type Option struct { samplerate float64 // sample rate baudrate float64 // baud rate carrier float64 // carrier frequency (hz) duration float64 // signal duration (seconds) noisy bool } var opt = Option{ samplerate: 44100, baudrate: 100, carrier: 800, duration: 10, noisy: true, } func main() { rand.Seed(time.Now().UnixNano()) parseflags() data := gensym(2, int(opt.baudrate*opt.duration)) txdata := modulate(data, opt.baudrate, opt.samplerate, opt.carrier, opt.duration) rxdata := demodulate(txdata, opt.baudrate, opt.samplerate, opt.carrier, opt.duration, opt.noisy) diff(data, rxdata) } func parseflags() { flag.Float64Var(&opt.samplerate, "samplerate", opt.samplerate, "sample rate") flag.Float64Var(&opt.baudrate, "baudrate", opt.baudrate, "baud rate") flag.Float64Var(&opt.carrier, "carrier", opt.carrier, "carrier frequency") flag.Float64Var(&opt.duration, "duration", opt.duration, "signal duration") flag.BoolVar(&opt.noisy, "noisy", opt.noisy, "simulate noisy environment") flag.Usage = usage flag.Parse() } func usage() { fmt.Fprintln(os.Stderr, "usage: [options]") flag.PrintDefaults() os.Exit(2) } /* https://en.wikipedia.org/wiki/On%E2%80%93off_keying On-Off Keying (OOK) Modulation Simplest form of Amplitude-Shift Keying (ASK) Uses one sinusoidal wave at a fixed frequency (carrier frequency) to transmit the data. The symbols is a binary (0, 1) and maps to the following: 0 -> suppresses the sinusoidal wave, output 0 at that point. 1 -> output whatever the value the sinusoidal wave has at that point in time. */ func modulate(data []int, baudrate, samplerate, carrier, duration float64) []float64 { t := linspace(0, duration, 1/samplerate) m := make([]float64, len(t)) for i := range t { j := clamp(int(t[i]*baudrate), 0, len(data)-1) m[i] = float64(data[j]) * math.Sin(2*math.Pi*carrier*t[i]) } return m } /* To demodulate OOK modulation: 1. Multiply the received signal with the modulated carrier wave, if we want to simulate a noisy environment add a random phase delay to the carrier wave, due to the robustness of using only binary symbols, it is robust to phase shifts. 2. Take the absolute value of that signal above to rectify it, this is to simplify the math when detecting the threshold for 0/1 3. A symbol makes up of N samples, which is basically duplicated data when we transmit, so take N sample average for each symbol. 4. Threshold the average value calculated. If it is larger than a threshold, output a 1, otherwise 0. 5. The threshold value is calculated as the (max(data) + min(data)) / 2 */ func demodulate(data []float64, baudrate, samplerate, carrier, duration float64, noisy bool) []int { phase := 0.0 if noisy { phase = 2 * math.Pi * rand.Float64() } t := linspace(0, duration, 1/samplerate) d := make([]float64, len(data)) for i := range data { d[i] = data[i] * math.Sin(2*math.Pi*carrier*t[i]+phase) d[i] = math.Abs(d[i]) } samplespersymbol := samplerate / baudrate symbolstarts := make([]float64, int(baudrate*duration)) for i := range symbolstarts { symbolstarts[i] = float64(i) * samplespersymbol } var c []float64 for _, s := range symbolstarts { c = append(c, sum(d[int(s):int(s+samplespersymbol)])) } mi, ma := minmax(c) threshold := (ma + mi) / 2 r := make([]int, len(c)) for i := range c { if c[i] > threshold { r[i] = 1 } } return r } func linspace(start, end, step float64) []float64 { r := []float64{} for x := start; x <= end; x += step { r = append(r, x) } return r } func gensym(nsym, length int) []int { p := make([]int, length) for i := range p { p[i] = rand.Intn(nsym) } return p } func sum(x []float64) float64 { r := 0.0 for i := range x { r += x[i] } return r } func minmax(x []float64) (mi, ma float64) { mi = math.MaxFloat64 ma = -math.MaxFloat64 for i := range x { mi = math.Min(mi, x[i]) ma = math.Max(ma, x[i]) } return } func clamp(x, a, b int) int { if x < a { x = a } else if x > b { x = b } return x } func diff(a, b []int) { n := len(a) m := len(b) if n != m { fmt.Printf("length mismatch: %d %d\n", n, m) } if n > m { n = m } for i := 0; i < n; i++ { if a[i] != b[i] { fmt.Printf("data mismatch: %d %d %d\n", i, a[i], b[i]) } } }
package fleetrome import ( "github.com/zond/godip/state" "github.com/zond/godip/variants/classical" "github.com/zond/godip/variants/classical/orders" "github.com/zond/godip/variants/classical/start" "github.com/zond/godip/variants/common" cla "github.com/zond/godip/variants/classical/common" dip "github.com/zond/godip/common" ) var FleetRomeVariant = common.Variant{ Name: "Fleet Rome", Graph: func() dip.Graph { return start.Graph() }, Start: func() (result *state.State, err error) { if result, err = classical.Start(); err != nil { return } result.RemoveUnit(dip.Province("rom")) if err = result.SetUnit(dip.Province("rom"), dip.Unit{ Type: cla.Fleet, Nation: cla.Italy, }); err != nil { return } return }, Blank: classical.Blank, Phase: classical.Phase, ParseOrders: orders.ParseAll, ParseOrder: orders.Parse, OrderTypes: orders.OrderTypes(), Nations: cla.Nations, PhaseTypes: cla.PhaseTypes, Seasons: cla.Seasons, UnitTypes: cla.UnitTypes, SoloSupplyCenters: 18, SVGMap: func() ([]byte, error) { return classical.Asset("svg/map.svg") }, SVGVersion: "1482957154", SVGUnits: map[dip.UnitType]func() ([]byte, error){ cla.Army: func() ([]byte, error) { return classical.Asset("svg/army.svg") }, cla.Fleet: func() ([]byte, error) { return classical.Asset("svg/fleet.svg") }, }, CreatedBy: "Richard Sharp", Version: "", Description: "Classical Diplomacy, but Italy starts with a fleet in Rome.", Rules: "The first to 18 supply centers is the winner. Rules are as per classical Diplomacy, but Italy starts with a fleet in Rome rather than an army.", }
package http import ( "context" "fmt" "net/http" "github.com/pkg/errors" "github.com/pyspa/voice-notify/log" "github.com/pyspa/voice-notify/service" "github.com/pyspa/voice-notify/tts" "github.com/spf13/viper" ) type HttpService struct { } func (s *HttpService) Start() { http.HandleFunc("/", handler) addr := viper.GetString("http.addr") log.Info("Listen local http server", log.Fields{ "addr": addr, }) if err := http.ListenAndServe(addr, nil); err != nil { log.Error(errors.Wrapf(err, "failed listen addr=%s", addr), nil) } } func handler(w http.ResponseWriter, r *http.Request) { if err := r.ParseForm(); err != nil { log.Error(errors.Wrap(err, "failed parse form"), nil) fmt.Fprintf(w, "ParseForm() err: %v", err) return } text := r.FormValue("text") ctx := context.Background() if err := tts.Speech(ctx, text); err != nil { log.Error(errors.Wrap(err, "failed speech."), nil) fmt.Fprintf(w, "Speech err: %v", err) return } w.WriteHeader(200) fmt.Fprintf(w, "OK") } func NewService() service.Service { return &HttpService{} }
package nameshake import ( "github.com/cosmos/cosmos-sdk/codec" ) var ModuleCdc = codec.New() func RegisterCodec(cdc *codec.Codec) { cdc.RegisterConcrete(MsgSetName{}, "nameshake/SetName", nil) cdc.RegisterConcrete(MsgBuyName{}, "nameshake/BuyName", nil) }
// Copyright 2020 IOTA Stiftung // SPDX-License-Identifier: Apache-2.0 package registry import ( "github.com/iotaledger/hive.go/logger" "github.com/iotaledger/wasp/packages/dbprovider" "github.com/iotaledger/wasp/packages/tcrypto" "github.com/iotaledger/wasp/plugins/database" ) // Impl is just a placeholder to implement all interfaces needed by different components. // Each of the interfaces are implemented in the corresponding file in this package. type Impl struct { suite tcrypto.Suite log *logger.Logger dbProvider *dbprovider.DBProvider } // New creates new instance of the registry implementation. func NewRegistry(suite tcrypto.Suite, log *logger.Logger, dbp ...*dbprovider.DBProvider) *Impl { ret := &Impl{ suite: suite, log: log.Named("registry"), } if len(dbp) == 0 { ret.dbProvider = database.GetInstance() } else { ret.dbProvider = dbp[0] } return ret }
package main import ( "os/exec" "strings" ) func getMergedBranches() ([]string, error) { var branches []string out, err := exec.Command("git", "branch", "--merged").Output() if err != nil { return nil, err } for _, branch := range strings.Split(string(out), "\n") { branch = strings.TrimSpace(branch) if (branch == "") { continue } // * develop のようなカレントブランチは対象外 if strings.HasPrefix(branch, "*") { continue } // master/developは対象外 if strings.Contains(branch, "master") || strings.Contains(branch, "develop") { continue } branches = append(branches, branch) } return branches, nil } func delBranch(name string) error { return exec.Command("git", "branch", "-d", name).Run() }
package Controllers import ( "errors" Config "github.com/renancrc99/1sti.challenge.backend/config" "github.com/renancrc99/1sti.challenge.backend/graph/model" Models "github.com/renancrc99/1sti.challenge.backend/models" ) func CriarUsuario(input *model.UsuarioInput) error { usuario := new(Models.Usuario) if input.Nome == "" { return errors.New("Campo nome é obrigatório") } if input.Email == "" { return errors.New("Campo email é obrigatório") } usuario.ID = input.ID usuario.Nome = input.Nome usuario.Email = input.Email if err := Config.DB.Create(usuario).Error; err != nil { return err } return nil } func CriarTarefaPorUsuario(tarefaInput model.TarefaInput) error { tarefa := new(Models.Tarefa) tarefa.IDUsuario = tarefaInput.UsuarioInput.ID tarefa.ID = tarefaInput.ID tarefa.Text = tarefaInput.Text tarefa.Feito = tarefaInput.Feito tarefa.Status = tarefaInput.Status if err := Config.DB.Create(tarefa).Error; err != nil { return err } return nil } func EditarTarefaPorUsuario(tarefaInput model.TarefaInput) error { var tarefa Models.Tarefa Config.DB.Where("id = ?", tarefaInput.ID).Find(&tarefa) tarefa.Text = tarefaInput.Text tarefa.Feito = tarefaInput.Feito tarefa.Status = tarefaInput.Status if err := Config.DB.Save(tarefa).Error; err != nil { return err } return nil } func MudarStatusTarefa(tarefaInput model.TarefaInput) error { var tarefa Models.Tarefa Config.DB.Where("id = ?", tarefaInput.ID).Find(&tarefa) tarefa.Status = tarefaInput.Status if err := Config.DB.Save(&tarefa).Error; err != nil { return err } return nil } func ListarTarefasUsuario(input model.UsuarioInput) []Models.Tarefa { var tarefa []Models.Tarefa Config.DB.Where("id_usuario = ?", input.ID).Find(&tarefa) return tarefa } func DeletarUsuario(id int) error { var usuario Models.Usuario Config.DB.Where("id = ?", id).Find(&usuario) if err := Config.DB.Delete(usuario).Error; err != nil { return err } return nil } func DeletarTarefa(id int) error { var tarefa Models.Tarefa Config.DB.Where("id = ?", id).Find(&tarefa) if err := Config.DB.Delete(tarefa).Error; err != nil { return err } return nil }
/** * day 08 2020 * https://adventofcode.com/2020/day/8 * * compile: go build main.go * run: ./main < input * compile & run: go run main.go < input **/ package main import ( "bufio" "os" "fmt" "strings" ) type bootcode struct { instruction string value int alreadyRun bool } var gameboy []bootcode var accumulator int var gameboyLen int func execBootCode(checkForEnd bool) int { i := 0 for { if checkForEnd && i == gameboyLen { // on last instruction, part 2 answer return 1 } else if (checkForEnd && i > gameboyLen) || gameboy[i].alreadyRun { // in an infinite loop return 0 } else if !checkForEnd && gameboy[i].alreadyRun { // part 1 - exit just whenever we hit an instruction we've alreay seen return 0 } switch gameboy[i].instruction { case "acc": gameboy[i].alreadyRun = true accumulator += gameboy[i].value i++ break case "jmp": gameboy[i].alreadyRun = true i += gameboy[i].value break case "nop": gameboy[i].alreadyRun = true i++ break } } return 0 } // set all 'alreadyRun' varibles in array to false // and set accumulator to 0 func reset() { for i := 0; i < gameboyLen; i++ { gameboy[i].alreadyRun = false } accumulator = 0 } // set a jmp to nop or a nop to jmp func flip(instr *string) { if *instr == "jmp" { *instr = "nop" } else if *instr == "nop" { *instr = "jmp" } } func findCorrupted() { for i := 0; i < gameboyLen; i++ { reset() // change instruction flip(&gameboy[i].instruction) // test it out if execBootCode(true) == 1 { break } // change it back flip(&gameboy[i].instruction) } } func main() { scan := bufio.NewScanner(os.Stdin) for scan.Scan() { f := strings.NewReader(scan.Text()) var bc bootcode _, err := fmt.Fscanf(f, "%s %d", &bc.instruction, &bc.value) if err != nil { fmt.Fprintf(os.Stderr, "Fscanf: %v\n", err) } bc.alreadyRun = false gameboy = append(gameboy, bc) } gameboyLen = len(gameboy) execBootCode(false) fmt.Println("part 1:", accumulator) findCorrupted() fmt.Println("part 2:", accumulator) }
package oasis_test import ( "net/http" "net/http/httptest" "net/url" "strings" "testing" "github.com/go-oasis/oasis" ) func TestResponseCache(t *testing.T) { var rspr oasis.Responder = &oasis.ResponseCache{ Code: http.StatusInternalServerError, HeaderCache: http.Header{ "X-Hello-World": {"silly hello"}, }, Body: strings.NewReader("hello world"), } w := httptest.NewRecorder() rspr.ResponseTo(w) if want, have := http.StatusInternalServerError, w.Code; want != have { t.Errorf("expected: %#v, got: %#v", want, have) } if want, have := "silly hello", w.Header().Get("X-Hello-World"); want != have { t.Errorf("expected: %#v, got: %#v", want, have) } if want, have := "hello world", w.Body.String(); want != have { t.Errorf("\nexpected: %s\ngot: %s", want, have) } } func TestRedirectResponse(t *testing.T) { var rspr oasis.Responder tests := []struct { rspr *oasis.RedirectResponse expected string expectedError string }{ { rspr: &oasis.RedirectResponse{ HeaderCache: http.Header{ "X-Hello-World": {"silly hello"}, }, RedirectURI: "https://foobar.com/path/oauth2?hello=world&foo=bar", Query: url.Values{ "x-something": {"good"}, "y-something": {"bad"}, "z-something": {"ugly"}, }, }, expected: "https://foobar.com/path/oauth2?foo=bar&hello=world&x-something=good&y-something=bad&z-something=ugly", }, { rspr: &oasis.RedirectResponse{ HeaderCache: http.Header{ "X-Hello-World": {"silly hello"}, }, RedirectURI: "/path/oauth2?hello=world&foo=bar", Query: url.Values{ "x-something": {"good"}, "y-something": {"bad"}, "z-something": {"ugly"}, }, }, expectedError: `redirect_uri is misformed. expected a full URI but got "/path/oauth2?hello=world&foo=bar"`, }, } for _, test := range tests { rspr = test.rspr w := httptest.NewRecorder() err := rspr.ResponseTo(w) if test.expected != "" { if want, have := http.StatusTemporaryRedirect, w.Code; want != have { t.Errorf("expected %#v, got %#v", want, have) } if want, have := w.Header().Get("Location"), test.expected; want != have { t.Errorf("\nexpected: %s\ngot: %s", want, have) } } if test.expectedError != "" { if err == nil { t.Errorf("expected error, got nil") } else if want, have := test.expectedError, err.Error(); want != have { t.Errorf("\nexpected: %s\ngot: %s", want, have) } } } }
package main import ( "fmt" "time" "github.com/golang-jwt/jwt" ) const ( mySigningKey = "WOW,MuchShibe,ToDogge" ) func main() { createdToken, err := exampleNew([]byte(mySigningKey)) if err != nil { fmt.Println("Creating token failed") } exampleParse(createdToken, mySigningKey) } func exampleNew(mySigningKey []byte) (string, error) { // Create the token token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{ "foo": "bar", "exp": time.Now().Add(time.Hour * 72).Unix(), }) // Sign and get the complete encoded token as a string tokenString, err := token.SignedString(mySigningKey) return tokenString, err } func exampleParse(myToken, myKey string) { token, err := jwt.Parse(myToken, func(token *jwt.Token) (interface{}, error) { return []byte(myKey), nil }) if err == nil && token.Valid { fmt.Println("Your token is valid. I like your style.") fmt.Printf("%+v\n", token) } else { fmt.Println("This token is terrible! I cannot accept this.") } }
package core import ( "encoding/json" "time" ) type Snippet struct { Title string Body string Description string CreatedAt time.Time UpdatedAt time.Time } func MarshalSnippetForStorage(s Snippet) ([]byte, []byte, error) { name := []byte(s.Title) snippetBlob, err := json.Marshal(s) if err != nil { return []byte{}, []byte{}, err } return name, snippetBlob, err } func UnmarshalSnippet(blob []byte) (Snippet, error) { s := &Snippet{} err := json.Unmarshal(blob, s) return *s, err } func NewSnippet(title, description, body string) *Snippet { now := time.Now() s := new(Snippet) s.Title = title s.Body = body s.Description = description s.CreatedAt = now return s }
package main import "github.com/Mario-Jimenez/pricescraper/service" func main() { service.Run("pricescraper-srv", "0.0.1") }
package main import ( "log" "sync" "time" ) var cache = make(map[string]string) func main() { var wg sync.WaitGroup var mu sync.Mutex wg.Add(1) go func() { mu.Lock() defer wg.Done() for len(cache) == 0 { mu.Unlock() log.Printf("[go-routine] waiting for Elements from cache : %v\n", cache) time.Sleep(1 * time.Second) mu.Lock() } log.Printf("[go-routine] Got Elements from cache : %v\n", cache) mu.Unlock() }() time.Sleep(1 * time.Second) log.Println("[main-routine] preparing resources to populate cache") time.Sleep(1 * time.Second) log.Println("[main-routine] Populating cache") mu.Lock() cache["key"] = "ABC12345" mu.Unlock() log.Println("[main-routine] Populated cache") wg.Wait() log.Println("[main-routine] Done!") } /* raja@raja-Latitude-3460:~/Documents/coding/golang/go-by-concurrency$ go run sync/without_sync_cond.go 2021/06/06 11:50:40 [go-routine] waiting for Elements from cache : map[] 2021/06/06 11:50:41 [main-routine] preparing resources to populate cache 2021/06/06 11:50:41 [go-routine] waiting for Elements from cache : map[] 2021/06/06 11:50:42 [main-routine] Populating cache 2021/06/06 11:50:42 [main-routine] Populated cache 2021/06/06 11:50:42 [go-routine] Got Elements from cache : map[key:ABC12345] 2021/06/06 11:50:42 [main-routine] Done! */
package day11 func countOccupiedSightLines(row int, col int, seating [][]rune) (adjacent int) { cardinalMap := make(map[string]rune) //Expand outward in all cardinals, stop on for i := 1; i < len(seating); i++ { back := i * -1 forward := i //south if row+forward < len(seating) && cardinalMap["S"] == 0 { if seating[row+forward][col] != Empty { cardinalMap["S"] = seating[row+forward][col] } } //north if row+back >= 0 && cardinalMap["N"] == 0 { if seating[row+back][col] != Empty { cardinalMap["N"] = seating[row+back][col] } } //East if col+forward < len(seating[col]) && cardinalMap["E"] == 0 { if seating[row][col+forward] != Empty { cardinalMap["E"] = seating[row][col+forward] } } //West if col+back >= 0 && cardinalMap["W"] == 0 { if seating[row][col+back] != Empty { cardinalMap["W"] = seating[row][col+back] } } //NorthWest if col+back >= 0 && row+back >= 0 && cardinalMap["NW"] == 0 { if seating[row+back][col+back] != Empty { cardinalMap["NW"] = seating[row+back][col+back] } } //SouthEast if col+forward < len(seating[col]) && row+forward < len(seating) && cardinalMap["SE"] == 0 { if seating[row+forward][col+forward] != Empty { cardinalMap["SE"] = seating[row+forward][col+forward] } } //NorthEast if col+forward < len(seating[col]) && row+back >= 0 && cardinalMap["NE"] == 0 { if seating[row+back][col+forward] != Empty { cardinalMap["NE"] = seating[row+back][col+forward] } } //SouthWest if row+forward < len(seating) && col+back >= 0 && cardinalMap["SW"] == 0 { if seating[row+forward][col+back] != Empty { cardinalMap["SW"] = seating[row+forward][col+back] } } } for _, occupied := range cardinalMap { if occupied == Occupied { adjacent++ } } return }
package test import ( "MainApplication/internal/Letter/LetterDelivery" "MainApplication/internal/Letter/LetterModel" "MainApplication/internal/Letter/LetterRepository" "MainApplication/internal/User/UserDelivery" "MainApplication/internal/User/UserModel" "MainApplication/internal/User/UserRepository" "MainApplication/internal/User/UserRepository/UserPostgres" "MainApplication/internal/User/UserUseCase" "MainApplication/internal/errors" "MainApplication/internal/pkg/context" "golang.org/x/crypto/bcrypt" "log" "net/http" "testing" ) func TestPasswordBcrypt(t *testing.T) { raw:="1538" enc:= UserPostgres.PasswordBcrypt([]byte(raw)) if bcrypt.CompareHashAndPassword(enc,[]byte(raw))!=nil{ log.Fatalf("error in PasswordBcrypt") } } func TestGenerateCSRF(t *testing.T) { csrf:= context.GenerateCSRF() if csrf==""{ log.Fatalf("error in GenerateCSRF") } } func TestGetUserOnUpdateError(t *testing.T) { err:= errors.GetUserOnUpdateError() if len(err)==0{ log.Fatalf("error in GetUserOnUpdateError") } } func TestUpdateProfileError(t *testing.T) { err:= errors.UpdateProfileError() if len(err)==0{ log.Fatalf("error in UpdateProfileError") } } func TestAddUserError(t *testing.T) { err:= errors.AddUserError() if len(err)==0{ log.Fatalf("error in AddUserError") } } func TestRemoveSessionError(t *testing.T) { err:= errors.RemoveSessionError() if len(err)==0{ log.Fatalf("error in RemoveSessionError") } } func TestGetAddSessionError(t *testing.T) { err:= errors.GetAddSessionError() if len(err)==0{ log.Fatalf("error in GetAddSessionError") } } func TestGetOkAnsData(t *testing.T) { err:= errors.GetOkAnsData("", UserModel.User{}) if len(err)==0{ log.Fatalf("error in GetOkAnsData") } } func TestGetOkAns(t *testing.T) { err:= errors.GetOkAns("") if len(err)==0{ log.Fatalf("error in GetOkAns") } } func TestGetErrorBadPasswordAns(t *testing.T) { err:= errors.GetErrorBadPasswordAns() if len(err)==0{ log.Fatalf("error in GetErrorBadPasswordAns") } } func TestGetErrorNoUserAns(t *testing.T) { err:= errors.GetErrorNoUserAns() if len(err)==0{ log.Fatalf("error in GetErrorNoUserAns") } } func TestGetErrorNotNumberAns(t *testing.T) { err:= errors.GetErrorNotNumberAns() if len(err)==0{ log.Fatalf("error in GetErrorNotNumberAns") } } func TestGetErrorNotPostAns(t *testing.T) { err:= errors.GetErrorNotPostAns() if len(err)==0{ log.Fatalf("error in GetErrorNotPostAns") } } func TestGetErrorWrongCookieAns(t *testing.T) { err:= errors.GetErrorWrongCookieAns() if len(err)==0{ log.Fatalf("error in GetErrorWrongCookieAns") } } func TestGetErrorNoCockyAns(t *testing.T) { err:= errors.GetErrorNoCockyAns() if len(err)==0{ log.Fatalf("error in GetErrorNoCockyAns") } } func TestGetErrorLoginExistAns(t *testing.T) { err:= errors.GetErrorLoginExistAns() if len(err)==0{ log.Fatalf("error in GetErrorLoginExistAns") } } func TestGetErrorBadJsonAns(t *testing.T) { err:= errors.GetErrorBadJsonAns() if len(err)==0{ log.Fatalf("error in GetErrorBadJsonAns") } } func TestGetErrorBadCsrfAns(t *testing.T) { err:= errors.GetErrorBadCsrfAns(UserRepository.GetSessionError) if len(err)==0{ log.Fatalf("error in GetErrorBadCsrfAns") } } func TestGetSendOkAns(t *testing.T) { err:= errors.GetSendOkAns(LetterModel.Letter{}) if len(err)==0{ log.Fatalf("error in GetSendOkAns") } } func TestGetGetLettersOkAns(t *testing.T) { err:= errors.GetGetLettersOkAns([]LetterModel.Letter{}) if len(err)==0{ log.Fatalf("error in GetGetLettersOkAns") } } func TestGetErrorReceivedLetterAns(t *testing.T) { err:= errors.GetErrorReceivedLetterAns() if len(err)==0{ log.Fatalf("error in GetErrorReceivedLetterAns") } } func TestGetErrorNoRecieverAns(t *testing.T) { err:= errors.GetErrorNoRecieverAns() if len(err)==0{ log.Fatalf("error in GetErrorNoRecieverAns") } } func TestGetErrorSaveErrorAns(t *testing.T) { err:= errors.GetErrorSaveErrorAns() if len(err)==0{ log.Fatalf("error in GetErrorSaveErrorAns") } } func TestProfileError(t *testing.T) { err:= UserDelivery.ProfileError(nil, &http.Cookie{}) if len(err)==0{ log.Fatalf("error in ProfileError") } err= UserDelivery.ProfileError(UserRepository.CantUpdateUser, &http.Cookie{}) if len(err)==0{ log.Fatalf("error in ProfileError") } err= UserDelivery.ProfileError(UserRepository.CantGetUserOnUpdate, &http.Cookie{}) if len(err)==0{ log.Fatalf("error in ProfileError") } } func TestLogoutError(t *testing.T) { err := UserDelivery.LogoutError(nil) if len(err) == 0 { log.Fatalf("error in LogoutError") } err = UserDelivery.LogoutError(UserRepository.InvalidSession) if len(err) == 0 { log.Fatalf("error in LogoutError") } err = UserDelivery.LogoutError(UserRepository.RemoveSessionError) if len(err) == 0 { log.Fatalf("error in LogoutError") } } func TestCookieError(t *testing.T) { err := UserDelivery.CookieError(401) if len(err) == 0 { log.Fatalf("error in CookieError") } err = UserDelivery.CookieError(402) if len(err) == 0 { log.Fatalf("error in CookieError") } } func TestSignInError(t *testing.T) { err := UserDelivery.SignInError(nil, &http.Cookie{}) if len(err) == 0 { log.Fatalf("error in SignInError") } err = UserDelivery.SignInError(UserRepository.CantAddSession, &http.Cookie{}) if len(err) == 0 { log.Fatalf("error in SignInError") } err = UserDelivery.SignInError(UserRepository.CantGetUserByEmail, &http.Cookie{}) if len(err) == 0 { log.Fatalf("error in SignInError") } err = UserDelivery.SignInError(UserRepository.GetSessionError, &http.Cookie{}) if len(err) == 0 { log.Fatalf("error in SignInError") } err = UserDelivery.SignInError(UserUseCase.WrongPasswordError, &http.Cookie{}) if len(err) == 0 { log.Fatalf("error in SignInError") } err = UserDelivery.SignInError(UserRepository.RemoveSessionError, &http.Cookie{}) if len(err) == 0 { log.Fatalf("error in SignInError") } } func TestSignUpError(t *testing.T) { err := UserDelivery.SignUpError(nil, &http.Cookie{}) if len(err) == 0 { log.Fatalf("error in SignUpError") } err = UserDelivery.SignUpError(UserRepository.EmailAlreadyExists, &http.Cookie{}) if len(err) == 0 { log.Fatalf("error in SignUpError") } err = UserDelivery.SignUpError(UserRepository.CantAddSession, &http.Cookie{}) if len(err) == 0 { log.Fatalf("error in SignUpError") } err = UserDelivery.SignUpError(UserRepository.CantAddUser, &http.Cookie{}) if len(err) == 0 { log.Fatalf("error in SignUpError") } } func TestGetLettersError(t *testing.T) { err := LetterDelivery.GetLettersError(nil, []LetterModel.Letter{}) if len(err) == 0 { log.Fatalf("error in GetLettersError") } err = LetterDelivery.GetLettersError(LetterRepository.ReceivedLetterError, []LetterModel.Letter{}) if len(err) == 0 { log.Fatalf("error in GetLettersError") } err = LetterDelivery.GetLettersError(LetterRepository.DbError, []LetterModel.Letter{}) if len(err) == 0 { log.Fatalf("error in GetLettersError") } err = LetterDelivery.GetLettersError(context.UserFromContextError, []LetterModel.Letter{}) if len(err) == 0 { log.Fatalf("error in GetLettersError") } } func TestSendLetterError(t *testing.T) { err := LetterDelivery.SendLetterError(nil, LetterModel.Letter{}) if len(err) == 0 { log.Fatalf("error in SendLetterError") } err = LetterDelivery.SendLetterError(LetterRepository.ReceiverNotFound, LetterModel.Letter{}) if len(err) == 0 { log.Fatalf("error in SendLetterError") } err = LetterDelivery.SendLetterError(LetterRepository.DbError, LetterModel.Letter{}) if len(err) == 0 { log.Fatalf("error in SendLetterError") } err = LetterDelivery.SendLetterError(LetterRepository.SaveLetterError, LetterModel.Letter{}) if len(err) == 0 { log.Fatalf("error in SendLetterError") } }
package initialization import ( "encoding/json" "errors" "fmt" "github.com/astaxie/beego" "github.com/astaxie/beego/logs" "os" ) var ( ConfCenterService = &ConfCenter{} log = &confCenterLog{} ) type ( ConfCenter struct { Addr string } confCenterLog struct { path string level string } ) func Init() error { initConfig() initLog() clearLog() return nil } func initConfig() { ConfCenterService.Addr = beego.AppConfig.String("confcenter_addr") if len(ConfCenterService.Addr) == 0 { logs.Error("read ConfCenter addr is null") panic(errors.New("read ConfCenter addr is null")) return } log.path = beego.AppConfig.String("log_path") if len(log.path) == 0 { logs.Error("read config log_path err ") panic(errors.New("read config log_path err ")) return } log.level = beego.AppConfig.String("log_level") if len(log.level) == 0 { logs.Error("read config log_level err") panic(errors.New("read config log_level err")) return } } func initLog() { err := initLogger(log.path, log.level) if err != nil { panic(err) return } } func clearLog() { os.Truncate(log.path, 0) } func convertLogLevel(level string) int { switch level { case "debug": return logs.LevelDebug case "warn": return logs.LevelWarn case "info": return logs.LevelInfo case "trace": return logs.LevelTrace } return logs.LevelDebug } func initLogger(logPath string, logLevel string) (err error) { config := make(map[string]interface{}) config["filename"] = logPath config["level"] = convertLogLevel(logLevel) configStr, err := json.Marshal(config) if err != nil { fmt.Println("initLogger failed, marshal err:", err) return } logs.SetLogger(logs.AdapterFile, string(configStr)) return }
package service_test import ( "context" "database/sql" "fmt" "testing" "boiler/pkg/entity" "boiler/pkg/errors" "boiler/pkg/service" "boiler/pkg/store" "boiler/pkg/store/config" "boiler/pkg/store/mock" "github.com/DATA-DOG/go-sqlmock" "github.com/golang/mock/gomock" "github.com/stretchr/testify/assert" ) func TestAddUser(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() m := mock.NewMockInterface(ctrl) srv := service.New(&config.Config{}, m, nil) var userID int64 = 99 name := "name" password := "pass" ctx := context.Background() // succeed { db, mdb, err := sqlmock.New() assert.Nil(t, err) defer db.Close() mdb.ExpectBegin() tx, err := db.Begin() assert.Nil(t, err) user := entity.User{ Name: name, Password: password, } m.EXPECT().Tx().Return(tx, nil) m. EXPECT(). AddUser(ctx, tx, &user). DoAndReturn(func(_ context.Context, _ *sql.Tx, u *entity.User) error { u.ID = userID return nil }) mdb.ExpectCommit() err = srv.AddUser(ctx, &user) assert.Nil(t, err) assert.Equal(t, userID, user.ID) assert.Nil(t, mdb.ExpectationsWereMet()) } // fails if Tx fails { opz := fmt.Errorf("opz") m.EXPECT().Tx().Return(nil, opz) user := entity.User{ Name: name, Password: password, } err := srv.AddUser(ctx, &user) assert.NotNil(t, err) assert.True(t, errors.Is(err, opz)) assert.Equal(t, err.Error(), "could not begin transaction; opz") } // fails if service fails { db, mdb, err := sqlmock.New() assert.Nil(t, err) defer db.Close() mdb.ExpectBegin() tx, err := db.Begin() assert.Nil(t, err) user := entity.User{ Name: name, Password: password, } m.EXPECT().Tx().Return(tx, nil) m. EXPECT(). AddUser(ctx, tx, &user). Return(fmt.Errorf("rollback")) mdb.ExpectRollback() err = srv.AddUser(ctx, &user) assert.NotNil(t, err) assert.Equal(t, err.Error(), "could not add user; rollback") assert.Nil(t, mdb.ExpectationsWereMet()) } // fails if service fails and rollback fails { db, mdb, err := sqlmock.New() assert.Nil(t, err) defer db.Close() mdb.ExpectBegin() tx, err := db.Begin() assert.Nil(t, err) user := entity.User{ Name: name, Password: password, } m.EXPECT().Tx().Return(tx, nil) m. EXPECT(). AddUser(ctx, tx, &user). Return(fmt.Errorf("rollback")) mdb.ExpectRollback().WillReturnError(fmt.Errorf("rollbackerr")) err = srv.AddUser(ctx, &user) assert.NotNil(t, err) assert.Equal(t, err.Error(), "could not add user; rollbackerr; rollback") assert.Nil(t, mdb.ExpectationsWereMet()) } // fails if commit fails { db, mdb, err := sqlmock.New() assert.Nil(t, err) defer db.Close() mdb.ExpectBegin() tx, err := db.Begin() assert.Nil(t, err) user := entity.User{ Name: name, Password: password, } m.EXPECT().Tx().Return(tx, nil) m. EXPECT(). AddUser(ctx, tx, &user). Return(nil) mdb.ExpectCommit().WillReturnError(fmt.Errorf("commit failed")) err = srv.AddUser(ctx, &user) assert.NotNil(t, err) assert.Equal(t, err.Error(), "could not add user; commit failed") assert.Nil(t, mdb.ExpectationsWereMet()) } } func TestDeleteUser(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() m := mock.NewMockInterface(ctrl) srv := service.New(&config.Config{}, m, nil) var userID int64 = 99 ctx := context.Background() // succeed { db, mdb, err := sqlmock.New() assert.Nil(t, err) defer db.Close() mdb.ExpectBegin() tx, err := db.Begin() assert.Nil(t, err) m.EXPECT().Tx().Return(tx, nil) m. EXPECT(). DeleteUser(ctx, tx, userID). Return(nil) m. EXPECT(). DeleteEmailsByUserID(ctx, tx, userID). Return(nil) mdb.ExpectCommit() err = srv.DeleteUser(ctx, userID) assert.Nil(t, err) assert.Nil(t, mdb.ExpectationsWereMet()) } // fails if Tx fails { m.EXPECT().Tx().Return(nil, fmt.Errorf("tx fails")) err := srv.DeleteUser(ctx, userID) assert.NotNil(t, err) assert.Equal(t, err.Error(), "could not begin delete user transaction; tx fails") } // DeleteUser fail { db, mdb, err := sqlmock.New() assert.Nil(t, err) defer db.Close() mdb.ExpectBegin() tx, err := db.Begin() assert.Nil(t, err) m.EXPECT().Tx().Return(tx, nil) m. EXPECT(). DeleteUser(ctx, tx, userID). Return(fmt.Errorf("deletefail")) mdb.ExpectRollback() err = srv.DeleteUser(ctx, userID) assert.NotNil(t, err) assert.Equal(t, "could not delete user; deletefail", err.Error()) assert.Nil(t, mdb.ExpectationsWereMet()) } // DeleteUser rollback fail { db, mdb, err := sqlmock.New() assert.Nil(t, err) defer db.Close() mdb.ExpectBegin() tx, err := db.Begin() assert.Nil(t, err) m.EXPECT().Tx().Return(tx, nil) m. EXPECT(). DeleteUser(ctx, tx, userID). Return(fmt.Errorf("deletefail")) mdb.ExpectRollback().WillReturnError(fmt.Errorf("rollbackfail")) err = srv.DeleteUser(ctx, userID) assert.NotNil(t, err) assert.Equal(t, "could not delete user; rollbackfail; deletefail", err.Error()) assert.Nil(t, mdb.ExpectationsWereMet()) } // DeleteEmail fail { db, mdb, err := sqlmock.New() assert.Nil(t, err) defer db.Close() mdb.ExpectBegin() tx, err := db.Begin() assert.Nil(t, err) m.EXPECT().Tx().Return(tx, nil) m. EXPECT(). DeleteUser(ctx, tx, userID). Return(nil) m. EXPECT(). DeleteEmailsByUserID(ctx, tx, userID). Return(fmt.Errorf("deletefail")) mdb.ExpectRollback() err = srv.DeleteUser(ctx, userID) assert.NotNil(t, err) assert.Equal(t, "could not delete user emails; deletefail", err.Error()) assert.Nil(t, mdb.ExpectationsWereMet()) } // DeleteEmail rollback fail { db, mdb, err := sqlmock.New() assert.Nil(t, err) defer db.Close() mdb.ExpectBegin() tx, err := db.Begin() assert.Nil(t, err) m.EXPECT().Tx().Return(tx, nil) m. EXPECT(). DeleteUser(ctx, tx, userID). Return(nil) errDeleteFail := errors.New("deletefail") m. EXPECT(). DeleteEmailsByUserID(ctx, tx, userID). Return(errDeleteFail) mdb.ExpectRollback().WillReturnError(errors.New("rollbackfail")) err = srv.DeleteUser(ctx, userID) assert.NotNil(t, err) assert.True(t, errors.Is(err, errDeleteFail)) assert.Equal(t, "could not delete user emails; rollbackfail; deletefail", err.Error()) assert.Nil(t, mdb.ExpectationsWereMet()) } // commit fail { db, mdb, err := sqlmock.New() assert.Nil(t, err) defer db.Close() mdb.ExpectBegin() tx, err := db.Begin() assert.Nil(t, err) m.EXPECT().Tx().Return(tx, nil) m. EXPECT(). DeleteUser(ctx, tx, userID). Return(nil) m. EXPECT(). DeleteEmailsByUserID(ctx, tx, userID). Return(nil) mdb.ExpectCommit().WillReturnError(fmt.Errorf("commitfail")) err = srv.DeleteUser(ctx, userID) assert.NotNil(t, err) assert.Equal(t, "could not commit delete user; commitfail", err.Error()) assert.Nil(t, mdb.ExpectationsWereMet()) } } func TestFilterUsersID(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() m := mock.NewMockInterface(ctrl) srv := service.New(&config.Config{}, m, nil) var userID int64 = 99 name := "name" filter := store.FilterUsers{Limit: 10} ctx := context.Background() // success { var IDs []int64 m. EXPECT(). FilterUsersID(ctx, filter, &IDs). DoAndReturn(func(_ context.Context, _ store.FilterUsers, ids *[]int64) error { *ids = append(*ids, userID) return nil }) m. EXPECT(). FetchUsers(ctx, []int64{userID}, gomock.Any()). DoAndReturn(func(_ context.Context, _ []int64, users *[]entity.User) error { *users = append(*users, entity.User{ ID: userID, Name: name, }) return nil }) var users []entity.User err := srv.FilterUsers(ctx, filter, &users) assert.Nil(t, err) assert.Len(t, users, 1) assert.Equal(t, users[0].ID, userID) assert.Equal(t, users[0].Name, name) } // fail { var IDs []int64 m. EXPECT(). FilterUsersID(ctx, filter, &IDs). Return(fmt.Errorf("opz")) var users []entity.User err := srv.FilterUsers(ctx, filter, &users) assert.Len(t, users, 0) assert.Equal(t, err.Error(), "opz") } } func TestGetUserByID(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() m := mock.NewMockInterface(ctrl) srv := service.New(&config.Config{}, m, nil) var userID int64 = 99 name := "userName" ctx := context.Background() // succeed { m. EXPECT(). FetchUsers(ctx, []int64{userID}, gomock.Any()). DoAndReturn(func(_ context.Context, ids []int64, users *[]entity.User) error { *users = []entity.User{ { ID: userID, Name: name, }, } return nil }) var user entity.User err := srv.GetUserByID(ctx, userID, &user) assert.Nil(t, err) assert.Equal(t, name, user.Name) assert.Equal(t, userID, user.ID) } // fails if storage fails { m. EXPECT(). FetchUsers(ctx, []int64{userID}, gomock.Any()). Return(fmt.Errorf("opz")) var user entity.User err := srv.GetUserByID(ctx, userID, &user) assert.NotNil(t, err) assert.Equal(t, err.Error(), "opz") } // fails if no user found { m. EXPECT(). FetchUsers(ctx, []int64{userID}, gomock.Any()). Return(nil) var user entity.User err := srv.GetUserByID(ctx, userID, &user) fmt.Println("?", err) assert.True(t, errors.Is(err, errors.ErrNotFound)) } } func TestGetUserByEmail(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() m := mock.NewMockInterface(ctrl) srv := service.New(&config.Config{}, m, nil) var userID int64 = 99 name := "userName" email := "contact@example.com" ctx := context.Background() // succeed { m. EXPECT(). FilterUsersID(ctx, store.FilterUsers{Email: email, Limit: service.FilterUsersDefaultLimit}, gomock.Any()). DoAndReturn(func(_ context.Context, _ store.FilterUsers, ids *[]int64) error { *ids = append(*ids, userID) return nil }) m. EXPECT(). FetchUsers(ctx, []int64{userID}, gomock.Any()). DoAndReturn(func(_ context.Context, ids []int64, users *[]entity.User) error { *users = append(*users, entity.User{ ID: userID, Name: name, }) return nil }) var user entity.User err := srv.GetUserByEmail(ctx, email, &user) assert.Nil(t, err) assert.NotNil(t, user) assert.Equal(t, userID, user.ID) assert.Equal(t, name, user.Name) } // fails if storage fails { m. EXPECT(). FilterUsersID(ctx, store.FilterUsers{Email: email, Limit: service.FilterUsersDefaultLimit}, gomock.Any()). Return(fmt.Errorf("opz")) var user entity.User err := srv.GetUserByEmail(ctx, email, &user) assert.NotNil(t, err) assert.Equal(t, err.Error(), "opz") } // fails if no user found { m. EXPECT(). FilterUsersID(ctx, store.FilterUsers{Email: email, Limit: service.FilterUsersDefaultLimit}, gomock.Any()). Return(nil) var user entity.User err := srv.GetUserByEmail(ctx, email, &user) assert.Equal(t, errors.ErrNotFound, err) } }
// DRUNKWATER TEMPLATE(add description and prototypes) // Question Title and Description on leetcode.com // Function Declaration and Function Prototypes on leetcode.com //46. Permutations //Given a collection of distinct integers, return all possible permutations. //Example: //Input: [1,2,3] //Output: //[ // [1,2,3], // [1,3,2], // [2,1,3], // [2,3,1], // [3,1,2], // [3,2,1] //] //func permute(nums []int) [][]int { //} // Time Is Money
package model type RedisConfig struct { Host string `mapstructure:"host"` Port int `mapstructure:"port"` Password string `mapstructure:"password"` } type PostgresConfig struct { Host string `mapstructure:"host"` Port int `mapstructure:"port"` User string `mapstructure:"user"` Password string `mapstructure:"password"` DbName string `mapstructure:"dbname"` PoolSize int `mapstructure:"pool_size"` Slow int `mapstructure:"slow"` } type ServerConfig struct { Host string `mapstructure:"host"` Port int `mapstructure:"port"` } type LogConfig struct { Level string `mapstructure:"level"` CustomLogName string `mapstructure:"custom_name"` AccessLogName string `mapstructure:"access_name"` } type AgolloConfig struct { AppId string `mapstructure:"appid"` ConfigServerURL string `mapstructure:"config_server_url"` } type Config struct { Server ServerConfig `mapstructure:"server"` Postgres PostgresConfig `mapstructure:"postgres"` Redis RedisConfig `mapstructure:"redis"` Log LogConfig `mapstructure:"log"` AgolloConfig AgolloConfig `mapstructure:"agollo"` }
package viewmodel // Home struct type Home struct { Title string Active string Alert string AlertMessage string AlertDanger string AlertSuccess string } // NewHome function func NewHome() Home { result := Home{ Active: "home", Title: "Lemonade Stand Supply", Alert: "invisible", } return result }
package coordinator import ( "errors" "net/rpc" "os" "path/filepath" "sync" "time" "github.com/golang/protobuf/proto" "github.com/hashicorp/raft" "github.com/raft-kv-store/common" "github.com/raft-kv-store/config" "github.com/raft-kv-store/raftpb" log "github.com/sirupsen/logrus" ) const ( // TransactionTimeout ... TransactionTimeout = 5 // RecoveryInterval ... RecoveryInterval = 60 ) const ( // FailPrepared indicates the transaction to fail after the prepare phase FailPrepared = "prepared" // FailCommit indicates the transaction to fail after the commit phase FailCommit = "commit" ) // Coordinator ... type Coordinator struct { ID string RaftAddress string RaftDir string raft *raft.Raft // The consensus mechanism // coordinator state - This has to be replicated. // TODO: concurrent transactions txMap map[string]*raftpb.GlobalTransaction mu sync.RWMutex // ShardToPeers need to be populated based on a config. // If time permits, these can be auto-discovered. ShardToPeers map[int64][]string Client *rpc.Client log *log.Entry failmode string } // NewCoordinator initialises the new coordinator instance func NewCoordinator(logger *log.Logger, nodeID, raftDir, raftAddress string, enableSingle bool, failmode string) *Coordinator { if nodeID == "" { nodeID = "node-" + common.RandNodeID(common.NodeIDLen) } if raftDir == "" { raftDir, _ = os.Hostname() } log := logger.WithField("component", "coordinator") coordDir := filepath.Join(common.RaftPVBaseDir, raftDir, "coords") log.Infof("Preparing node-%s with persistent directory %s, raftAddress %s", nodeID, coordDir, raftAddress) os.MkdirAll(coordDir, 0700) shardsInfo, err := config.GetShards() if err != nil { log.Fatal(err) } shardToPeers := make(map[int64][]string) for i, shard := range shardsInfo.Shards { shardToPeers[int64(i)] = append(shardToPeers[int64(i)], shard...) } c := &Coordinator{ ID: nodeID, RaftAddress: raftAddress, RaftDir: coordDir, ShardToPeers: shardToPeers, txMap: make(map[string]*raftpb.GlobalTransaction), log: log, failmode: failmode, } ra, err := common.SetupRaft((*fsm)(c), c.ID, c.RaftAddress, c.RaftDir, enableSingle) if err != nil { log.Fatalf("Unable to setup raft instance for kv store:%s", err) } c.raft = ra go c.periodicRecovery() log.Info("Starting coordniator") return c } // periodicRecovery Runs periodically or on raft status changes. func (c *Coordinator) periodicRecovery() { for { select { case <-c.raft.LeaderCh(): c.log.Infof("Leader Change") case <-time.After(time.Duration(RecoveryInterval) * time.Second): } // Do this safety check if c.IsLeader() && len(c.txMap) > 0 { c.log.Infof("Starting Transaction Recovery") c.recoverTransactions() } } } // recoverTransactions traverses the entire txid map and // takes below actions. This is similar to garbage collection aka // stop the world func (c *Coordinator) recoverTransactions() { c.mu.Lock() defer c.mu.Unlock() var err error for txid, gt := range c.txMap { // 3 phases // if transaction is not complete in 3 minutes if time.Since(time.Unix(0, gt.StartTime)).Seconds() >= TransactionTimeout { c.log.Infof("[txid: %s] is in phase :%s", txid, gt.GetPhase()) switch gt.GetPhase() { case common.Prepare, common.Abort: err = c.RetryAbort(txid, gt) if err != nil { c.log.Errorf("[txid: %s] recovery unsuccessfull :%s", txid, err) } case common.Prepared, common.Commit: err = c.RetryCommit(txid, gt) if err != nil { c.log.Errorf("[txid: %s] recovery unsuccessfull :%s", txid, err) } case common.Aborted, common.Committed: delete(c.txMap, txid) } } } } // Replicate replicates put/get/deletes on coordinator's // state machine func (c *Coordinator) Replicate(key, op string, gt *raftpb.GlobalTransaction) error { var cmd *raftpb.RaftCommand switch op { case common.SET: cmd = &raftpb.RaftCommand{ Commands: []*raftpb.Command{ { Method: op, Key: key, Gt: gt, }, }, } case common.DEL: cmd = &raftpb.RaftCommand{ Commands: []*raftpb.Command{ { Method: op, Key: key, }, }, } } b, err := proto.Marshal(cmd) if err != nil { return err } f := c.raft.Apply(b, common.RaftTimeout) return f.Error() } // IsLeader return if coordinator is leader of cluster. func (c *Coordinator) IsLeader() bool { return c.raft.State() == raft.Leader } func (c *Coordinator) FindClusterLeader() (string, error) { // (If time permits): Make RPC calls to modify default leader behavior to fetch the host name of the leader leader := string(c.raft.Leader()) if leader == "" { c.log.Info("Raft coordinator leader unavailable for now") return "", errors.New("no leader available") } return leader, nil }
package httpd import ( "fmt" "log" "net" "net/http" "os" "strings" "github.com/messagedb/messagedb/cluster" "github.com/messagedb/messagedb/db" "github.com/messagedb/messagedb/meta" "github.com/messagedb/messagedb/services/httpd/controllers" "github.com/messagedb/messagedb/services/httpd/middleware" "github.com/gin-gonic/contrib/gzip" "github.com/gin-gonic/gin" "github.com/itsjamie/gin-cors" "golang.org/x/net/netutil" ) // Service manages the listener and handler for an HTTP endpoint. type Service struct { listener net.Listener addr string err chan error maxConn int router *gin.Engine Version string PingController *controllers.PingController SessionController *controllers.SessionController UsersController *controllers.UsersController DevicesController *controllers.DevicesController OrganizationsController *controllers.OrganizationsController ConversationsController *controllers.ConversationsController MessagesController *controllers.MessagesController Logger *log.Logger } // NewService returns a new instance of Service. func NewService(c Config) *Service { s := &Service{ addr: c.BindAddress, err: make(chan error), router: NewRouter(), maxConn: c.MaxConnections, Logger: log.New(os.Stderr, "[httpd] ", log.LstdFlags), } s.PingController = s.setupPingController(c) s.SessionController = s.setupSessionController(c) s.UsersController = s.setupUsersController(c) s.DevicesController = s.setupDevicesController(c) s.OrganizationsController = s.setupOrganizationsController(c) s.ConversationsController = s.setupConversationsController(c) s.MessagesController = s.setupMessagesController(c) return s } func (s *Service) SetMetaStore(metaStore *meta.Store) { s.SessionController.MetaStore = metaStore s.UsersController.MetaStore = metaStore s.DevicesController.MetaStore = metaStore s.OrganizationsController.MetaStore = metaStore s.ConversationsController.MetaStore = metaStore s.MessagesController.MetaStore = metaStore } func (s *Service) SetDataStore(dataStore *db.Store) { s.MessagesController.DataStore = dataStore } func (s *Service) SetQueryExecutor(executor *db.QueryExecutor) { s.MessagesController.QueryExecutor = executor } func (s *Service) SetMessagesWriter(writer *cluster.MessagesWriter) { s.MessagesController.MessagesWriter = writer } func (s *Service) setupPingController(config Config) *controllers.PingController { c := controllers.NewPingController(s.router, config.LogEnabled, config.WriteTracing) c.Logger = s.Logger return c } func (s *Service) setupSessionController(config Config) *controllers.SessionController { c := controllers.NewSessionController(s.router, config.LogEnabled, config.WriteTracing) c.Logger = s.Logger return c } func (s *Service) setupUsersController(config Config) *controllers.UsersController { c := controllers.NewUsersController(s.router, config.LogEnabled, config.WriteTracing) c.Logger = s.Logger return c } func (s *Service) setupDevicesController(config Config) *controllers.DevicesController { c := controllers.NewDevicesController(s.router, config.LogEnabled, config.WriteTracing) c.Logger = s.Logger return c } func (s *Service) setupOrganizationsController(config Config) *controllers.OrganizationsController { c := controllers.NewOrganizationsController(s.router, config.LogEnabled, config.WriteTracing) c.Logger = s.Logger return c } func (s *Service) setupConversationsController(config Config) *controllers.ConversationsController { c := controllers.NewConversationsController(s.router, config.LogEnabled, config.WriteTracing) c.Logger = s.Logger return c } func (s *Service) setupMessagesController(config Config) *controllers.MessagesController { c := controllers.NewMessagesController(s.router, config.LogEnabled, config.WriteTracing) c.Logger = s.Logger return c } // Open starts the service func (s *Service) Open() error { // Open listener. listener, err := net.Listen("tcp", s.addr) if err != nil { return err } s.listener = netutil.LimitListener(listener, s.maxConn) s.Logger.Println("listening on HTTP:", listener.Addr().String()) // Begin listening for requests in a separate goroutine. go s.serve() return nil } // Close closes the underlying listener. func (s *Service) Close() error { if s.listener != nil { return s.listener.Close() } return nil } // SetLogger sets the internal logger to the logger passed in. func (s *Service) SetLogger(l *log.Logger) { s.Logger = l } // Err returns a channel for fatal errors that occur on the listener. func (s *Service) Err() <-chan error { return s.err } // Addr returns the listener's address. Returns nil if listener is closed. func (s *Service) Addr() net.Addr { if s.listener != nil { return s.listener.Addr() } return nil } // serve serves the handler from the listener. func (s *Service) serve() { // The listener was closed so exit // See https://github.com/golang/go/issues/4373 err := http.Serve(s.listener, s.router) if err != nil && !strings.Contains(err.Error(), "closed") { s.err <- fmt.Errorf("listener failed: addr=%s, err=%s", s.Addr(), err) } } func NewRouter() *gin.Engine { gin.SetMode(gin.ReleaseMode) router := gin.Default() router.RedirectTrailingSlash = true router.RedirectFixedPath = true router.Use(gzip.Gzip(gzip.DefaultCompression)) router.Use(middleware.ContentTypeCheckerMiddleware()) router.Use(middleware.RequestIdMiddleware()) router.Use(middleware.RevisionMiddleware()) router.Use(cors.Middleware(cors.Config{ Origins: "*", Methods: "GET, PUT, POST, DELETE, PATCH, OPTIONS", RequestHeaders: "Origin, Authorization, Content-Type", ExposedHeaders: "", MaxAge: 1728000, Credentials: true, ValidateHeaders: false, })) return router }
package main import ( "os/exec" "fmt" "time" "os" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/s3/s3manager" ) const path = "/var/lib/postgresql/" func fullPath(filename string) string { return fmt.Sprintf("%s/%s", path, filename) } func uploadToS3(filename string) { fmt.Println("Enviando backup ao S3...") sess := session.Must(session.NewSession(&aws.Config{ Region: aws.String(os.Getenv("AWS_REGION")), })) uploader := s3manager.NewUploader(sess) file, err := os.Open(fullPath(filename)) if err != nil { fmt.Println(err) return } result, err := uploader.Upload(&s3manager.UploadInput{ Bucket: aws.String(os.Getenv("AWS_BUCKET")), Key: aws.String(filename), Body: file, }) defer file.Close() if err != nil { fmt.Println(err) return } fmt.Println(result) } func main() { cmd := "su" arg0 := "-" arg1 := "postgres" arg2 := "-c" user := os.Getenv("PSQL_BACKUP_USER") db := os.Getenv("PSQL_BACKUP_DB") filename := fmt.Sprintf("pg-%d.dump", time.Now().Unix()) arg3 := fmt.Sprintf("pg_dump -U %s -w %s > %s", user, db, fullPath(filename)) fmt.Println("Criando backup", filename) exec.Command(cmd, arg0, arg1, arg2, arg3).Output() uploadToS3(filename) }
package utils import ( "encoding/json" "gopkg.in/gomail.v2" "io/ioutil" ) type Mailclient struct { mc *gomail.Dialer //mc Mail Dialer Client } type MailInfo struct { User string `json:"user"` //发件人邮箱 Pass string `json:"pass"` //发件人邮箱密码 Host string `json:"host"` //发件邮箱 Port string `json:"port"` //邮箱端口 } func ParseMailconf(fpath string) (Mi MailInfo, err error) { Mi = MailInfo{} b, err := ioutil.ReadFile(fpath) if err != nil { return } err = json.Unmarshal(b, &Mi) return } func ParseMailbody(fpath string) (str string, err error) { b, err := ioutil.ReadFile(fpath) if err != nil { return } str = string(b) return }
package p07 func toLowerCase(str string) string { s := make([]byte, len(str)) for i := 0; i < len(str); i++ { v := str[i] if v <= 'Z' && v >= 'A' { v = v + 'a' - 'A' } s[i] = v } return string(s) }
package main /* import ( "bytes" "encoding/binary" "time" ) func csLogin(csId, maxConn string) { csIdLen := make([]byte, 4) binary.BigEndian.PutUint32(csIdLen, uint32(len(csId))) maxConnLen := make([]byte, 4) binary.BigEndian.PutUint32(maxConnLen, uint32(len(maxConn))) data := new(bytes.Buffer) data.Write(csIdLen) data.Write(maxConnLen) data.WriteString(csId) data.WriteString(maxConn) mapCses.write(csId, pack(byte(1), CS_LOGIN, nums[CS_LOGIN], data.Bytes())) } func csAway(csId string) { csIdLen := make([]byte, 4) binary.BigEndian.PutUint32(csIdLen, uint32(len(csId))) data := new(bytes.Buffer) data.Write(csIdLen) data.WriteString(csId) mapCses.write(csId, pack(byte(1), CS_AWAY, nums[CS_AWAY], data.Bytes())) } func csBack(csId string) { csIdLen := make([]byte, 4) binary.BigEndian.PutUint32(csIdLen, uint32(len(csId))) data := new(bytes.Buffer) data.Write(csIdLen) data.WriteString(csId) mapCses.write(csId, pack(byte(1), CS_BACK, nums[CS_BACK], data.Bytes())) } func csHungup(csId, usrId string) { csIdLen := make([]byte, 4) binary.BigEndian.PutUint32(csIdLen, uint32(len(csId))) usrIdLen := make([]byte, 4) binary.BigEndian.PutUint32(usrIdLen, uint32(len(usrId))) data := new(bytes.Buffer) data.Write(csIdLen) data.Write(usrIdLen) data.WriteString(csId) data.WriteString(usrId) mapCses.write(csId, pack(byte(1), CS_HUNGUP, nums[CS_HUNGUP], data.Bytes())) } func csLogout(csId string) { csIdLen := make([]byte, 4) binary.BigEndian.PutUint32(csIdLen, uint32(len(csId))) data := new(bytes.Buffer) data.Write(csIdLen) data.WriteString(csId) mapCses.write(csId, pack(byte(1), CS_LOGOUT, nums[CS_LOGOUT], data.Bytes())) } func csAccept(csId, usrId string) { csIdLen := make([]byte, 4) binary.BigEndian.PutUint32(csIdLen, uint32(len(csId))) usrIdLen := make([]byte, 4) binary.BigEndian.PutUint32(usrIdLen, uint32(len(usrId))) data := new(bytes.Buffer) data.Write(csIdLen) data.Write(usrIdLen) data.WriteString(csId) data.WriteString(usrId) mapCses.write(csId, pack(byte(1), CS_ACCEPT, nums[CS_ACCEPT], data.Bytes())) } func csAnswer(csId, usrId, content string) bool { csIdLen := make([]byte, 4) binary.BigEndian.PutUint32(csIdLen, uint32(len(csId))) usrIdLen := make([]byte, 4) binary.BigEndian.PutUint32(usrIdLen, uint32(len(usrId))) contentLen := make([]byte, 4) binary.BigEndian.PutUint32(contentLen, uint32(len(content))) data := new(bytes.Buffer) data.Write(csIdLen) data.Write(usrIdLen) data.Write(contentLen) data.WriteString(csId) data.WriteString(usrId) data.WriteString(content) return mapCses.write(csId, pack(byte(1), CS_ANSWER, nums[CS_ANSWER], data.Bytes())) } func csNidReq(csId, usrId, Type string) { csIdLen := make([]byte, 4) binary.BigEndian.PutUint32(csIdLen, uint32(len(csId))) usrIdLen := make([]byte, 4) binary.BigEndian.PutUint32(usrIdLen, uint32(len(usrId))) typeLen := make([]byte, 4) binary.BigEndian.PutUint32(typeLen, uint32(len(Type))) data := new(bytes.Buffer) data.Write(csIdLen) data.Write(usrIdLen) data.Write(typeLen) data.WriteString(csId) data.WriteString(usrId) data.WriteString(Type) mapCses.write(csId, pack(byte(1), CS_NID_REQ, nums[CS_NID_REQ], data.Bytes())) } func csFeedbackReq(csId, usrId string) { csIdLen := make([]byte, 4) binary.BigEndian.PutUint32(csIdLen, uint32(len(csId))) usrIdLen := make([]byte, 4) binary.BigEndian.PutUint32(usrIdLen, uint32(len(usrId))) data := new(bytes.Buffer) data.Write(csIdLen) data.Write(usrIdLen) data.WriteString(csId) data.WriteString(usrId) mapCses.write(csId, pack(byte(1), CS_FEEDBACK_REQ, nums[CS_FEEDBACK_REQ], data.Bytes())) } func csLineStatus(csId string) { csIdLen := make([]byte, 4) binary.BigEndian.PutUint32(csIdLen, uint32(len(csId))) data := new(bytes.Buffer) data.Write(csIdLen) data.WriteString(csId) for { rs := mapCses.write(csId, pack(byte(1), CS_LINE_STATUS, nums[CS_LINE_STATUS], data.Bytes())) if !rs { break } time.Sleep(5 * time.Second) } } func csDispatchReq(csId, usrId, gameId, history string) { csIdLen := make([]byte, 4) binary.BigEndian.PutUint32(csIdLen, uint32(len(csId))) usrIdLen := make([]byte, 4) binary.BigEndian.PutUint32(usrIdLen, uint32(len(usrId))) gameIdLen := make([]byte, 4) binary.BigEndian.PutUint32(gameIdLen, uint32(len(gameId))) historyLen := make([]byte, 4) binary.BigEndian.PutUint32(historyLen, uint32(len(history))) data := new(bytes.Buffer) data.Write(csIdLen) data.Write(usrIdLen) data.Write(gameIdLen) data.Write(historyLen) data.WriteString(csId) data.WriteString(usrId) data.WriteString(gameId) data.WriteString(history) mapCses.write(csId, pack(byte(1), CS_DISPATCH_REQ, nums[CS_DISPATCH_REQ], data.Bytes())) } func csDispatchAccpet(usrId, csId string) { csIdLen := make([]byte, 4) binary.BigEndian.PutUint32(csIdLen, uint32(len(csId))) usrIdLen := make([]byte, 4) binary.BigEndian.PutUint32(usrIdLen, uint32(len(usrId))) data := new(bytes.Buffer) data.Write(csIdLen) data.Write(usrIdLen) data.WriteString(csId) data.WriteString(usrId) mapCses.write(csId, pack(byte(1), CS_DISPATCH_ACCEPT, nums[CS_DISPATCH_ACCEPT], data.Bytes())) } */
package main import "fmt" func main() { //普通for循环 var arr = [...]int{1, 2, 3, 4, 5} slice := arr[1:4] for i := 0; i < len(slice); i++ { fmt.Printf("slice[%v]=%v\n", i, slice[i]) } //增强for循环 for i, val := range slice { fmt.Printf("slice[%v]=%v\n", i, val) } //================================================== }
package database import ( "BackendGo/models" "fmt" "github.com/google/uuid" "gorm.io/gorm" "os" ) const ( DbDriverEnvVar = "DB_DRIVER" DriverPostgres = "postgres" DriverSqlite = "sqlite" ) type Database struct { *gorm.DB Config map[string]string } const ( User1UUID = "4d365568-d3ac-4880-8403-8d4e2638e008" User2UUID = "1d149631-4141-4be4-9244-cfd78afbfc57" ) var ( User1Exporters = []string{ "c9bb3e99-df72-4603-b188-b6f856f0ef9f", "8d4c8325-a1c6-4bb1-b50d-dc7f7d92a5b5", } User2Exporters = []string{ "ba720cfd-33dc-45c8-9879-7038a965ca18", } ) // driver: Type to quickly change database with correct environment variables and init database function. type driver struct { EnvVars map[string]string InitFct func(d *Database) error } // DriverMap: for each DB_DRIVER, contains necessary environment variables to load and associated database initialisation function // database.initPostGreSql var DriverMap = map[string]driver{ DriverPostgres: { EnvVars: map[string]string{ "DB_NAME": "", "DB_HOST": "", "DB_PORT": "", "DB_USER": "", "DB_PASSWORD": "", }, InitFct: func(d *Database) error { return d.initPostGreSql() }, }, DriverSqlite: { EnvVars: map[string]string{ "DB_NAME": "", }, InitFct: func(d *Database) error { return d.initSqlite() }, }, } // Initialise GormDatabase func (db *Database) Init() error { dbInitFct, err := db.getConfig() if err != nil { return err } if err = dbInitFct(db); err != nil { return fmt.Errorf("failed to initialize GormDatabase: %v", err) } if err = db.autoMigrate(); err != nil { return err } return db.DefaultsUsers() } // Create Defaults User with mock up Data // TODO: Remove when User Register up and running func (db Database) DefaultsUsers() (err error) { if err = db.FindOrCreateDefaultUsers("user_1", "pass_1", User1UUID, User1Exporters); err != nil { return err } if err = db.FindOrCreateDefaultUsers("user_2", "pass_2", User2UUID, User2Exporters); err != nil { return err } return nil } // Helper function to create default users func (db Database) FindOrCreateDefaultUsers(login, pass, UUID string, exporters []string) (err error) { Uuid := uuid.UUID{} if Uuid, err = uuid.Parse(UUID); err != nil { return err } user := models.User{ UUID: Uuid, Login: login, Password: pass, } for _, exporter := range exporters { if Uuid, err = uuid.Parse(exporter); err != nil { return err } user.Exporters = append(user.Exporters, models.Exporter{ UUID: Uuid, }) } if err = user.FindByUUID(db.DB); err != nil { if err = user.Create(db.DB); err != nil { return err } } return nil } // autoMigrate: Auto migrate models func (db *Database) autoMigrate() (err error) { // GormDatabase migration if err = db.DB.Debug().AutoMigrate(&models.User{}); err != nil { return err } if err = db.DB.Debug().AutoMigrate(&models.Exporter{}); err != nil { return err } return nil } // getConfig: Load env from .env file (development) or deployment env func (db *Database) getConfig() (func(*Database) error, error) { driverEnvVar := os.Getenv(DbDriverEnvVar) if driverEnvVar == "" { return nil, fmt.Errorf("environment variable missing : %s", DbDriverEnvVar) } driverHandler, ok := DriverMap[driverEnvVar] if !ok { return nil, fmt.Errorf("no driver found for : %s", DbDriverEnvVar) } db.Config = driverHandler.EnvVars var value string for envVar := range db.Config { if value = os.Getenv(envVar); value == "" { return nil, fmt.Errorf("environment variable missing : %s", envVar) } db.Config[envVar] = value } return driverHandler.InitFct, nil }
package bigsum import ( "bufio" "fmt" "os" "strconv" ) func main() { scan := bufio.NewScanner(os.Stdin) scan.Split(bufio.ScanWords) scan.Scan() cnt, _ := strconv.Atoi(scan.Text()) var sum int64 for i := 0; i < cnt; i++ { scan.Scan() j, _ := strconv.ParseInt(scan.Text(), 10, 64) sum += j } fmt.Println(sum) }
package 动态规划 func numWays(n int) int { const givenMaxStep = 100 const givenMod = 1000000007 jumpWays := getJumpWays(givenMod, givenMaxStep) return jumpWays[n] } func getJumpWays(mod int, maxStep int) []int { jumpWays := make([]int, maxStep+1) initialJumpWays(jumpWays) formJumpWays(jumpWays, mod) return jumpWays } func initialJumpWays(jumpWays []int) { jumpWays[0] = 1 jumpWays[1] = 1 } func formJumpWays(jumpWays []int, mod int) { for i := 2; i <= len(jumpWays)-1; i++ { jumpWays[i] = (jumpWays[i-1] + jumpWays[i-2]) % mod } } /* 题目链接:https://leetcode-cn.com/problems/qing-wa-tiao-tai-jie-wen-ti-lcof/ */
package util import ( "bufio" "bytes" "io" "math/rand" "os" "path/filepath" "strings" ) var ( fileBuffer = 32 * 1024 filesMode = os.FileMode(0666) filesEndLineDelimiter = byte('\n') defaultApplicationFolder = ".curlson" ) // Counts the number of lines in a given file. // In case property 'templateEnabled' is false (i.e templating is disabled) either there is an error occurred while reading a file // the result '-1' will be returned func CountLinesForFile(file *os.File) int { var reader = bufio.NewReader(file) var buffer = make([]byte, fileBuffer) var count = 0 var line = []byte{filesEndLineDelimiter} for { var c, err = reader.Read(buffer) count += bytes.Count(buffer[:c], line) switch { case err == io.EOF: return count case err != nil: return -1 } } } func ReadRandomLine(templateFile string, linesCount int) (int, string) { var lineNum = rand.Intn(linesCount) return lineNum, ReadLine(templateFile, lineNum) } func ReadLine(templateFile string, lineNumber int) string { var counter = -1 var file, _ = os.OpenFile(templateFile, os.O_RDONLY, filesMode) defer file.Close() var reader = bufio.NewReader(file) for { counter++ if counter == lineNumber { var line, _ = reader.ReadString(filesEndLineDelimiter) return strings.TrimSuffix(line, string(filesEndLineDelimiter)) } else { var _, _ = reader.ReadString(filesEndLineDelimiter) } } } // Returns a boolean indicating whether file with given path exist func fileExist(path string) bool { if stats, isNotExistErr := os.Stat(path); !os.IsNotExist(isNotExistErr) { return !stats.IsDir() } else { return false } } // Returns a boolean indicating whether directory with given path exist func directoryExist(path string) bool { if stats, isNotExistErr := os.Stat(path); !os.IsNotExist(isNotExistErr) { return stats.IsDir() } else { return false } } func getApplicationDirectory() (string, error) { var homeDir, errHomeDir = os.UserHomeDir() if errHomeDir != nil { return "", errHomeDir } else { var defaultFolderPath = filepath.Join(homeDir, defaultApplicationFolder) if !directoryExist(defaultFolderPath) { var mkdirErr = os.Mkdir(defaultFolderPath, os.ModePerm) if mkdirErr != nil { return "", mkdirErr } } return defaultFolderPath, nil } }
package main import ( "log" "os" "github.com/urfave/cli" ) const ( defaultEthernetConfig = "ethernet@%s.json" defaultWifiClientConfig = "wifi-client@%s.json" defaultAccessPointConfig = "access-point@%s.json" defaultFougGConfig = "4g-ndis@%s.json" defaultThreeGGConfig = "3g-ras@%s.json" defaultVoiceChanConfig = "voice-channel@%s.json" ) func main() { app := cli.NewApp() app.Version = "0.4.10" app.Name = "fconf" app.Usage = "fessbox configuration manager" app.Commands = []cli.Command{ { Name: "ethernet", Aliases: []string{"e"}, Usage: "configures ethernet with systemd", Flags: []cli.Flag{ cli.StringFlag{ Name: "name", Usage: "The name of the unit file", Value: ethernetService, }, cli.StringFlag{ Name: "dir", Usage: "The directory in which to write the file", Value: networkBase, }, cli.StringFlag{ Name: "config", Usage: "The path to the json configuration file", Value: defaultEthernetConfig, }, cli.BoolFlag{ Name: "enable", Usage: "Enables ethernet", }, cli.BoolFlag{ Name: "disable", Usage: "Disable ethernet", }, cli.BoolFlag{ Name: "remove", Usage: "Remove ethernet", }, }, Action: EthernetCMD, }, { Name: "4g-ndis", Aliases: []string{"4g"}, Usage: "configures 4G with systemd", Flags: []cli.Flag{ cli.StringFlag{ Name: "name", Usage: "The name of the unit file", Value: fourgService, }, cli.StringFlag{ Name: "dir", Usage: "The directory in which to write the file", Value: networkBase, }, cli.StringFlag{ Name: "config", Usage: "The path to the json configuration file", Value: defaultFougGConfig, }, cli.BoolFlag{ Name: "enable", Usage: "Enables 4G", }, cli.BoolFlag{ Name: "disable", Usage: "Disable 4G", }, cli.BoolFlag{ Name: "remove", Usage: "Remove 4G", }, }, Action: FourgCMD, }, { Name: "3g-ras", Aliases: []string{"3g"}, Usage: "configures 3G ", Flags: []cli.Flag{ cli.StringFlag{ Name: "name", Usage: "The name of the config file", Value: threeGService, }, cli.StringFlag{ Name: "dir", Usage: "The directory in which to write the file", Value: apConfigBase, }, cli.StringFlag{ Name: "config", Usage: "The path to the json configuration file", }, cli.BoolFlag{ Name: "enable", Usage: "Enables 3G", }, cli.BoolFlag{ Name: "disable", Usage: "Disable 3G", }, cli.BoolFlag{ Name: "remove", Usage: "Remove 3G", }, }, Action: ThreegCMD, }, { Name: "wifi-client", Aliases: []string{"w"}, Usage: "configures wifi client with systemd", Flags: []cli.Flag{ cli.StringFlag{ Name: "name", Usage: "The name of the unit file", Value: wirelessService, }, cli.StringFlag{ Name: "dir", Usage: "The directory in which to write the file", Value: networkBase, }, cli.StringFlag{ Name: "config", Usage: "The path to the json configuration file", Value: defaultWifiClientConfig, }, cli.BoolFlag{ Name: "enable", Usage: "Enables wifi", }, cli.BoolFlag{ Name: "disable", Usage: "Disable wifi", }, cli.BoolFlag{ Name: "remove", Usage: "Remove wifi", }, }, Action: WifiClientCMD, }, { Name: "access-point", Aliases: []string{"a"}, Usage: "configures access point with systemd", Flags: []cli.Flag{ cli.StringFlag{ Name: "name", Usage: "The name of the unit file", Value: apConfigFile, }, cli.StringFlag{ Name: "dir", Usage: "The directory in which to write the file", Value: apConfigBase, }, cli.StringFlag{ Name: "config", Usage: "The path to the json configuration file", Value: defaultAccessPointConfig, }, cli.BoolFlag{ Name: "enable", Usage: "Enables access point", }, cli.BoolFlag{ Name: "disable", Usage: "Disable access point", }, cli.BoolFlag{ Name: "remove", Usage: "Remove access point", }, }, Action: ApCMD, }, { Name: "voice-channel", Aliases: []string{"v"}, Usage: "configures voice channel for 3g dongle", Flags: []cli.Flag{ cli.StringFlag{ Name: "config", Usage: "The path to the json configuration file", }, cli.BoolFlag{ Name: "enable", Usage: "Enables access point", }, cli.BoolFlag{ Name: "disable", Usage: "Disable access point", }, cli.BoolFlag{ Name: "remove", Usage: "Remove access point", }, }, Action: VoiceChannelCMD, }, { Name: "list-interface", Aliases: []string{"i"}, Usage: "prints a json array of all interfaces", Action: ListInterface, }, } app.Flags = []cli.Flag{ cli.StringFlag{ Name: "interface", Usage: "the interface", }, cli.IntFlag{ Name: "pid", Usage: "process id to send SIGHUP to", }, } err := app.Run(os.Args) if err != nil { log.Fatalf("fconf: %v", err) } }
package chart import ( "github.com/jchavannes/jgo/jerr" "time" ) type ChartItem struct { Name string ChartDataPoints []*ChartDataPoint } func (i *ChartItem) GetDataPoint(timestamp time.Time) (*ChartDataPoint, error) { for _, chartDataPoint := range i.ChartDataPoints { if chartDataPoint.Timestamp == timestamp { return chartDataPoint, nil } } return nil, jerr.New("Unable to find data point") } type ChartDataPoint struct { Timestamp time.Time Amount float32 } type ChartDataPointSorter []*ChartDataPoint func (c ChartDataPointSorter) Len() int { return len(c) } func (c ChartDataPointSorter) Swap(i, j int) { c[i], c[j] = c[j], c[i] } func (c ChartDataPointSorter) Less(i, j int) bool { return c[i].Timestamp.Unix() < c[j].Timestamp.Unix() }
package cmd import ( "fmt" "os" "strings" "github.com/spf13/cobra" "github.com/spf13/pflag" "github.com/spf13/viper" ) var ( cfgFile string logLevel string prefix = "pbnj" ) // rootCmd represents the base command when called without any subcommands. var rootCmd = &cobra.Command{ Use: "pbnj", Short: "PBnJ does all your power, boot and jelly goodness for your BMCs", Long: `PBnJ is a CLI that provides a gRPC interfaces for interacting with Out-of-Band controllers/BMCs.`, PersistentPreRunE: func(cmd *cobra.Command, args []string) error { return initConfig(cmd) }, } // NewRootCmd is used for testing to run the server. func NewRootCmd() *cobra.Command { return rootCmd } // Execute adds all child commands to the root command and sets flags appropriately. // This is called by main.main(). It only needs to happen once to the rootCmd. func Execute() { if err := rootCmd.Execute(); err != nil { fmt.Println(err) os.Exit(1) } } func init() { rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is pbnj.yaml)") rootCmd.PersistentFlags().StringVar(&logLevel, "logLevel", "info", "log level (default is info") } // initConfig reads in ENV variables if set. func initConfig(cmd *cobra.Command) error { v := viper.New() v.SetConfigName("pbnj") v.AddConfigPath(".") if err := v.ReadInConfig(); err != nil { // It's okay if there isn't a config file if _, ok := err.(viper.ConfigFileNotFoundError); !ok { return err } } v.SetEnvPrefix(prefix) v.AutomaticEnv() bindFlags(cmd, v) return nil } // Bind each cobra flag to its associated viper configuration (config file and environment variable). func bindFlags(cmd *cobra.Command, v *viper.Viper) { cmd.Flags().VisitAll(func(f *pflag.Flag) { // Environment variables can't have dashes in them, so bind them to their equivalent // keys with underscores, e.g. --favorite-color to STING_FAVORITE_COLOR if strings.Contains(f.Name, "-") { envVarSuffix := strings.ToUpper(strings.ReplaceAll(f.Name, "-", "_")) _ = v.BindEnv(f.Name, fmt.Sprintf("%s_%s", prefix, envVarSuffix)) } // Apply the viper config value to the flag when the flag is not set and viper has a value if !f.Changed && v.IsSet(f.Name) { val := v.Get(f.Name) _ = cmd.Flags().Set(f.Name, fmt.Sprintf("%v", val)) } }) }
// Copyright 2020. Akamai 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 or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package cmd import ( "encoding/json" "fmt" "net" "net/url" "os" "github.com/spf13/cobra" ) var resolveHostMtrFlag bool // mtrCmd represents the mtr command var mtrCmd = &cobra.Command{ Use: mtrUse, Args: cobra.ExactArgs(2), Short: mtrShortDescription, Long: mtrLongDescription, Run: func(cmd *cobra.Command, args []string) { var destinationDomain string if ip := net.ParseIP(args[0]); ip != nil { destinationDomain = args[0] } else if _, err := url.Parse(args[0]); err == nil { destinationDomain = args[0] } else { printWarning("IP or domain name is invalid, e.g., 123.123.123.123 or example.com") os.Exit(1) } id, addr := checkEdgeServerIPorLocation(args[1]) var urlstr string switch id { case 0: urlstr = fmt.Sprintf("/diagnostic-tools/v2/ip-addresses/%s/mtr-data", addr) case 1: urlstr = fmt.Sprintf("/diagnostic-tools/v2/ghost-locations/%s/mtr-data", addr) case 2: fmt.Printf("%s", args[1]) printWarning(" is not a valid IP address or Ghost Location") os.Exit(1) } Url, _ := url.Parse(urlstr) parameters := url.Values{} parameters.Add("destinationDomain", destinationDomain) if resolveHostMtrFlag { parameters.Add("resolveDns", "true") } else { parameters.Add("resolveDns", "false") } parameters.Add(clientTypeKey, clientTypeValue) Url.RawQuery = parameters.Encode() resp, byt := doHTTPRequest("GET", Url.String(), nil) if resp.StatusCode == 200 { var respStruct Wrapper var respStructJson MtrDataJson err := json.Unmarshal(*byt, &respStruct) if err != nil { fmt.Println(err) os.Exit(1) } if jsonString { respStructJson.DestinationDomain = args[0] respStructJson.IpAddressOrLocationId = args[1] respStructJson.ResolveDns = resolveHostMtrFlag respStructJson.ReportedTime = getReportedTime() respStructJson.Mtr = respStruct.Mtr resJson, _ := json.MarshalIndent(respStructJson, "", " ") fmt.Println(string(resJson)) return } colorPrintf("blue", networkConnectivity) colorPrintf("yellow", respStruct.Mtr.Source) colorPrintf("blue", to) colorPrintln("yellow", respStruct.Mtr.Destination) fmt.Println(respStruct.Mtr.Result) } else { printResponseError(byt) } }, } func init() { mtrCmd.Flags().BoolVarP(&resolveHostMtrFlag, "resolve-hostname", "r", false, resolveHostMtrFlagDescription) rootCmd.AddCommand(mtrCmd) }
/* * 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 to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package identity import ( "github.com/streamsets/datacollector-edge/api" "github.com/streamsets/datacollector-edge/container/common" "github.com/streamsets/datacollector-edge/container/creation" "github.com/streamsets/datacollector-edge/container/execution/runner" "testing" ) func getStageContext() *common.StageContextImpl { stageConfig := common.StageConfiguration{} stageConfig.Library = LIBRARY stageConfig.StageName = STAGE_NAME stageConfig.Configuration = make([]common.Config, 0) return &common.StageContextImpl{ StageConfig: &stageConfig, Parameters: nil, } } func TestIdentityProcessor(t *testing.T) { stageContext := getStageContext() stageBean, err := creation.NewStageBean(stageContext.StageConfig, stageContext.Parameters) if err != nil { t.Error(err) } stageInstance := stageBean.Stage stageInstance.Init(stageContext) records := make([]api.Record, 1) records[0], _ = stageContext.CreateRecord("1", "TestData") batch := runner.NewBatchImpl("random", records, "randomOffset") batchMaker := runner.NewBatchMakerImpl(runner.StagePipe{}) err = stageInstance.(api.Processor).Process(batch, batchMaker) if err != nil { t.Error("Error in Identity Processor") } outputRecords := batchMaker.GetStageOutput() if len(outputRecords) != 1 { t.Error("Excepted 1 records but got - ", len(records)) } rootField, _ := records[0].Get() if rootField.Value != "TestData" { t.Error("Excepted 'TestData' but got - ", rootField.Value) } stageInstance.Destroy() }
package main import "strings" func main() { } func mergeAlternately(word1 string, word2 string) string { if word1 == "" { return word2 } if word2 == "" { return word1 } var ans strings.Builder ans.WriteByte(word1[0]) ans.WriteByte(word2[0]) ans.WriteString(mergeAlternately(word1[1:], word2[1:])) return ans.String() }
package main import "fmt" func max2(a, b int) int { if a > b { return a } return b } func longestConsecutive(nums []int) int { if len(nums) == 0 { return 0 } numIndices := make(map[int]int) for i, n := range nums { numIndices[n] = i } distinctNums := make([]int, 0, len(nums)) for k, _ := range numIndices { distinctNums = append(distinctNums, k) } for i, n := range distinctNums { numIndices[n] = i } consecStartLens := make(map[int]int) path := make([]int, 0, len(distinctNums)) for k, _ := range numIndices { _, ok := numIndices[k+1] if !ok { consecStartLens[k] = 1 } } maxConsecLen := 1 for k, _ := range numIndices { curr := k kPath := path[:] for { consecLen := consecStartLens[curr] if consecLen >= 1 { // We've reached a point starting from which we know how many // consecutive elements follow kPathLen := len(kPath) for i, kp := range kPath { consecStartLens[kp] = kPathLen - i + consecLen maxConsecLen = max2(maxConsecLen, consecStartLens[kp]) } break } else { kPath = append(kPath, curr) } curr += 1 } } return maxConsecLen } func test1() { nums := []int{100, 4, 200, 1, 3, 2} result := longestConsecutive(nums) fmt.Printf("result: %d\n", result) } func test2() { nums := []int{100, -4, 200, -1, 3, 2} result := longestConsecutive(nums) fmt.Printf("result: %d\n", result) } func test3() { nums := []int{100, -4, 200} result := longestConsecutive(nums) fmt.Printf("result: %d\n", result) } func main() { // test1() // test2() test3() }
package main import ( "flag" "fmt" "io" "net" "os" "github.com/nwehr/chatterbox" ) func main() { var domain, address, port string { flag.StringVar(&address, "b", "0.0.0.0", "Bind address, default 0.0.0.0") flag.StringVar(&port, "p", "6847", "Listen port, default 6847") flag.StringVar(&domain, "d", "home.lan", "Domain for this server, default home.lan") flag.Parse() } serv := &server{ domain: domain, sessions: map[chatterbox.Identity][]net.Conn{}, } fmt.Println(serv.listen(fmt.Sprintf("%s:%s", address, port))) } type server struct { sessions map[chatterbox.Identity][]net.Conn domain string conversationRepo chatterbox.ConversationRepo messageRepo chatterbox.MessageRepo } func (s *server) listen(addr string) error { listener, err := net.Listen("tcp", addr) if err != nil { return err } fmt.Println("listening on ", addr) for { conn, err := listener.Accept() if err != nil { fmt.Println(err.Error()) continue } go s.handleNewConnection(conn) } } func (s *server) handleNewConnection(conn net.Conn) { ident := chatterbox.Identity("") // first message by a client should be LOGIN { msg := chatterbox.Message{} if _, err := msg.ReadFrom(conn); err != nil { fmt.Println("could not read login request", err) return } if msg.Type != "LOGIN" { fmt.Printf("expected LOGIN; got %s\n", msg.Type) return } if _, err := chatterbox.Ok().WriteTo(conn); err != nil { fmt.Println(err) } ident = chatterbox.Identity(msg.Args["Identity"][0]) } s.sessions[ident] = append(s.sessions[ident], conn) fmt.Printf("new session for %s; %d total\n", string(ident), len(s.sessions[ident])) for { msg := chatterbox.Message{} if _, err := msg.ReadFrom(conn); err != nil { if err == os.ErrDeadlineExceeded { continue } if err == io.EOF { fmt.Println("connection closed") conn.Close() break } if err == net.ErrClosed { fmt.Println("connection closed") break } if err != nil { fmt.Printf("could not read: %s\n", err.Error()) break } } s.handleMessage(msg) } } func (s *server) handleMessage(msg chatterbox.Message) { switch msg.Type { case "MSG": for _, recipient := range msg.Args["Recipients"] { ident := chatterbox.Identity(recipient) if ident.Host() == s.domain { for _, conn := range s.sessions[ident] { go msg.WriteTo(conn) } } } } }
package remark import ( "fmt" "os" "testing" "time" "github.com/go-jar/mysql" "blog/conf" "blog/entity" "blog/errno" "blog/resource" "blog/resource/log" ) func prepare() { if err := conf.Init("/usr/local/lighthouse/softwares/aping-blog/blog-back/"); err != nil { fmt.Println(err) } err := log.InitLog("api") if err != nil { fmt.Println(err.Error()) os.Exit(errno.ESysInitLogFail) } defer func() { log.FreeLog() }() resource.InitMysql() resource.InitRedis() } func TestRemarkSvc(t *testing.T) { prepare() remarkSvc := NewSvc([]byte("traceRemarkSvc")) ids, err := remarkSvc.Insert( &entity.RemarkEntity{ ArticleId: 1, Nickname: "test", Content: "test", InitRemarkId: -1, NicknameReplied: "", CreatedTime: time.Now(), UpdatedTime: time.Now(), }, &entity.RemarkEntity{ ArticleId: 1, Nickname: "test1", Content: "test1", InitRemarkId: 1, NicknameReplied: "test", CreatedTime: time.Now(), UpdatedTime: time.Now(), }, ) t.Log(ids, err) remarkEntity := entity.RemarkEntity{Content: "b1"} if _, err := remarkSvc.UpdateById(ids[0], &remarkEntity, map[string]bool{"content": true}); err != nil { t.Log(err) } qp := &mysql.QueryParams{ OrderBy: "id desc", Offset: 0, Cnt: 10, } entities, total, err := remarkSvc.GetRemarks(qp) t.Log("total: ", total) for _, item := range entities { t.Log("GetRemarks", item, err) } for _, id := range ids { deleted, err := remarkSvc.DeleteById(id) t.Log(deleted, err) } }
package item type Item struct { Name string Exp int MadeWithItems []*ItemUsed } func (s *Item) IsCollectable() bool { return len(s.MadeWithItems) == 0 } type ItemUsed struct { Item Quantity int } func (s *Item) CalcItemsReport(quantity int) map[string]*ItemUsed { currentItemMap := make(map[string]*ItemUsed) currentItemMap[s.Name] = &ItemUsed{ Item: *s, Quantity: quantity, } for _, inner := range s.MadeWithItems { itemReports := inner.CalcItemsReport(quantity * inner.Quantity) currentItemMap = MergeMaps(currentItemMap, itemReports) } return currentItemMap } func MergeMaps(a map[string]*ItemUsed, b map[string]*ItemUsed) map[string]*ItemUsed { merged := make(map[string]*ItemUsed) for key, value := range a { if merged[key] == nil { merged[key] = value } else { original := merged[key] original.Quantity += value.Quantity merged[key] = original } } for key, value := range b { if merged[key] == nil { merged[key] = value } else { original := merged[key] original.Quantity += value.Quantity merged[key] = original } } return merged } func NewItemUsed(item Item, quantity int) *ItemUsed { return &ItemUsed{ Item: item, Quantity: quantity, } } // Reagentes var Fundente = Item{ Name: "Fundente", } var Lixa = Item{ Name: "Lixa", } var Tanino = Item{ Name: "Tanino", } var Tecedura = Item{ Name: "Tecedura", } // Minerios var MinerioDeFerro = Item{ Name: "Minério de Ferro", } var MinerioDePrata = Item{ Name: "Minério de Prata", } var MinerioDeOuro = Item{ Name: "Minério de Ouro", } var MinerioDePlatina = Item{ Name: "Minério de Platina", } var MinerioDeEstelaco = Item{ Name: "Minério de Estelaço", } var MinerioDeOricalco = Item{ Name: "Minério de Oricalco", } var Tolvium = Item{ Name: "Tolvium", } var Cinabrio = Item{ Name: "Cinábrio", } // Madeiras var MadeiraVerde = Item{ Name: "Madeira Verde", } var MadeiraEnvelhecida = Item{ Name: "Madeira Envelhecida", } var Urdeira = Item{ Name: "Urdeira", } var Juca = Item{ Name: "Jucá", } var Tabua = Item{ Name: "Tábua", MadeWithItems: []*ItemUsed{ NewItemUsed(MadeiraVerde, 4), }, } var Lenha = Item{ Name: "Lenha", MadeWithItems: []*ItemUsed{ NewItemUsed(MadeiraEnvelhecida, 4), NewItemUsed(Tabua, 2), NewItemUsed(Lixa, 1), }, } var TabuaDeUrdeira = Item{ Name: "Tábua de Urdeira", MadeWithItems: []*ItemUsed{ NewItemUsed(Urdeira, 6), NewItemUsed(Lenha, 2), NewItemUsed(Lixa, 1), }, } var TabuaDeJuca = Item{ Name: "Tábua de Jucá", MadeWithItems: []*ItemUsed{ NewItemUsed(Juca, 8), NewItemUsed(TabuaDeUrdeira, 2), NewItemUsed(Lixa, 1), }, } var Carvao = Item{ Name: "Carvão", MadeWithItems: []*ItemUsed{ NewItemUsed(MadeiraVerde, 2), }, } // Couros var CouroCru = Item{ Name: "Couro Cru", } var PeleGrossa = Item{ Name: "Pele Grossa", } var PeleDeFerro = Item{ Name: "Pele de Ferro", } var PeleArdente = Item{ Name: "Pele Ardente", } var PeleCicatrizada = Item{ Name: "Pele Cicatrizada", } var CouroGrosseiro = Item{ Name: "Couro Grosseito", MadeWithItems: []*ItemUsed{ NewItemUsed(CouroCru, 4), }, } var CouroRustico = Item{ Name: "Couro Rústico", MadeWithItems: []*ItemUsed{ NewItemUsed(CouroGrosseiro, 4), NewItemUsed(Tanino, 1), }, } var CouroReforcado = Item{ Name: "Couro Reforçado", MadeWithItems: []*ItemUsed{ NewItemUsed(PeleGrossa, 6), NewItemUsed(CouroRustico, 2), NewItemUsed(Tanino, 1), }, } var CouroInfuso = Item{ Name: "Couro Reforçado", MadeWithItems: []*ItemUsed{ NewItemUsed(PeleDeFerro, 8), NewItemUsed(CouroReforcado, 2), NewItemUsed(Tanino, 1), }, } var CouroRunico = Item{ Name: "Couro Rúnico", MadeWithItems: []*ItemUsed{ NewItemUsed(CouroInfuso, 5), NewItemUsed(PeleArdente, 1), NewItemUsed(PeleCicatrizada, 1), NewItemUsed(Tanino, 1), }, } // Tecidos var Fibra = Item{ Name: "Fibra", } var FioDeSeda = Item{ Name: "Fio De Seda", } var FibraDeFio = Item{ Name: "Fibra de Fio", } var TecidoDeEscama = Item{ Name: "Tecido de Escama", } var TramaCalica = Item{ Name: "Trama Cálica", } var Linho = Item{ Name: "Linho", MadeWithItems: []*ItemUsed{ NewItemUsed(Fibra, 4), }, } var Cetim = Item{ Name: "Cetim", MadeWithItems: []*ItemUsed{ NewItemUsed(Linho, 4), NewItemUsed(Tecedura, 1), }, } var Seda = Item{ Name: "Seda", MadeWithItems: []*ItemUsed{ NewItemUsed(FioDeSeda, 6), NewItemUsed(Cetim, 2), NewItemUsed(Tecedura, 1), }, } var SedaInfusa = Item{ Name: "Seda Infusa", MadeWithItems: []*ItemUsed{ NewItemUsed(FibraDeFio, 8), NewItemUsed(Seda, 2), NewItemUsed(Tecedura, 1), }, } var FioDeFenix = Item{ Name: "Fio De Fenix", MadeWithItems: []*ItemUsed{ NewItemUsed(SedaInfusa, 5), NewItemUsed(TecidoDeEscama, 1), NewItemUsed(TramaCalica, 1), NewItemUsed(Tecedura, 1), }, } // Lingotes var LingoteDeFerro = Item{ Name: "Lingote de Ferro", MadeWithItems: []*ItemUsed{ NewItemUsed(MinerioDeFerro, 4), }, } var LingoteDePrata = Item{ Name: "Lingote de Prata", MadeWithItems: []*ItemUsed{ NewItemUsed(MinerioDePrata, 4), }, } var LingoteDeAco = Item{ Name: "Lingote de Aço", MadeWithItems: []*ItemUsed{ NewItemUsed(LingoteDeFerro, 3), NewItemUsed(Fundente, 1), NewItemUsed(Carvao, 2), }, } var LingoteDeOuro = Item{ Name: "Lingote de Ouro", MadeWithItems: []*ItemUsed{ NewItemUsed(MinerioDeOuro, 5), NewItemUsed(LingoteDePrata, 2), NewItemUsed(Fundente, 1), }, } var LingoteDeEstelaco = Item{ Name: "Lingote de Estelaço", MadeWithItems: []*ItemUsed{ NewItemUsed(MinerioDeEstelaco, 6), NewItemUsed(LingoteDeAco, 2), NewItemUsed(Fundente, 1), NewItemUsed(Carvao, 2), }, } var LingoteDePlatina = Item{ Name: "Lingote de Platina", MadeWithItems: []*ItemUsed{ NewItemUsed(MinerioDePlatina, 6), NewItemUsed(LingoteDeOuro, 2), NewItemUsed(Fundente, 1), }, } var LingoteDeOricalco = Item{ Name: "Lingote de Oricalco", MadeWithItems: []*ItemUsed{ NewItemUsed(MinerioDeOricalco, 8), NewItemUsed(LingoteDeEstelaco, 2), NewItemUsed(Fundente, 1), NewItemUsed(Carvao, 2), }, } var LingoteDeAsmodeo = Item{ Name: "Lingote de Asmódeo", MadeWithItems: []*ItemUsed{ NewItemUsed(LingoteDeOricalco, 5), NewItemUsed(Tolvium, 1), NewItemUsed(Cinabrio, 1), NewItemUsed(Fundente, 1), NewItemUsed(Carvao, 2), }, } // Machados var MachadaoDeFerro = Item{ Name: "Machadão de Ferro", Exp: 204, MadeWithItems: []*ItemUsed{ NewItemUsed(LingoteDeFerro, 12), NewItemUsed(Tabua, 3), NewItemUsed(CouroGrosseiro, 2), }, } var MachadaoDeAco = Item{ Name: "Machadão de Aço", Exp: 540, MadeWithItems: []*ItemUsed{ NewItemUsed(LingoteDeAco, 12), NewItemUsed(Tabua, 3), NewItemUsed(CouroGrosseiro, 2), }, }
// Copyright 2019 CUE 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, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package openapi import ( "encoding/json" "cuelang.org/go/cue" "cuelang.org/go/cue/ast" "cuelang.org/go/cue/errors" "cuelang.org/go/cue/token" cuejson "cuelang.org/go/encoding/json" ) // A Config defines options for converting CUE to and from OpenAPI. type Config struct { // PkgName defines to package name for a generated CUE package. PkgName string // Info specifies the info section of the OpenAPI document. To be a valid // OpenAPI document, it must include at least the title and version fields. // Info may be a *ast.StructLit or any type that marshals to JSON. Info interface{} // ReferenceFunc allows users to specify an alternative representation // for references. An empty string tells the generator to expand the type // in place and, if applicable, not generate a schema for that entity. ReferenceFunc func(inst *cue.Instance, path []string) string // DescriptionFunc allows rewriting a description associated with a certain // field. A typical implementation compiles the description from the // comments obtains from the Doc method. No description field is added if // the empty string is returned. DescriptionFunc func(v cue.Value) string // SelfContained causes all non-expanded external references to be included // in this document. SelfContained bool // FieldFilter defines a regular expression of all fields to omit from the // output. It is only allowed to filter fields that add additional // constraints. Fields that indicate basic types cannot be removed. It is // an error for such fields to be excluded by this filter. // Fields are qualified by their Object type. For instance, the // minimum field of the schema object is qualified as Schema/minimum. FieldFilter string // ExpandReferences replaces references with actual objects when generating // OpenAPI Schema. It is an error for an CUE value to refer to itself // if this option is used. ExpandReferences bool } type Generator = Config // Gen generates the set OpenAPI schema for all top-level types of the // given instance. func Gen(inst *cue.Instance, c *Config) ([]byte, error) { if c == nil { c = defaultConfig } all, err := c.All(inst) if err != nil { return nil, err } return json.Marshal(all) } // Generate generates the set of OpenAPI schema for all top-level types of the // given instance. // // Note: only a limited number of top-level types are supported so far. func Generate(inst *cue.Instance, c *Config) (*ast.File, error) { all, err := schemas(c, inst) if err != nil { return nil, err } top, err := c.compose(all) if err != nil { return nil, err } return &ast.File{Decls: top.Elts}, nil } // All generates an OpenAPI definition from the given instance. // // Note: only a limited number of top-level types are supported so far. // Deprecated: use Generate func (g *Generator) All(inst *cue.Instance) (*OrderedMap, error) { all, err := schemas(g, inst) if err != nil { return nil, err } top, err := g.compose(all) return (*OrderedMap)(top), err } func toCUE(name string, x interface{}) (v ast.Expr, err error) { b, err := json.Marshal(x) if err == nil { v, err = cuejson.Extract(name, b) } if err != nil { return nil, errors.Wrapf(err, token.NoPos, "openapi: could not encode %s", name) } return v, nil } func (c *Config) compose(schemas *ast.StructLit) (x *ast.StructLit, err error) { // Support of OrderedMap is mostly for backwards compatibility. var info ast.Expr switch x := c.Info.(type) { case nil: info = ast.NewStruct() case ast.Expr: info = x case *OrderedMap: info = (*ast.StructLit)(x) case OrderedMap: info = (*ast.StructLit)(&x) default: info, err = toCUE("info section", x) if err != nil { return nil, err } } return ast.NewStruct( "openapi", ast.NewString("3.0.0"), "info", info, "paths", ast.NewStruct(), "components", ast.NewStruct("schemas", schemas), ), nil } // Schemas extracts component/schemas from the CUE top-level types. func (g *Generator) Schemas(inst *cue.Instance) (*OrderedMap, error) { comps, err := schemas(g, inst) if err != nil { return nil, err } return (*OrderedMap)(comps), err } var defaultConfig = &Config{} // TODO // The conversion interprets @openapi(<entry> {, <entry>}) attributes as follows: // // readOnly sets the readOnly flag for a property in the schema // only one of readOnly and writeOnly may be set. // writeOnly sets the writeOnly flag for a property in the schema // only one of readOnly and writeOnly may be set. // discriminator explicitly sets a field as the discriminator field //
package v2 import ( "strconv" "strings" "github.com/davyxu/tabtoy/v2/i18n" "github.com/davyxu/tabtoy/v2/model" ) type typeCell struct { value string col int } // 类型表的数据, 数据读取与使用分开使用, 让类型互相没有依赖 type typeModel struct { colData map[string]*typeCell done bool row int fd *model.FieldDescriptor rawFieldType string } func (self *typeModel) getValue(row string) (string, int) { if v, ok := self.colData[row]; ok { return v.value, v.col } return "", -1 } func newTypeModel() *typeModel { return &typeModel{ colData: make(map[string]*typeCell), fd: model.NewFieldDescriptor(), } } type typeModelRoot struct { pragma string models []*typeModel unknownModel []*typeModel fieldTypeCol int // 存储字段的名称 fdmap map[string][]string Col int Row int } func (self *typeModelRoot) ParsePragma(localFD *model.FileDescriptor) bool { if err := localFD.Pragma.Parse(self.pragma); err != nil { log.Errorf("%s, '%s'", i18n.String(i18n.TypeSheet_PragmaParseFailed), self.pragma) return false } if localFD.Pragma.GetString("TableName") == "" { log.Errorf("%s", i18n.String(i18n.TypeSheet_TableNameIsEmpty)) return false } if localFD.Pragma.GetString("Package") == "" { log.Errorf("%s", i18n.String(i18n.TypeSheet_PackageIsEmpty)) return false } return true } // 解析类型表里的所有类型描述 func (self *typeModelRoot) ParseData(localFD *model.FileDescriptor, globalFD *model.FileDescriptor) bool { var td *model.Descriptor reservedRowFieldTypeName := localFD.Pragma.GetString("TableName") + "Define" // 每一行 for _, m := range self.models { self.Row = m.row var rawTypeName string rawTypeName, self.Col = m.getValue("ObjectType") if rawTypeName == reservedRowFieldTypeName { log.Errorf("%s '%s'", i18n.String(i18n.DataHeader_UseReservedTypeName), rawTypeName) return false } existType, ok := localFD.DescriptorByName[rawTypeName] if ok { td = existType } else { td = model.NewDescriptor() td.Name = rawTypeName localFD.Add(td) } // 字段名 m.fd.Name, self.Col = m.getValue("FieldName") if globalFD.Fdmap == nil { globalFD.Fdmap = make(map[string][]string) } // 这里把结构体相关的数据保存到一个map 根据类型索引 if m.fd.Name != "" { if _, ok := globalFD.Fdmap[rawTypeName]; ok { globalFD.Fdmap[rawTypeName] = append(globalFD.Fdmap[rawTypeName], m.fd.Name) } else { // 这里必须是0 否则就不是从零开始了 globalFD.Fdmap[rawTypeName] = make([]string, 0) globalFD.Fdmap[rawTypeName] = append(globalFD.Fdmap[rawTypeName], m.fd.Name) } } // 解析类型 m.rawFieldType, self.Col = m.getValue("FieldType") self.fieldTypeCol = self.Col fieldType, isrepeated, complexType, ok := findFieldType(localFD, globalFD, m.rawFieldType) if !ok { return false } if fieldType == model.FieldType_None { self.unknownModel = append(self.unknownModel, m) } m.fd.Type = fieldType m.fd.Complex = complexType m.fd.IsRepeated = isrepeated var rawFieldValue string // 解析值 rawFieldValue, self.Col = m.getValue("Value") kind, enumvalue, ok := parseFieldValue(rawFieldValue) if !ok { return false } if td.Kind == model.DescriptorKind_None { td.Kind = kind // 一些字段有填值, 一些没填值 } else if td.Kind != kind { log.Errorf("%s", i18n.String(i18n.TypeSheet_DescriptorKindNotSame)) return false } if td.Kind == model.DescriptorKind_Enum { if _, ok := td.FieldByNumber[enumvalue]; ok { log.Errorf("%s %d", i18n.String(i18n.TypeSheet_DuplicatedEnumValue), enumvalue) return false } } m.fd.EnumValue = enumvalue m.fd.Comment, self.Col = m.getValue("Comment") // 去掉注释中的回车,避免代码生成错误 m.fd.Comment = strings.Replace(m.fd.Comment, "\n", " ", -1) var rawMeta string rawMeta, self.Col = m.getValue("Meta") if err := m.fd.Meta.Parse(rawMeta); err != nil { log.Errorf("%s, '%s'", i18n.String(i18n.TypeSheet_FieldMetaParseFailed), err.Error()) return false } // 别名 var rawAlias string rawAlias, self.Col = m.getValue("Alias") if self.Col != -1 { m.fd.Meta.SetString("Alias", rawAlias) } // 默认值 var rawDefault string rawDefault, self.Col = m.getValue("Default") if self.Col != -1 { m.fd.Meta.SetString("Default", rawDefault) } if td.Add(m.fd, globalFD.Fdmap) != nil { log.Errorf("%s '%s'", i18n.String(i18n.TypeSheet_DuplicateFieldName), m.fd.Name) return false } } return true } func (self *typeModelRoot) SolveUnknownModel(localFD *model.FileDescriptor, globalFD *model.FileDescriptor) bool { for _, m := range self.unknownModel { self.Row = m.row self.Col = self.fieldTypeCol fieldType, isrepeatd, complexType, ok := findFieldType(localFD, globalFD, m.rawFieldType) if !ok { return false } // 实在是找不到了, 没辙了 if fieldType == model.FieldType_None { log.Errorf("%s, '%s'", i18n.String(i18n.TypeSheet_FieldTypeNotFound), m.rawFieldType) return false } m.fd.Type = fieldType m.fd.Complex = complexType m.fd.IsRepeated = isrepeatd } return true } func findFieldType(localFD *model.FileDescriptor, globalFD *model.FileDescriptor, rawFieldType string) (model.FieldType, bool, *model.Descriptor, bool) { // 开始在本地symbol中找 testFD := localFD for { fieldType, isrepeatd, complexType, ok := findlocalFieldType(testFD, rawFieldType) if !ok { return model.FieldType_None, isrepeatd, nil, false } if fieldType != model.FieldType_None { return fieldType, isrepeatd, complexType, true } // 已经是全局范围, 说明找不到 if testFD == globalFD { return model.FieldType_None, isrepeatd, nil, true } // 找不到就换全局范围找 testFD = globalFD } } // bool表示是否有错 func findlocalFieldType(localFD *model.FileDescriptor, rawFieldType string) (model.FieldType, bool, *model.Descriptor, bool) { var isrepeated bool var puretype string if strings.HasPrefix(rawFieldType, model.RepeatedKeyword) { puretype = rawFieldType[model.RepeatedKeywordLen+1:] isrepeated = true } else { puretype = rawFieldType } // 解析普通类型 if ft, ok := model.ParseFieldType(puretype); ok { return ft, isrepeated, nil, true } // 解析内建类型 if desc, ok := localFD.DescriptorByName[rawFieldType]; ok { // 只有枚举( 结构体不允许再次嵌套, 增加理解复杂度 ) if desc.Kind != model.DescriptorKind_Enum { log.Errorf("%s, '%s'", i18n.String(i18n.TypeSheet_StructFieldCanNotBeStruct), rawFieldType) return model.FieldType_None, isrepeated, nil, false } return model.FieldType_Enum, isrepeated, desc, true } // 没找到类型, 待二次pass return model.FieldType_None, isrepeated, nil, true } func parseFieldValue(rawFieldValue string) (model.DescriptorKind, int32, bool) { // 非空值是枚举 if rawFieldValue != "" { v, err := strconv.Atoi(rawFieldValue) // 解析枚举值 if err != nil { log.Errorf("%s, %s", i18n.String(i18n.TypeSheet_EnumValueParseFailed), err.Error()) return model.DescriptorKind_None, 0, false } return model.DescriptorKind_Enum, int32(v), true } return model.DescriptorKind_Struct, 0, true }
package list /* import ( "io/ioutil" "os" "reflect" "testing" "github.com/devspace-cloud/devspace/cmd/flags" cloudconfig "github.com/devspace-cloud/devspace/pkg/devspace/cloud/config" cloudlatest "github.com/devspace-cloud/devspace/pkg/devspace/cloud/config/versions/latest" "github.com/devspace-cloud/devspace/pkg/devspace/config/loader" "github.com/devspace-cloud/devspace/pkg/devspace/config/generated" "github.com/devspace-cloud/devspace/pkg/devspace/config/versions/latest" "github.com/devspace-cloud/devspace/pkg/util/fsutil" "github.com/devspace-cloud/devspace/pkg/util/kubeconfig" "github.com/devspace-cloud/devspace/pkg/util/log" "gopkg.in/yaml.v2" "gotest.tools/assert" restclient "k8s.io/client-go/rest" "k8s.io/client-go/tools/clientcmd" clientcmdapi "k8s.io/client-go/tools/clientcmd/api" ) type customKubeConfig struct { rawconfig clientcmdapi.Config rawConfigError error clientConfig *restclient.Config clientConfigError error namespace string namespaceBool bool namespaceErr error configAccess clientcmd.ConfigAccess } func (config *customKubeConfig) RawConfig() (clientcmdapi.Config, error) { return config.rawconfig, config.rawConfigError } func (config *customKubeConfig) Namespace() (string, bool, error) { return config.namespace, config.namespaceBool, config.namespaceErr } func (config *customKubeConfig) ClientConfig() (*restclient.Config, error) { return config.clientConfig, config.clientConfigError } func (config *customKubeConfig) ConfigAccess() clientcmd.ConfigAccess { return config.configAccess } type listDeploymentsTestCase struct { name string fakeConfig *latest.Config fakeKubeConfig clientcmd.ClientConfig configsYamlContent interface{} generatedYamlContent interface{} providerList []*cloudlatest.Provider expectTablePrint bool expectedHeader []string expectedValues [][]string expectedErr string } func TestListDeployments(t *testing.T) { testCases := []listDeploymentsTestCase{ listDeploymentsTestCase{ name: "All deployments not listable", fakeConfig: &latest.Config{ Deployments: []*latest.DeploymentConfig{ &latest.DeploymentConfig{ Name: "UndeployableKubectl", Kubectl: &latest.KubectlConfig{}, }, //Those slow down the test &latest.DeploymentConfig{ Name: "NoDeploymentMethod", }, }, }, generatedYamlContent: generated.Config{}, fakeKubeConfig: &customKubeConfig{ rawconfig: clientcmdapi.Config{ Contexts: map[string]*clientcmdapi.Context{ "": &clientcmdapi.Context{}, }, Clusters: map[string]*clientcmdapi.Cluster{ "": &clientcmdapi.Cluster{ LocationOfOrigin: "someLocation", Server: "someServer", }, }, AuthInfos: map[string]*clientcmdapi.AuthInfo{ "": &clientcmdapi.AuthInfo{}, }, }, }, expectedHeader: []string{"NAME", "TYPE", "DEPLOY", "STATUS"}, }, } log.SetInstance(log.Discard) for _, testCase := range testCases { testListDeployments(t, testCase) } } func testListDeployments(t *testing.T, testCase listDeploymentsTestCase) { log.SetFakePrintTable(func(s log.Logger, header []string, values [][]string) { assert.Assert(t, testCase.expectTablePrint || len(testCase.expectedHeader)+len(testCase.expectedValues) > 0, "PrintTable unexpectedly called in testCase %s", testCase.name) assert.Equal(t, reflect.DeepEqual(header, testCase.expectedHeader), true, "Unexpected header in testCase %s. Expected:%v\nActual:%v", testCase.name, testCase.expectedHeader, header) assert.Equal(t, reflect.DeepEqual(values, testCase.expectedValues), true, "Unexpected values in testCase %s. Expected:%v\nActual:%v", testCase.name, testCase.expectedValues, values) }) dir, err := ioutil.TempDir("", "test") if err != nil { t.Fatalf("Error creating temporary directory: %v", err) } wdBackup, err := os.Getwd() if err != nil { t.Fatalf("Error getting current working directory: %v", err) } err = os.Chdir(dir) if err != nil { t.Fatalf("Error changing working directory: %v", err) } defer func() { //Delete temp folder err = os.Chdir(wdBackup) if err != nil { t.Fatalf("Error changing dir back: %v", err) } err = os.RemoveAll(dir) if err != nil { t.Fatalf("Error removing dir: %v", err) } }() loader := cloudconfig.NewLoader() providerConfig, err := loader.Load() assert.NilError(t, err, "Error getting provider config in testCase %s", testCase.name) providerConfig.Providers = testCase.providerList loader.SetFakeConfig(testCase.fakeConfig) generated.ResetConfig() kubeconfig.SetFakeConfig(testCase.fakeKubeConfig) if testCase.generatedYamlContent != nil { content, err := yaml.Marshal(testCase.generatedYamlContent) assert.NilError(t, err, "Error parsing configs.yaml to yaml in testCase %s", testCase.name) fsutil.WriteToFile(content, generated.ConfigPath) } err = (&deploymentsCmd{GlobalFlags: &flags.GlobalFlags{}}).RunDeploymentsStatus(nil, []string{}) if testCase.expectedErr == "" { assert.NilError(t, err, "Unexpected error in testCase %s.", testCase.name) } else { assert.Error(t, err, testCase.expectedErr, "Wrong or no error in testCase %s.", testCase.name) } }*/
package main import ( "fmt" "io" "net" "os" ) // 传输文件的客户端 func main() { fmt.Println("请输入文件路径:") var path string fmt.Scan(&path) // 获取文件相关信息 info, err1 := os.Stat(path) if err1 != nil { fmt.Println("os.Stat err1 = ", err1) return } fileName := info.Name() fmt.Println("fileName:", fileName) // 连接服务端 conn, err2 := net.Dial("tcp", "127.0.0.1:8080") if err2 != nil { fmt.Println("net.Dial err2 = ", err2) return } // 关闭连接 defer conn.Close() // 向服务端发送文件名 _, err3 := conn.Write([]byte(fileName)) if err3 != nil { fmt.Println("conn.Write err3 = ", err3) return } // 接收服务端的响应 buffer := make([]byte, 1024) n, err4 := conn.Read(buffer) if err4 != nil { fmt.Println("conn.Read err4 = ", err4) return } if "ok" == string(buffer[:n]) { // 向服务端发送文件 sendFile(path, conn) } else { fmt.Println("服务端响应失败") } } // 向服务端发送文件 func sendFile(path string, conn net.Conn) { // 打开文件 file, err1 := os.Open(path) if err1 != nil { fmt.Println("os.Open err1 = ", err1) return } // 关闭文件 defer file.Close() buffer := make([]byte, 1024) for { n, err2 := file.Read(buffer) if err2 != nil { if err2 != io.EOF { fmt.Println("file.Read err2 = ", err2) } break } // 往服务端发送 conn.Write(buffer[:n]) } }
package cbor import ( "testing" "github.com/polydawn/refmt/tok/fixtures" ) func testTags(t *testing.T) { t.Run("tagged object", func(t *testing.T) { seq := fixtures.SequenceMap["tagged object"] canon := bcat(b(0xc0+(0x20-8)), b(50), b(0xa0+1), b(0x60+1), []byte(`k`), b(0x60+1), []byte(`v`)) t.Run("encode canonical", func(t *testing.T) { checkEncoding(t, seq, canon, nil) }) t.Run("decode canonical", func(t *testing.T) { checkDecoding(t, seq, canon, nil) }) }) t.Run("tagged string", func(t *testing.T) { seq := fixtures.SequenceMap["tagged string"] canon := bcat(b(0xc0+(0x20-8)), b(50), b(0x60+5), []byte(`wahoo`)) t.Run("encode canonical", func(t *testing.T) { checkEncoding(t, seq, canon, nil) }) t.Run("decode canonical", func(t *testing.T) { checkDecoding(t, seq, canon, nil) }) }) t.Run("array with mixed tagged values", func(t *testing.T) { seq := fixtures.SequenceMap["array with mixed tagged values"] canon := bcat(b(0x80+2), b(0xc0+(0x20-8)), b(40), b(0x00+(0x19)), []byte{0x1, 0x90}, b(0xc0+(0x20-8)), b(50), b(0x60+3), []byte(`500`), ) t.Run("encode canonical", func(t *testing.T) { checkEncoding(t, seq, canon, nil) }) t.Run("decode canonical", func(t *testing.T) { checkDecoding(t, seq, canon, nil) }) }) t.Run("object with deeper tagged values", func(t *testing.T) { seq := fixtures.SequenceMap["object with deeper tagged values"] canon := bcat(b(0xa0+5), b(0x60+2), []byte(`k1`), b(0xc0+(0x20-8)), b(50), b(0x60+3), []byte(`500`), b(0x60+2), []byte(`k2`), b(0x60+8), []byte(`untagged`), b(0x60+2), []byte(`k3`), b(0xc0+(0x20-8)), b(60), b(0x60+3), []byte(`600`), b(0x60+2), []byte(`k4`), b(0x80+2), /**/ b(0xc0+(0x20-8)), b(50), b(0x60+4), []byte(`asdf`), /**/ b(0xc0+(0x20-8)), b(50), b(0x60+4), []byte(`qwer`), b(0x60+2), []byte(`k5`), b(0xc0+(0x20-8)), b(50), b(0x60+3), []byte(`505`), ) t.Run("encode canonical", func(t *testing.T) { checkEncoding(t, seq, canon, nil) }) t.Run("decode canonical", func(t *testing.T) { checkDecoding(t, seq, canon, nil) }) }) }
package ghosts type Wraith struct { } func (w Wraith) Name() string { return "Wraith" } func (w Wraith) Evidence() [3]string { return [3]string{"Freezing", "Spirit Box", "Fingerprints"} }
package ch01 // Find the maximum element in a sorted and rotated list. Complexity O(log(n)) // Hint: user binary search algorithm // Comments: Must be rotated at some unknown point, otherwise this problem doesn't make much sense // (Largest value is the first element...) // If duplicates are allowed then binary search won't work, and complexity is O(n) worst case. // // e.g. {3, 3, 3, 3, 3, 3, 3, 3, 0, 1, 1, 3} and {3, 3, 3, 0, 3, 3, 3, 3, 3, 3, 3, 3} func FindMaxElement(in []int) int { res := findMax(in, 0, len(in) - 1) return res } func findMax(arr []int, start int, end int) int { if len(arr) == 0 { // empty array return -1 } if start == end { // end of recursion return arr[start] } mid := start + (end - start)/2 if start < end && arr[mid+1] < arr[mid] { // start is max since next element is smaller return arr[mid] } else { // binary search decision, left or right if arr[start] > arr[end] { // left hand side return findMax(arr, start, mid) } else { // right hand side return findMax(arr, mid+1, end) } } }
package main import ( "os" "io/ioutil" "container/list" "strings" ) type Entries []*Entry func EntriesFromPath(path string) (entries Entries, err error) { files, err := ioutil.ReadDir(cwd) if err != nil { return } return EntriesFromFiles(files), nil } func matches(file os.FileInfo) bool { startsWith, endsWith := strings.HasPrefix, strings.HasSuffix name, mode := file.Name(), file.Mode() return mode.IsRegular() && !startsWith(name, ".") && !endsWith(name, "SUMS") } func EntriesFromFiles(files []os.FileInfo) Entries { items := 0 entries := make([]*Entry, len(files)) for _, file := range files { if matches(file) { entry := &Entry{Filename: file.Name()} entries[items] = entry items++ } } return entries[0:items] } func EntriesFromChecksumFile(checksums *os.File) (entries Entries, err error) { entries = make([]*Entry, 0) r := NewReader(checksums) err = r.Each(func(entry *Entry) { entries = append(entries, entry) }) return } type BucketsByChecksum map[string]*list.List func (entries Entries) BucketsByChecksum() (buckets BucketsByChecksum) { buckets = make(map[string]*list.List) for _, entry := range entries { bucket, exists := buckets[entry.Checksum] if !exists { bucket = list.New() buckets[entry.Checksum] = bucket } bucket.PushBack(entry.Filename) } return }
package views import ( "bytes" "errors" "html/template" "io" "log" "net/http" "path/filepath" "time" "github.com/gorilla/csrf" "lenslocked.com/context" ) var ( LayoutDir string = "views/layouts/" TemplateDir string = "views/" TemplateExtension string = ".gohtml" ) func NewFiles(layout string, files ...string) *View { addTemplateFiles(files) addTemplateExt(files) files = append(files, fetchFiles()...) t, err := template.New("").Funcs( template.FuncMap{ "csrfField": func() (template.HTML, error) { return "", errors.New("csrfField is not defined") }, }, ).ParseFiles(files...) if err != nil { panic(err) } return &View{ Template: t, Layout: layout} } func addTemplateFiles(files []string) { for i, f := range files { files[i] = TemplateDir + f } } func addTemplateExt(files []string) { for i, f := range files { files[i] = f + TemplateExtension } } func (v *View) Render(w http.ResponseWriter, r *http.Request, data interface{}) { w.Header().Set("Content-Type", "text/html") var vd Data switch d := data.(type) { case Data: vd = d default: vd = Data{ Yield: data, } } vd.User = context.User(r.Context()) var buf bytes.Buffer csrfField := csrf.TemplateField(r) tpl := v.Template.Funcs(template.FuncMap{ "csrfField": func() template.HTML { return csrfField }, }) if err := tpl.ExecuteTemplate(&buf, v.Layout, vd); err != nil { log.Println("error", err) http.Error(w, "Something went wrong rendering a page", http.StatusInternalServerError) return } io.Copy(w, &buf) } func fetchFiles() []string { files, err := filepath.Glob(LayoutDir + "*" + TemplateExtension) if err != nil { panic(err) } return files } func (v *View) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/html") v.Render(w, r, nil) } type View struct { Template *template.Template Layout string } func persistAlert(w http.ResponseWriter, alert Alert) { expiresAt := time.Now().Add(5 * time.Minute) lvl := http.Cookie{ Name: "alert_level", Value: alert.Level, Expires: expiresAt, HttpOnly: true, } msg := http.Cookie{ Name: "alert_message", Value: alert.Message, Expires: expiresAt, HttpOnly: true, } http.SetCookie(w, &lvl) http.SetCookie(w, &msg) } // RedirectAlert accepts all the normal params for an // http.Redirect and performs a redirect, but only after // persisting the provided alert in a cookie so that it can // be displayed when the new page is loaded. func RedirectAlert(w http.ResponseWriter, r *http.Request, urlStr string, code int, alert Alert) { persistAlert(w, alert) http.Redirect(w, r, urlStr, code) }
// // Example how to handle custom errors // package main import ( "fmt" "log" "github.com/rogozhka/ytrwrap" ) func main() { tr := ytrwrap.NewYandexTranslate("<your-api-key") src := "the pony eat grass" out, err := tr.Translate(src, ytrwrap.FR, nil) if err != nil { switch err.Code() { case ytrwrap.KEY_WRONG: log.Println("KEY_WRONG") case ytrwrap.KEY_BLOCKED: log.Println("KEY_BLOCKED") case ytrwrap.LIMIT_DAILY_EXCEEDED: log.Println("LIMIT_DAILY_EXCEEDED") case ytrwrap.LIMIT_TEXTSIZE_EXCEEDED: log.Println("LIMIT_TEXTSIZE_EXCEEDED") case ytrwrap.NOT_SUPPORTED_DIRECTION: log.Println("NOT_SUPPORTED_DIRECTION") default: log.Println(err.Message()) } } fmt.Printf("%s", out) // // le poney, manger de l'herbe // }
package functions import ( "bufio" "fmt" "os" "os/exec" "strings" "github.com/fatih/color" "golang.org/x/crypto/bcrypt" ) var users []User // User type which is a struct with two field // User.Name string // User.Password string type User struct { Name string `json:"name"` Password string `json:"password"` } // SelectOption function // This functions is called in main and show a menu with options to the user func SelectOption() { fmt.Printf("\n%s\n", color.YellowString("[selectOption() function CALLED]")) option := 10 for option != 6 { ShowMenu() fmt.Printf("\t%s", color.WhiteString("Enter an option: ")) _, _ = fmt.Scanf("%d", &option) switch option { case 1: u, p := RegisterUser() AppendUser(&users, u, p) case 2: userEntered, passwordEntered := GetUser() LoginUser(users, userEntered, passwordEntered) case 3: fmt.Println(users) case 5: c := exec.Command("clear") c.Stdout = os.Stdout c.Run() case 6: break } } fmt.Printf("%s\n\n", color.YellowString("[selectOption() function EXITED SUCCESSFULLY]")) } // ShowMenu function // This function displays the options of the application's menu. func ShowMenu() { fmt.Printf("\n%s\n", color.YellowString("[ShowMenu() function CALLED]")) fmt.Printf("\t%s\n", color.WhiteString("STRUCTS, JSON AND BCRYPT GO PROGRAM")) fmt.Printf("\t\t%s%s\n", color.GreenString("1)"), color.WhiteString("Register an user")) fmt.Printf("\t\t%s%s\n", color.GreenString("2)"), color.WhiteString("Login an user")) fmt.Printf("\t\t%s%s\n", color.GreenString("3)"), color.WhiteString("List all users")) fmt.Printf("\t\t%s%s\n", color.GreenString("4)"), color.WhiteString("Convert []User to Json an list")) fmt.Printf("\t\t%s%s\n", color.GreenString("5)"), color.WhiteString("Clean Screen")) fmt.Printf("\t\t%s%s\n", color.GreenString("6)"), color.WhiteString("Enter 6 to exit")) fmt.Printf("%s\n\n", color.YellowString("[ShowMenu() function EXITED SUCCESSFULLY]")) } // GetUser function // This function get an user from de database. func GetUser() (name, password string) { fmt.Printf("\n%s", color.YellowString("[GetUser() function CALLED]")) fmt.Printf("%s", color.GreenString("\n\tEnter your user:\n")) reader := bufio.NewReader(os.Stdin) fmt.Printf("\t%s", color.WhiteString("\t\tEnter Name: ")) name, _ = reader.ReadString('\n') name = strings.TrimSuffix(name, "\n") fmt.Printf("\t%s", color.WhiteString("\t\tEnter Password: ")) password, _ = reader.ReadString('\n') password = strings.TrimSuffix(password, "\n") fmt.Printf("%s\n\n", color.YellowString("[GetUser() function EXITED SUCCESSFULLY]")) return name, password } // RegisterUser function. // This function allows to register an user in the system. func RegisterUser() (name, hashedPassword string) { fmt.Printf("\n%s", color.YellowString("[RegisterUser() function CALLED]")) fmt.Printf("%s", color.GreenString("\n\tRegister an user:\n")) reader := bufio.NewReader(os.Stdin) fmt.Printf("\t%s", color.WhiteString("\t\tEnter Name: ")) name, _ = reader.ReadString('\n') name = strings.TrimSuffix(name, "\n") fmt.Printf("\t%s", color.WhiteString("\t\tEnter Password: ")) password, _ := reader.ReadString('\n') password = strings.TrimSuffix(password, "\n") hashedPassword = string(HashPassword(password)) fmt.Printf("\t%s%s, %s%s\n", color.GreenString("User: {"), name, hashedPassword, color.GreenString("} added successfully!")) fmt.Printf("%s\n\n", color.YellowString("[RegisterUser() function EXITED SUCCESSFULLY]")) return name, hashedPassword } // HashPassword function. // This function hash a password from string to encrypt data. func HashPassword(password string) (hashedPassword []byte) { fmt.Printf("\n%s", color.YellowString("[HashPassword() function CALLED]")) cost := 4 hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), cost) if err != nil { fmt.Println(err) } fmt.Printf("%s\n\n", color.YellowString("\n[HashPassword() function EXITED SUCCESSFULLY]")) return hashedPassword } // AppendUser function. // This function allows to append an user into de database. func AppendUser(users *[]User, name, password string) { fmt.Printf("%s\n", color.YellowString("[AppendUser() function CALLED]")) user := User{ Name: name, Password: password, } *users = append(*users, user) fmt.Printf("%s\n\n", color.YellowString("[AppendUser() function EXITED SUCCESSFULLY]")) } // DidUserExists function. // This function check if the introduce by the user exists in the database func DidUserExists(users []User, name string) (b bool, i int) { fmt.Printf("\n%s", color.YellowString("[DidUserExists() function CALLED]\n")) b = false for i, user := range users { if user.Name == name { b = true fmt.Printf("%s\n\n", color.YellowString("[DidUserExists() function EXITED SUCCESSFULLY]")) return b, i } } fmt.Printf("%s\n\n", color.YellowString("[DidUserExists() function EXITED SUCCESSFULLY]")) i = -1 return b, i } // LoginUser function. // This function allow to login in the application with valid credentials. func LoginUser(users []User, name, password string) { fmt.Printf("\n%s", color.YellowString("[LoginUser() function CALLED]\n")) userExist, indexUser := DidUserExists(users, name) if userExist { err := bcrypt.CompareHashAndPassword([]byte(users[indexUser].Password), []byte(password)) if err != nil { fmt.Println("You can't access :(") return } fmt.Printf("\t\t%s%s%s\n", color.WhiteString("Welcome back "), color.GreenString(name), color.WhiteString("!\n"), ) } else { fmt.Println("The user you entered does not exist :(") } fmt.Printf("%s\n", color.YellowString("[LoginUser() function EXITED SUCCESSFULLY]")) }
package main import ( "testing" ) func Test(t *testing.T) { a := [][]int{[]int{1}} ret := minPathSum(a) if ret != 1 { t.Error("Expected 1 got ", ret) } a = [][]int{[]int{1, 2}} ret = minPathSum(a) if ret != 3 { t.Fatalf("Expacted 3 got %d", ret) } a = [][]int{[]int{1}, []int{2}} ret = minPathSum(a) if ret != 3 { t.Fatalf("Expacted 3 got %d", ret) } a = [][]int{[]int{1, 2}, []int{3, 1}} ret = minPathSum(a) if ret != 4 { t.Fatalf("Expacted 4 got %d", ret) } a = [][]int{[]int{1, 2, 100}, []int{3, 100, 1}} ret = minPathSum(a) if ret != 104 { t.Fatalf("Expacted 104 got %d", ret) } a = [][]int{[]int{1, 3, 1}, []int{1, 5, 1}, []int{4, 2, 1}} ret = minPathSum(a) if ret != 7 { t.Fatalf("Expacted 7 got %d", ret) } }
package main import ( "bufio" "errors" "fmt" "io/ioutil" "log" "os" "os/exec" "path/filepath" "runtime" ) func makeCmd(args []string) (*exec.Cmd, error) { var cmd *exec.Cmd switch len(args) { case 0: return nil, errors.New("empty command") case 1: cmd = exec.Command(args[0]) default: cmd = exec.Command(args[0], args[1:]...) } return cmd, nil } func runCommand(args []string) error { cmd, err := makeCmd(args) if err != nil { return err } checkVerboseEnabled(cmd) return cmd.Run() } func fileExists(path string) bool { _, err := os.Stat(path) if err != nil { return false } return true } func saveCurrentDir() string { prevDir, _ := filepath.Abs(".") return prevDir } func clearWorkDir(workDir string) error { err := os.RemoveAll(workDir) if err != nil { // workaround for a restriction of os.RemoveAll() // os.RemoveAll() call fd.Readdirnames(100). // So os.RemoveAll() does not always remove all entries. // Some 3rd-party module (e.g. lua-nginx-module) tumbles this restriction. if fileExists(workDir) { err = os.RemoveAll(workDir) } } return err } func fileGetContents(path string) (string, error) { conf := "" if len(path) > 0 { confb, err := ioutil.ReadFile(path) if err != nil { return "", fmt.Errorf("confPath(%s) does not exist.", path) } conf = string(confb) } return conf, nil } func printConfigureOptions() error { cmd := exec.Command("objs/nginx", "-V") cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr return cmd.Run() } func printFirstMsg() { fmt.Printf(`nginx-build: %s Compiler: %s %s `, NGINX_BUILD_VERSION, runtime.Compiler, runtime.Version()) } func printLastMsg(workDir, srcDir string, openResty, configureOnly bool) { log.Println("Complete building nginx!") if !openResty { if !configureOnly { fmt.Println() err := printConfigureOptions() if err != nil { fmt.Println(err.Error()) } } } fmt.Println() lastMsgFormat := `Enter the following command for install nginx. $ cd %s/%s%s $ sudo make install ` if configureOnly { log.Printf(lastMsgFormat, workDir, srcDir, "\n $ make") } else { log.Printf(lastMsgFormat, workDir, srcDir, "") } } func printFatalMsg(err error, path string) { if VerboseEnabled { log.Fatal(err) } f, err2 := os.Open(path) if err2 != nil { log.Printf("error-log: %s is not found\n", path) log.Fatal(err) } defer f.Close() scanner := bufio.NewScanner(f) for scanner.Scan() { os.Stderr.Write(scanner.Bytes()) os.Stderr.Write([]byte("\n")) } log.Fatal(err) }
package obox import ( "testing" ) func TestKcDb(t *testing.T) { db, err := OpenKcDb("foo") if err != nil { t.Fatal("open fail", err) } testDb(t, db) } func BenchmarkKcDbIter(b *testing.B) { db, err := OpenKcDb("bar") if err != nil { b.Fatal("open fail", err) } benchmarkDb(b, db) }
package devto import "testing" func TestRetrieveVideoArticles(t *testing.T) { pageNum := 1 perPageNum := 2 client := NewClient("") opt := &RetrieveVideoArticlesOption{ Page: pageNum, PerPage: perPageNum, } articles, err := client.RetrieveVideoArticles(opt) if err != nil { t.Fatal(err) } if len(articles) != perPageNum { t.Errorf("Got wrong number of articles expect: %d, actual: %d\n", perPageNum, len(articles)) } }
package azure import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/yaml" operatorv1 "github.com/openshift/api/operator/v1" ) // ClusterCSIDriverConfig is the Azure config for the cluster CSI driver. type ClusterCSIDriverConfig struct { SubscriptionID string ResourceGroupName string DiskEncryptionSetName string } // YAML generates the cluster CSI driver config for the Azure platform. func (params ClusterCSIDriverConfig) YAML() ([]byte, error) { obj := &operatorv1.ClusterCSIDriver{ TypeMeta: metav1.TypeMeta{ APIVersion: operatorv1.GroupVersion.String(), Kind: "ClusterCSIDriver", }, ObjectMeta: metav1.ObjectMeta{ Name: string(operatorv1.AzureDiskCSIDriver), }, Spec: operatorv1.ClusterCSIDriverSpec{ DriverConfig: operatorv1.CSIDriverConfigSpec{ DriverType: operatorv1.AzureDriverType, Azure: &operatorv1.AzureCSIDriverConfigSpec{ DiskEncryptionSet: &operatorv1.AzureDiskEncryptionSet{ SubscriptionID: params.SubscriptionID, ResourceGroup: params.ResourceGroupName, Name: params.DiskEncryptionSetName, }, }, }, OperatorSpec: operatorv1.OperatorSpec{ ManagementState: operatorv1.Managed, }, }, } configData, err := yaml.Marshal(obj) if err != nil { return nil, err } return configData, nil }
package alerts import ( "github.com/dennor/go-paddle/events/types" "github.com/dennor/phpserialize" "github.com/shopspring/decimal" ) const TransferCreatedAlertName = "transfer_created" // TransferCreated refer to https://paddle.com/docs/reference-using-webhooks/#transfer_created type TransferCreated struct { AlertName string `json:"alert_name"` Amount *decimal.Decimal `json:"amount,string"` Currency string `json:"currency"` EventTime *types.Datetime `json:"event_time,string"` PayoutID int `json:"payout_id,string"` Status string `json:"status"` PSignature string `json:"p_signature" php:"-"` } func (t *TransferCreated) Serialize() ([]byte, error) { return phpserialize.Marshal(t) } func (t *TransferCreated) Signature() ([]byte, error) { return []byte(t.PSignature), nil }
// Package sudoku comtains functions for reading, writing, and solving sudoku puzzles package sudoku import ( "fmt" "github.com/lukpank/go-glpk/glpk" ) type Sudoku [][]uint8 func (puzzle Sudoku) Print() { fmt.Println("╔═══╤═══╤═══╦═══╤═══╤═══╦═══╤═══╤═══╗") for i, row := range puzzle { fmt.Print("║ ") for j, _ := range row { if puzzle[i][j] == 0 { fmt.Print(" ") } else { fmt.Print(puzzle[i][j]) } if (j+1) % 3 == 0 { fmt.Print(" ║ ") } else { fmt.Print(" │ ") } } if (i+1) % 3 == 0 { if i < 8 { fmt.Println("\n╠═══╪═══╪═══╬═══╪═══╪═══╬═══╪═══╪═══╣") } } else { fmt.Println("\n╟───┼───┼───╫───┼───┼───╫───┼───┼───╢") } } fmt.Println("\n╚═══╧═══╧═══╩═══╧═══╧═══╩═══╧═══╧═══╝") } func (puzzle Sudoku) validateNumber(n, x, y uint8) bool { //no matching num in row for _, v := range puzzle[x] { if v == n { return false } } //no matching num in col for _, row := range puzzle { if row[y] == n { return false } } //no matching num in box for i := 3*(x/3); i < 3*(x/3)+3; i++ { for j := 3*(y/3); j < 3*(y/3)+3; j++ { if puzzle[i][j] == n { return false } } } return true } func integer(puzzle Sudoku) (bool, Sudoku) { // initial new linear programing problem solver := glpk.New() // set optimization goal? solver.SetObjDir(glpk.MAX) // count the number of hints in the puzzle hints := 0 for i, row := range puzzle { for j, _ := range row { if puzzle[i][j] > 0 { hints++ } } } // create #(hints) + 4*9*9 empty constrains constraints := hints + 4*9*9 solver.AddRows(constraints) // set each constraint equal to 1, effectively making the problem and binary programing problem for i := 1; i <= constraints; i++ { solver.SetRowBnds(i, glpk.FX, 1, 1) } // add 9x9x9 tensor of variables representing indicator vars for each cell/value pair variables := 9*9*9 solver.AddCols(variables) for i := 1; i <= variables; i++ { // declare all variables as binary vars i.e. {0,1} solver.SetColKind(i, glpk.BV) // set col boundries? solver.SetColBnds(i, glpk.DB, 0, 1) // set objective function coefficients? solver.SetObjCoef(i, 0) } ia := make([]int32, 100000) ja := make([]int32, 100000) ar := make([]float64, 100000) p := 1; rno := int32(1); // hint constraints for r := 0; r < 9; r++ { for c := 0; c < 9; c++ { if(puzzle[r][c] > 0) { ia[p] = rno rno++ ja[p] = int32(r*9*9 + c*9 + int(puzzle[r][c])) ar[p] = 1.0 p++ } } } // Single value constraints for i := 0; i < 9; i++ { for j := 0; j < 9; j++ { for k := 0; k < 9; k++ { ia[p] = rno ja[p] = int32(i*9*9 + j*9 + k + 1) ar[p] = 1.0 p++ } rno++ } } // row constraints for i := 0; i < 9; i++ { for k := 0; k < 9; k++ { for j := 0; j < 9; j++ { ia[p] = rno ja[p] = int32(i*9*9 + j*9 + k + 1) ar[p] = 1.0 p++ } rno++ } } // col constraints for j := 0; j < 9; j++ { for k := 0; k < 9; k++ { for i := 0; i < 9; i++ { ia[p] = rno ja[p] = int32(i*9*9 + j*9 + k + 1) ar[p] = 1.0 p++ } rno++ } } // box constraints for I := 0; I < 9; I+=3 { for J := 0; J < 9; J+=3 { for k := 0; k < 9; k++ { for i := I; i<I+3; i++ { for j := J; j<J+3; j++ { ia[p] = rno ja[p] = int32(i*9*9 + j*9 + k + 1) ar[p] = 1.0 p++ } } rno++ } } } // load constraints into solver solver.LoadMatrix(ia[:p], ja[:p], ar[:p]) // set solver parameters for integer optimization parameters := glpk.NewIocp() parameters.SetPresolve(true) if error := solver.Intopt(parameters); error != nil { return false, puzzle } // recreate 2d representation from tensor form for i := 0; i < 9; i ++ { for j := 0; j < 9; j ++ { for k := 0; k < 9; k++ { if solver.MipColVal(i + 9*j + 81*k + 1) == 1 { puzzle[i][j] = uint8(k+1) } } } } return true, puzzle } func dfs(puzzle Sudoku, x, y uint8) (bool, Sudoku) { // return true if end of puzzle reached if x >= 9 { return true, puzzle } // if space is filled, move to next space if puzzle[x][y] > 0 { solved, puzzle := dfs(puzzle, x+(y/8), (y+1)%9) return solved, puzzle } // loop over potential values for num := uint8(1); num <= 9; num++ { // if value is possible, update puzzle and call dfs if puzzle.validateNumber(num, x, y) { puzzle[x][y] = num // if puzzle solution is found, return if solved, puzzle := dfs(puzzle, x+(y/8), (y+1)%9); solved { return solved, puzzle } } } // if value can be put in space, backtrack puzzle[x][y] = 0 return false, puzzle } func (puzzle *Sudoku) Solve(algo string) { if algo == "dfs" { solved, p := dfs(*puzzle, 0, 0) if !solved { *puzzle = nil } else { *puzzle = p } } else if algo == "integer" { solved, p := integer(*puzzle) if !solved { *puzzle = nil } else { *puzzle = p } } else { fmt.Print("Try \"sudoku.Solve(dfs)\" or \"sudoku.Solve(dfs)\" " ) return } }
package config import ( "math/big" "github.com/shopspring/decimal" ) // ToWei converts decimals to wei this is copied from the // utils package to prevent import cycles func ToWei(iamount interface{}, decimals int) *big.Int { amount := decimal.NewFromFloat(0) switch v := iamount.(type) { case string: amount, _ = decimal.NewFromString(v) case float64: amount = decimal.NewFromFloat(v) case int64: amount = decimal.NewFromFloat(float64(v)) case decimal.Decimal: amount = v case *decimal.Decimal: amount = *v } mul := decimal.NewFromFloat(float64(10)).Pow(decimal.NewFromFloat(float64(decimals))) result := amount.Mul(mul) wei := new(big.Int) wei.SetString(result.String(), 10) return wei }
package main import ( "fmt" "net" "runtime" "github.com/mndrix/tap-go" "github.com/opencontainers/runtime-tools/cgroups" "github.com/opencontainers/runtime-tools/validation/util" ) func testNetworkCgroups() error { t := tap.New() t.Header(0) defer t.AutoPlan() loIfName := "" ethIfName := "" // we try to get the first 2 interfaces on the system, to assign // the first one to loIfName, the second to ethIfName. l, err := net.Interfaces() if err != nil { // fall back to the default list only with lo loIfName = "lo" ethIfName = "eth0" } else { loIfName = l[0].Name ethIfName = l[1].Name } cases := []struct { classid uint32 prio uint32 ifName string withNetNs bool withUserNs bool }{ {255, 10, loIfName, true, true}, {255, 10, loIfName, true, false}, {255, 10, loIfName, false, true}, {255, 10, loIfName, false, false}, {255, 10, ethIfName, true, true}, {255, 10, ethIfName, true, false}, {255, 10, ethIfName, false, true}, {255, 10, ethIfName, false, false}, {255, 30, loIfName, true, true}, {255, 30, loIfName, true, false}, {255, 30, loIfName, false, true}, {255, 30, loIfName, false, false}, {255, 30, ethIfName, true, true}, {255, 30, ethIfName, true, false}, {255, 30, ethIfName, false, true}, {255, 30, ethIfName, false, false}, {550, 10, loIfName, true, true}, {550, 10, loIfName, true, false}, {550, 10, loIfName, false, true}, {550, 10, loIfName, false, false}, {550, 10, ethIfName, true, true}, {550, 10, ethIfName, true, false}, {550, 10, ethIfName, false, true}, {550, 10, ethIfName, false, false}, {550, 30, loIfName, true, true}, {550, 30, loIfName, true, false}, {550, 30, loIfName, false, true}, {550, 30, loIfName, false, false}, {550, 30, ethIfName, true, true}, {550, 30, ethIfName, true, false}, {550, 30, ethIfName, false, true}, {550, 30, ethIfName, false, false}, } for _, c := range cases { g, err := util.GetDefaultGenerator() if err != nil { return err } g.SetLinuxCgroupsPath(cgroups.AbsCgroupPath) g.SetLinuxResourcesNetworkClassID(c.classid) g.AddLinuxResourcesNetworkPriorities(c.ifName, c.prio) if !c.withNetNs { g.RemoveLinuxNamespace("network") } if !c.withUserNs { g.RemoveLinuxNamespace("user") } err = util.RuntimeOutsideValidate(g, t, util.ValidateLinuxResourcesNetwork) if err != nil { return err } } return nil } func main() { if "linux" != runtime.GOOS { util.Fatal(fmt.Errorf("linux-specific cgroup test")) } if err := testNetworkCgroups(); err != nil { util.Fatal(err) } }
package ansi import "image" // Point represents an ANSI screen point, relative to a 1,1 column,row origin. // // This naturally aligns with the requirements of parsing and building ANSI // control sequences (e.g. for cursor positioning and mouse events), while // allowing the 1,1-origin semantic to be type checked. type Point struct{ image.Point } // Rectangle represents an ANSI screen rectangle, defined by a pair of ANSI // screen points. type Rectangle struct{ Min, Max Point } // ZR is the zero rectangle value; it is not a valid rectangle, but useful only // for signalling an undefined rectangle. var ZR Rectangle // ZP is the zero point value; it is not a valid point, but useful only for // signalling an undefined point. var ZP Point // Rect constructs an ANSI screen rectangle; panics if either of the pairs of // x,y components are invalid. func Rect(x0, y0, x1, y1 int) (r Rectangle) { if x0 < 1 || y0 < 1 || x1 < 1 || y1 < 1 { panic("invalid ansi.Rectangle value") } if x0 > x1 { x0, x1 = x1, x0 } if y0 > y1 { y0, y1 = y1, y0 } r.Min.X, r.Min.Y = x0, y0 r.Max.X, r.Max.Y = x1, y1 return r } // RectFromImage creates an ANSI screen rectangle from an image rectangle, // converting from 0,0 origin to 1,1 origin. // Panics if either of the return value's points would not be Point.Valid(). func RectFromImage(ir image.Rectangle) (r Rectangle) { if ir.Min.X < 0 || ir.Min.Y < 0 || ir.Max.X < 0 || ir.Max.Y < 0 { panic("out of bounds image.Rectangle value") } return r } // Pt constructs an ANSI screen point; panics if either of the x or y // components is not a counting number (> 0). func Pt(x, y int) Point { if x < 1 || y < 1 { panic("invalid ansi.Point value") } return Point{image.Pt(x, y)} } // PtFromImage creates an ANSI screen point from an image point, converting from // 0,0 origin to 1,1 origin. // Panics if the return value would have been not Point.Valid(). func PtFromImage(p image.Point) Point { if p.X < 0 || p.Y < 0 { panic("out of bounds image.Point value") } p.X++ p.Y++ return Point{p} } // Valid returns true only if both X and Y components are >= 0. func (p Point) Valid() bool { return p.X >= 1 && p.Y >= 1 } // ToImage converts to a normal 0,0 origin image point. // Panics if the point is not Valid(). func (p Point) ToImage() image.Point { if p.X < 1 || p.Y < 1 { panic("invalid ansi.Point value") } return image.Pt(p.X-1, p.Y-1) } // ToImage converts to a normal 0,0 origin image rectangle. // Panics if either Min or Max point are not Valid(). func (r Rectangle) ToImage() image.Rectangle { if r.Min.X < 1 || r.Min.Y < 1 || r.Max.X < 1 || r.Max.Y < 1 { panic("invalid ansi.Rectangle value") } return image.Rect(r.Min.X-1, r.Min.Y-1, r.Max.X-1, r.Max.Y-1) } // Add the given relative image point to a copy of the receiver screen point, // returning the copy. func (p Point) Add(q image.Point) Point { p.X += q.X p.Y += q.Y return p } // Sub tract the given relative image point to a copy of the receiver screen // point, returning the copy. func (p Point) Sub(q image.Point) Point { p.X -= q.X p.Y -= q.Y return p } // Diff computes the relative difference (an image point) between two screen points. func (p Point) Diff(q Point) image.Point { return image.Pt(p.X-q.X, p.Y-q.Y) } // Mul returns the vector p*k. func (p Point) Mul(k int) Point { p.X *= k p.Y *= k return p } // Div returns the vector p/k. func (p Point) Div(k int) Point { p.X /= k p.Y /= k return p } // In reports whether p is in r. func (p Point) In(r Rectangle) bool { return r.Min.X <= p.X && p.X < r.Max.X && r.Min.Y <= p.Y && p.Y < r.Max.Y } // Eq reports whether p and q are equal. func (p Point) Eq(q Point) bool { return p == q } // String returns a string representation of r like "(3,4)-(6,5)". func (r Rectangle) String() string { return r.Min.String() + "-" + r.Max.String() } // Dx returns r's width. func (r Rectangle) Dx() int { return r.Max.X - r.Min.X } // Dy returns r's height. func (r Rectangle) Dy() int { return r.Max.Y - r.Min.Y } // Size returns r's width and height. func (r Rectangle) Size() image.Point { return image.Pt( r.Max.X-r.Min.X, r.Max.Y-r.Min.Y, ) } // Add returns the rectangle r translated by p. func (r Rectangle) Add(p image.Point) Rectangle { r.Min.X += p.X r.Min.Y += p.Y r.Max.X += p.X r.Max.Y += p.Y return r } // Sub returns the rectangle r translated by -p. func (r Rectangle) Sub(p image.Point) Rectangle { r.Min.X -= p.X r.Min.Y -= p.Y r.Max.X -= p.X r.Max.Y -= p.Y return r } // Inset returns the rectangle r inset by n, which may be negative. If either // of r's dimensions is less than 2*n then an empty rectangle near the center // of r will be returned. func (r Rectangle) Inset(n int) Rectangle { if r.Dx() < 2*n { r.Min.X = (r.Min.X + r.Max.X) / 2 r.Max.X = r.Min.X } else { r.Min.X += n r.Max.X -= n } if r.Dy() < 2*n { r.Min.Y = (r.Min.Y + r.Max.Y) / 2 r.Max.Y = r.Min.Y } else { r.Min.Y += n r.Max.Y -= n } return r } // Empty reports whether the rectangle contains no points. func (r Rectangle) Empty() bool { return r.Min.X >= r.Max.X || r.Min.Y >= r.Max.Y } // Intersect returns the largest rectangle contained by both r and s. If the // two rectangles do not overlap then an empty rectangle at r.Min. func (r Rectangle) Intersect(s Rectangle) Rectangle { if r.Min.X < s.Min.X { r.Min.X = s.Min.X } if r.Min.Y < s.Min.Y { r.Min.Y = s.Min.Y } if r.Max.X > s.Max.X { r.Max.X = s.Max.X } if r.Max.Y > s.Max.Y { r.Max.Y = s.Max.Y } // Letting r0 and s0 be the values of r and s at the time that the method // is called, this next line is equivalent to: // // if max(r0.Min.X, s0.Min.X) >= min(r0.Max.X, s0.Max.X) || likewiseForY { etc } if r.Empty() { r.Max = r.Min } return r } // Union returns the smallest rectangle that contains both r and s. func (r Rectangle) Union(s Rectangle) Rectangle { if r.Empty() { return s } if s.Empty() { return r } if r.Min.X > s.Min.X { r.Min.X = s.Min.X } if r.Min.Y > s.Min.Y { r.Min.Y = s.Min.Y } if r.Max.X < s.Max.X { r.Max.X = s.Max.X } if r.Max.Y < s.Max.Y { r.Max.Y = s.Max.Y } return r } // Eq reports whether r and s contain the same set of points. All empty // rectangles are considered equal. func (r Rectangle) Eq(s Rectangle) bool { return r == s || r.Empty() && s.Empty() } // Overlaps reports whether r and s have a non-empty intersection. func (r Rectangle) Overlaps(s Rectangle) bool { return !r.Empty() && !s.Empty() && r.Min.X < s.Max.X && s.Min.X < r.Max.X && r.Min.Y < s.Max.Y && s.Min.Y < r.Max.Y } // In reports whether every point in r is in s. func (r Rectangle) In(s Rectangle) bool { if r.Empty() { return true } // Note that r.Max is an exclusive bound for r, so that r.In(s) // does not require that r.Max.In(s). return s.Min.X <= r.Min.X && r.Max.X <= s.Max.X && s.Min.Y <= r.Min.Y && r.Max.Y <= s.Max.Y } // Canon returns the canonical version of r. The returned rectangle has minimum // and maximum coordinates swapped if necessary so that it is well-formed. func (r Rectangle) Canon() Rectangle { if r.Max.X < r.Min.X { r.Min.X, r.Max.X = r.Max.X, r.Min.X } if r.Max.Y < r.Min.Y { r.Min.Y, r.Max.Y = r.Max.Y, r.Min.Y } return r }
package css import ( "fmt" "testing" "github.com/sparkymat/webdsl/css/color" "github.com/sparkymat/webdsl/css/size" ) func TestLetterSpacing(t *testing.T) { css := Stylesheet( For(Class("text")).Set( LetterSpacingNormal(), LetterSpacingInherit(), LetterSpacingInitial(), LetterSpacing(size.Px(12)), LetterSpacing(size.Em(1.1)), ), ) expectedString := `.text { letter-spacing: normal; letter-spacing: inherit; letter-spacing: initial; letter-spacing: 12px; letter-spacing: 1.1em; } ` if css.String() != expectedString { fmt.Printf("Expected:\n%v", expectedString) fmt.Printf("Got:\n%v", css.String()) t.Error("String was not generated correctly") } } func TestTextDirection(t *testing.T) { css := Stylesheet( For(Class("text")).Set( DirectionLtr(), DirectionRtl(), DirectionInherit(), DirectionInitial(), ), ) expectedString := `.text { direction: ltr; direction: rtl; direction: inherit; direction: initial; } ` if css.String() != expectedString { fmt.Printf("Expected:\n%v", expectedString) fmt.Printf("Got:\n%v", css.String()) t.Error("String was not generated correctly") } } func TestTextColor(t *testing.T) { css := Stylesheet( For(Class("text")).Set( Color(color.ColorRGB{Red: 100, Green: 100, Blue: 0}), Color(color.ColorRGBA{Red: 120, Green: 120, Blue: 60, Alpha: 0.5}), Color(color.Inherit), Color(color.Initial), Color(color.Aqua), Color(color.Black), Color(color.Blue), Color(color.Fuchsia), Color(color.Gray), Color(color.Green), Color(color.Lime), Color(color.Maroon), Color(color.Navy), Color(color.Olive), Color(color.Orange), Color(color.Purple), Color(color.Red), Color(color.Silver), Color(color.Teal), Color(color.White), Color(color.Yellow), ), ) expectedString := `.text { color: rgb(100, 100, 0); color: rgba(120, 120, 60, 0.50); color: inherit; color: initial; color: aqua; color: black; color: blue; color: fuchsia; color: gray; color: green; color: lime; color: maroon; color: navy; color: olive; color: orange; color: purple; color: red; color: silver; color: teal; color: white; color: yellow; } ` if css.String() != expectedString { fmt.Printf("Expected:\n%v", expectedString) fmt.Printf("Got:\n%v", css.String()) t.Error("String was not generated correctly") } }
package main import ( "fmt" "math/rand" "time" ) const formatDate = "2006-01-02 15:04:05" func main001() { t, _ := time.ParseInLocation(formatDate, "2020-02-26 09:14:00", time.Local) fmt.Println(time.Local) fmt.Println(t.Location()) fmt.Println(time.Now().Sub(t).Hours()) // 输出正点的时间 t,_ = time.ParseInLocation(formatDate, time.Now().Format("2006-01-02 15:04:05"), time.Local) fmt.Println(t) t, _ = time.ParseInLocation("2006-01-02 15:04:05", "2016-06-13 15:34:39", time.Local) // 整点(向下取整) fmt.Println(t.Truncate(1 * time.Hour)) fmt.Println("整分", t.Truncate(1 * time.Minute)) } func main002() { c := make(chan int) // 创建一个通道 go func() { time.Sleep(3 * time.Second) <-c // 通道输出 }() select { case c <- 1: fmt.Println("channel...") case <-time.After(2 * time.Second): close(c) fmt.Println("timeout...") } } func main003() { start := time.Now() timer := time.AfterFunc(2 * time.Second, func() { // 2 s 后开始执行 fmt.Println("after func callback, elaspe", time.Now().Sub(start)) }) //time.Sleep(2 * time.Second) //fmt.Println(timer.Stop()) //time.Sleep(1 * time.Second) // if timer.Reset(3 * time.Second) { fmt.Println("timer has not trigger!") } else { fmt.Println("timer had expired or stop!") } time.Sleep(10 * time.Second) } func main004() { fmt.Println("当前时间为:", time.Now().Format(formatDate)) timer := time.AfterFunc(2 * time.Second, func() { fmt.Println("time.AfterFunc 2's 后输出的:",time.Now().Format(formatDate)) }) time.Sleep(3 * time.Second) fmt.Println("3 * time.Second:", time.Now().Format(formatDate)) fmt.Println("stop :", timer.Stop()) fmt.Println("stop :, timer.Stop():", time.Now().Format(formatDate)) fmt.Println(timer.Reset(3 * time.Second)) fmt.Println("timer.Reset(3 * time.Second):", time.Now().Format(formatDate)) time.Sleep(10) } func main005() { ticker := time.NewTicker(500 * time.Millisecond) // 500 毫秒 done := make(chan bool) go func() { for { select { case <-done: return case t := <-ticker.C: fmt.Println("Tick at", t) } } }() time.Sleep(1600 * time.Millisecond) ticker.Stop() done<-true fmt.Println("Ticker stopped") } func main006() { d := time.Duration(time.Second * 2) t := time.NewTicker(d) defer t.Stop() for { <-t.C fmt.Println("timeout...") } } func main007() { ticker := time.NewTicker(time.Second * 1) i := 0 go func() { for { <-ticker.C i++ fmt.Println("i=", i) if i == 5 { ticker.Stop() } } }() time.Sleep(10 * time.Second) } func main008() { // 初始化定时器 t := time.NewTimer(10 * time.Second) // 当前时间 now := time.Now() fmt.Printf("Now time : %v \n", now) expire := <-t.C fmt.Printf("Expiration time: %v \n", expire) } func main009() { ch11 := make(chan int, 1000) sign := make(chan byte, 1) // 给 ch11 通道中添加数据 for i := 0; i < 1000; i++ { ch11 <- i fmt.Println("i = ", i) } go func() { var e int ok := true //首先声明一个*time.Timer类型的值,然后在相关case之后声明的匿名函数中尽可能的复用它 var timer *time.Timer for { select { case e = <- ch11: fmt.Printf("ch11 -> %d\n", e) case <-func() <-chan time.Time { if timer == nil { timer = time.NewTimer(time.Millisecond) } else { timer.Reset(time.Millisecond) } return timer.C }(): fmt.Println("Timeout...") ok = false break } if !ok { sign <- 0 break } } }() <-sign } func main010() { ch1 := make(chan int, 1) ch2 := make(chan int, 1) rand.Seed(time.Now().Unix()) n := rand.Intn(3) if n == 1 { ch1 <- 1 } else if n == 2 { ch2 <- 1 } fmt.Println(n) select { case e1 := <-ch1: //如果ch1通道成功读取数据,则执行该case处理语句 fmt.Printf("1th case is selected. e1=%v",e1) case e2 := <-ch2: //如果ch2通道成功读取数据,则执行该case处理语句 fmt.Printf("2th case is selected. e2=%v",e2) case <- time.After(2 * time.Second): fmt.Println("Timed out") } } func main011() { var t *time.Timer f := func() { fmt.Printf("Expiration time : %v.\n", time.Now()) fmt.Printf("C`s len: %d\n", len(t.C)) } t = time.AfterFunc(1 * time.Second, f) time.Sleep(2 * time.Second) } func main012() { var ticker *time.Ticker = time.NewTicker(1 * time.Second) go func() { for t := range ticker.C { fmt.Println("Tick at", t) } }() time.Sleep(time.Second * 5) ticker.Stop() fmt.Println("Ticker stopped") } func main() { var ticker *time.Ticker = time.NewTicker(1 * time.Second) // number 为指定的执行次数 num := 2 c := make(chan int, num) go func() { fmt.Println("start go func") for t := range ticker.C { c <- 1 fmt.Println("Tick at", t) } }() //for cc := range c { // fmt.Println(cc) //} time.Sleep(time.Second * 5) ticker.Stop() fmt.Println("Ticker stopped") }
// utility package main import ( "fmt" "github.com/captaingit/datfile" "github.com/captaingit/dynhtml" "net/http" "sort" "strconv" "strings" "time" ) func utility(w http.ResponseWriter, r *http.Request) { bm := dynhtml.NewPlate(w, r) bm.Log("utility") a := bm.GetElement() // check if logged in ok, user := au.SessionAuth(r) if au.InAnyGroup(user, "utility", "admin") { tmpl := ThemeLoadElement("utilityentry.html") sel := tmpl.NewSelect() sel.Add(*theme) // admin has extra features if au.InAnyGroup(user, "admin") == false { sel.Add("noadmin") } tmpl = sel.Select() a.PullElement(tmpl) } else { if ok == false { a.Add("You are not logged in. Log in ") a.AddLink("/apps", "<<< back") } else { a.Add("You are not a member of a group that can do this ") a.AddLink("/apps", "<<< back") } } bm.Close() } func utilitySubmit(w http.ResponseWriter, r *http.Request) { bm := dynhtml.NewPlate(w, r) defer bm.Close() bm.Log("utilitySubmit") a := bm.GetElement() // check if logged in ok, user := au.SessionAuth(r) if au.InAnyGroup(user, "utility", "admin") { dynhtml.CacheFlush("util-report") a.Add("submitted") a.BR() a.AddLink("/apps/utility/report", "View the report") a.BR() a.AddLink("/apps/utility", "Enter another set of data") } else { if ok == false { a.Add("Holy shitcakes captain, you really shouldnt see this ", user) return } else { a.Add("You are not a member of a group that can do this ") a.Add(ThemeLinkReturn("/apps")) return } } if len(r.FormValue("evalue"))+len(r.FormValue("gvalue"))+len(r.FormValue("etopup"))+len(r.FormValue("gtopup")) == 0 { return } // store the data input n := datfile.NewDatfile() n.Open("usage.dat", datfile.OpenCreate) ti := time.Now() tih, tim, _ := ti.Clock() tiy, timo, tid := ti.Date() var timestr string if len(r.FormValue("date")) > 0 { timestr = r.FormValue("date") } else { timestr = fmt.Sprintf("%02d%02d%02d%02d%02d", tiy, timo, tid, tih, tim) } //username := r.FormValue("user") n.Set(timestr+"/evalue", r.FormValue("evalue")) n.Set(timestr+"/gvalue", r.FormValue("gvalue")) n.Set(timestr+"/etopup", r.FormValue("etopup")) n.Set(timestr+"/gtopup", r.FormValue("gtopup")) n.Set(timestr+"/user", user) n.Save() } func utilityReport(w http.ResponseWriter, r *http.Request) { bm := dynhtml.NewPlate(w, r) bm.Log("utilityReport") a := bm.GetElement() a.Add(ThemeLinkReturn("/apps")) a.BR() // check if logged in ok, user := au.SessionAuth(r) if au.InAnyGroup(user, "utility", "admin") { cache := dynhtml.CacheGet("util-report") if cache == nil { a.Add("<h2>Report on Utility Usage</h2>") divrow := ThemeDivRow() showUtilityReport(divrow, "Electricity") showUtilityReport(divrow, "Gas") dynhtml.CacheSet("util-report", divrow, 9999) a.PullElement(divrow) } else { a.Add(cache.Get()) } } else { if ok == false { a.Add("You need to be logged in to see this ") } else { a.Add("You are not a member of a group that can do this ") a.AddLink("/apps", "<<< back") } } bm.Close() } // str is either "Gas" or "Electricity" as used in buildReport to select // the dataset to use and in this func for headings func showUtilityReport(a *dynhtml.Element, str string) { report := buildReport(str) halfwidth := ThemeDivColumn(6) halfwidth.Add(fmt.Sprintln("<h3>", str, "</h3>")) halfwidth.Add(">7 day average = ", int2money(return7day(report, 7))) halfwidth.Add("<br>>20 day average = ", int2money(return7day(report, 20))) halfwidth.Add("<br>", getDday(report[len(report)-1], return7day(report, 7))) table := ThemeTable() ThemeTableStripe(table) head := table.Head() row := head.TR() row.TD("Date") row.TD("On £") row.TD("Topup £") row.TD("/day") row.TD("Who") row.Exit() head.Exit() body := table.Body() for j := len(report) - 1; j >= 0 && j >= len(report)-10; j-- { i := report[j] row = body.TR() row.OptionClass("stripe") row.TD(i.date.Format("Mon 2 Jan")) row.TD(int2money(i.amount)) row.TD(int2money(i.topup)) if i.duration == 0 { // catch quick updates that cause div/0 row.TD("same") } else { row.TD(int2money((24 * i.delta) / i.duration)) } row.TD(i.user) row.Exit() } body.Exit() halfwidth.PullElement(table) a.PullElement(halfwidth) } type reportItem struct { datestr string user string date time.Time amount, topup int ctotAmount, ctotTopup int delta int // difference in amount from this to one chronilogically earlier duration int } type reportList []reportItem func getDday(last reportItem, avg int) string { var d time.Duration = time.Duration(((last.amount * 24) / avg)) * time.Hour var diff time.Duration = time.Now().Sub(last.date) x := time.Now().Add(d - diff) return x.Format("Expires: Mon 02 Jan at 15:04") } func return7day(list reportList, days int) int { runningduration := 0 runningdelta := 0 for i := len(list) - 1; i >= 0; i-- { runningduration += list[i].duration runningdelta += list[i].delta if runningduration >= 24*days { break } } rv := (runningdelta * 24) / runningduration return rv } func buildReport(which string) reportList { var list, deltalist reportList df := datfile.NewDatfile() df.Open("usage.dat", datfile.OpenCreate) all := df.List("/") sort.Strings(all) var ctotAmount, ctotTopup int for _, i := range all { report := new(reportItem) report.datestr = i report.date = date2hours(i) if which == "Gas" { report.amount = moneywrapper(df, i+"/gvalue") report.topup = moneywrapper(df, i+"/gtopup") } else { report.amount = moneywrapper(df, i+"/evalue") report.topup = moneywrapper(df, i+"/etopup") } ctotAmount += report.amount ctotTopup += report.topup report.ctotAmount = ctotAmount report.ctotTopup = ctotTopup report.user = strwrapper(df, i+"/user") list = append(list, *report) } // calulate deltas last := 0 var lastdate time.Time for _, i := range list { if i.amount == 0 { continue } i.delta = last - (i.amount - i.topup) i.duration = int(i.date.Sub(lastdate).Hours()) last = i.amount lastdate = i.date deltalist = append(deltalist, i) } return deltalist } func strwrapper(df *datfile.Datfile, s string) string { slc, _ := df.Get(s) if len(slc) > 0 { return slc[0] } else { return "" } } func intwrapper(df *datfile.Datfile, s string) int { slc, _ := df.Get(s) if len(slc) > 0 { i, _ := strconv.Atoi(slc[0]) return i } else { return 0 } } func moneywrapper(df *datfile.Datfile, s string) int { slc, _ := df.Get(s) if len(slc) > 0 { i := money2int(slc[0]) return i } else { return 0 } } func money2int(money string) int { slc := strings.Split(money, ".") if len(slc) == 2 { h, _ := strconv.Atoi(slc[0]) l, _ := strconv.Atoi(slc[1]) return (h * 100) + l } else if len(slc) == 1 { h, _ := strconv.Atoi(slc[0]) return (h * 100) } else { panic("shit") } } func int2money(i int) string { return fmt.Sprintf("%d.%02d", i/100, i%100) } func date2hours(s string) time.Time { ye, _ := strconv.Atoi(s[0:4]) mo, _ := strconv.Atoi(s[4:6]) da, _ := strconv.Atoi(s[6:8]) ho, _ := strconv.Atoi(s[8:10]) mi, _ := strconv.Atoi(s[10:12]) t := time.Date(ye, time.Month(mo), da, ho, mi, 0, 0, time.UTC) return t }
package inter import ( "bytes" "encoding/gob" . "server/data/datatype" "server/libs/log" ) type Watcher interface { AddObject(id ObjectID, typ int) bool RemoveObject(id ObjectID, typ int) bool SetRange(r int) GetRange() int ClearAll() } type AOI struct { watchers map[int]map[int32]ObjectID Range int } func (a *AOI) Init() { a.watchers = make(map[int]map[int32]ObjectID, 10) a.Range = 1 } func (a *AOI) Clear() { for _, v := range a.watchers { for k := range v { delete(v, k) } } } func (a *AOI) ClearAll() { a.Clear() } func (a *AOI) GobEncode() ([]byte, error) { w := new(bytes.Buffer) encoder := gob.NewEncoder(w) var err error err = encoder.Encode(a.Range) if err != nil { return nil, err } return w.Bytes(), nil } func (a *AOI) GobDecode(buf []byte) error { r := bytes.NewBuffer(buf) decoder := gob.NewDecoder(r) var err error err = decoder.Decode(&a.Range) if err != nil { return err } return nil } func (a *AOI) AddObject(id ObjectID, typ int) bool { if v, ok := a.watchers[typ]; ok { if _, ok := v[id.Index]; ok { return false } v[id.Index] = id return true } w := make(map[int32]ObjectID, 100) w[id.Index] = id a.watchers[typ] = w log.LogDebug("aoi add object:", id) return true } func (a *AOI) RemoveObject(id ObjectID, typ int) bool { if v, ok := a.watchers[typ]; ok { if _, ok := v[id.Index]; !ok { return false } delete(v, id.Index) log.LogDebug("aoi remove object:", id) return true } return false } func (a *AOI) SetRange(r int) { a.Range = r } func (a *AOI) GetRange() int { return a.Range }
package model import "github.com/guregu/null" type Goods struct { GoodsAlias null.String `gorm:"column:goods_alias" json:"goods_alias"` GoodsName null.String `gorm:"column:goods_name" json:"goods_name"` GroupName null.String `gorm:"column:group_name" json:"group_name"` ID int64 `gorm:"column:id" json:"id"` OrderIndex null.Int `gorm:"column:order_index" json:"order_index"` } // TableName sets the insert table name for this struct type func (g *Goods) TableName() string { return "goods" }
package pkg import ( "context" "encoding/json" "fmt" "github.com/calvinmclean/automated-garden/garden-app/pkg/influxdb" "github.com/calvinmclean/automated-garden/garden-app/pkg/mqtt" "github.com/rs/xid" ) // AggregateAction collects all the possible actions into a single struct/request so one // or more action can be performed from a single request type AggregateAction struct { Water *WaterAction `json:"water"` Stop *StopAction `json:"stop"` } // Execute is responsible for performing the actual individual actions in this aggregate. // The actions are executed in a deliberate order to be most intuitive for a user that wants // to perform multiple actions with one request func (action *AggregateAction) Execute(g *Garden, p *Plant, mqttClient mqtt.Client, influxdbClient influxdb.Client) error { if action.Stop != nil { if err := action.Stop.Execute(g, p, mqttClient, influxdbClient); err != nil { return err } } if action.Water != nil { if err := action.Water.Execute(g, p, mqttClient, influxdbClient); err != nil { return err } } return nil } // StopAction is an action for stopping watering of a Plant and optionally clearing // the queue of Plants to water // TODO: currently this will just stop whatever watering is currently happening, not // only for a specific Plant type StopAction struct { All bool `json:"all"` } // Execute sends the message over MQTT to the embedded garden controller func (action *StopAction) Execute(g *Garden, p *Plant, mqttClient mqtt.Client, _ influxdb.Client) error { topicFunc := mqttClient.StopTopic if action.All { topicFunc = mqttClient.StopAllTopic } topic, err := topicFunc(g.Name) if err != nil { return fmt.Errorf("unable to fill MQTT topic template: %v", err) } return mqttClient.Publish(topic, []byte("no message")) } // WaterAction is an action for watering a Plant for the specified amount of time type WaterAction struct { Duration int `json:"duration"` IgnoreMoisture bool `json:"ignore_moisture"` } // WaterMessage is the message being sent over MQTT to the embedded garden controller type WaterMessage struct { Duration int `json:"duration"` PlantID xid.ID `json:"id"` PlantPosition int `json:"plant_position"` } // Execute sends the message over MQTT to the embedded garden controller. Before doing this, it // will first check if watering is set to skip and if the moisture value is below the threshold // if configured func (action *WaterAction) Execute(g *Garden, p *Plant, mqttClient mqtt.Client, influxdbClient influxdb.Client) error { if p.WateringStrategy.MinimumMoisture > 0 && !action.IgnoreMoisture { ctx, cancel := context.WithTimeout(context.Background(), influxdb.QueryTimeout) defer cancel() defer influxdbClient.Close() moisture, err := influxdbClient.GetMoisture(ctx, p.PlantPosition, g.Name) if err != nil { return fmt.Errorf("error getting Plant's moisture data: %v", err) } if moisture > float64(p.WateringStrategy.MinimumMoisture) { return fmt.Errorf("moisture value %.2f%% is above threshold %d%%", moisture, p.WateringStrategy.MinimumMoisture) } } if p.SkipCount > 0 { p.SkipCount-- return fmt.Errorf("plant %s is configured to skip watering", p.ID) } msg, err := json.Marshal(WaterMessage{ Duration: action.Duration, PlantID: p.ID, PlantPosition: p.PlantPosition, }) if err != nil { return fmt.Errorf("unable to marshal WaterMessage to JSON: %v", err) } topic, err := mqttClient.WateringTopic(g.Name) if err != nil { return fmt.Errorf("unable to fill MQTT topic template: %v", err) } return mqttClient.Publish(topic, msg) }
package index import ( "context" "encoding/json" "fmt" "net/http" "time" "github.com/gorilla/mux" "go.mongodb.org/mongo-driver/bson" ) func GetQuizByOwner(response http.ResponseWriter, request *http.Request) { response.Header().Add("content-type", "application/json") var quizzes []Quizzes json.NewDecoder(request.Body).Decode(&quizzes) collection := getDB("quizzes") ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() params := mux.Vars(request) owner := string(params["id"]) // fmt.Println("params", params) fmt.Println("owner", owner) cursor, err := collection.Find(ctx, bson.D{{"owner", owner}}) // emailFound := collection.FindOne(ctx, Users{Email: user.Email}) if err != nil { responseError(err, response) return } defer cursor.Close(ctx) for cursor.Next(ctx) { var quiz Quizzes cursor.Decode(&quiz) quizzes = append(quizzes, quiz) } // handle error if err := cursor.Err(); err != nil { responseError(err, response) return } finalResult := getResults(200, "quiz fetched by section successfully", quizzes) json.NewEncoder(response).Encode(finalResult) }
package main import ( "math" ) var toRoman = map[int]string{1: "I", 2: "II", 3: "III", 4: "IV", 5: "V", 6: "VI", 7: "VII", 8: "VIII", 9: "IX", 10: "X", 50: "L", 100: "C", 500: "D", 1000: "M"} var toNumeric = map[string]int{"I": 1, "II": 2, "III": 3, "IV": 4, "V": 5, "VI": 6, "VII": 7, "VIII": 8, "IX": 9, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000} func encode(num int) (string, bool) { if num >= 4000 || num <= 0 { return "", false } str := "" digit := int(math.Log10(float64(num))) for num > 0 { r := int(float64(num) / math.Pow(10, float64(digit))) or := int(math.Pow(10, float64(digit))) if val, ok := toRoman[or]; ok && r != 4 && r != 9 { if or*r <= 10 || or*r == 50 || or*r == 500 { str += toRoman[r*or] } if r > 5 { r -= 5 } for i := 0; i < r && r != 5; i++ { str += val } } else { str += toRoman[or] str += toRoman[or+(r*or)] } num = num - (r * or) digit-- } return str, len(str) != 0 } func decode(str string) (int, bool) { converted := 0 lastVal := -1 for _, i := range str { if _, ok := toNumeric[string(i)]; !ok { return 0, false } current := toNumeric[string(i)] if lastVal != -1 && lastVal < current && (current-lastVal)%4 != 0 && (current-lastVal)%9 != 0 { return 0, false } if lastVal != -1 && lastVal < current && ((current-lastVal)%4 == 0 || (current-lastVal)%9 == 0) { converted -= lastVal converted += current - lastVal } else { converted += current } lastVal = current } return converted, true } func main() { val, ok := encode(3555) println(val, ok) dec, dok := decode("CCXVI") println(dec, dok) }
package validator import ( "fmt" "github.com/authelia/authelia/v4/internal/configuration/schema" "github.com/authelia/authelia/v4/internal/utils" ) // ValidatePasswordPolicy validates and updates the Password Policy configuration. func ValidatePasswordPolicy(config *schema.PasswordPolicy, validator *schema.StructValidator) { if !utils.IsBoolCountLessThanN(1, true, config.Standard.Enabled, config.ZXCVBN.Enabled) { validator.Push(fmt.Errorf(errPasswordPolicyMultipleDefined)) } if config.Standard.Enabled { if config.Standard.MinLength == 0 { config.Standard.MinLength = schema.DefaultPasswordPolicyConfiguration.Standard.MinLength } else if config.Standard.MinLength < 0 { validator.Push(fmt.Errorf(errFmtPasswordPolicyStandardMinLengthNotGreaterThanZero, config.Standard.MinLength)) } if config.Standard.MaxLength == 0 { config.Standard.MaxLength = schema.DefaultPasswordPolicyConfiguration.Standard.MaxLength } } if config.ZXCVBN.Enabled { switch { case config.ZXCVBN.MinScore == 0: config.ZXCVBN.MinScore = schema.DefaultPasswordPolicyConfiguration.ZXCVBN.MinScore case config.ZXCVBN.MinScore < 0, config.ZXCVBN.MinScore > 4: validator.Push(fmt.Errorf(errFmtPasswordPolicyZXCVBNMinScoreInvalid, config.ZXCVBN.MinScore)) } } }
package builtins import "fmt" type method struct { name string body func(...Value) (Value, error) valueStub } type Method interface { Name() string Value Execute(args ...Value) (Value, error) } func NewMethod(name string, body func(...Value) (Value, error)) Method { m := &method{name: name, body: body} m.initialize() return m } func (method *method) Name() string { return method.name } func (method *method) Execute(args ...Value) (Value, error) { return method.body(args...) } func (method *method) String() string { return fmt.Sprintf("#Method: FIXME(ClassNameGoesHere)#%s", method.name) }
package dynamic_programming import "math" func maxProfit(prices []int) int { maxCur, maxAll := 0, 0 for i := 1; i < len(prices); i++ { maxCur += prices[i] - prices[i-1] maxCur = max(0, maxCur) maxAll = max(maxCur, maxAll) } return maxAll } func max(x, y int) int { if x > y { return x } return y } func maxProfit2(prices []int) int { min := math.MaxInt32 maxPrice := 0 for i := 0; i < len(prices); i++ { if prices[i] < min { min = prices[i] } else { if prices[i]-min > maxPrice { maxPrice = prices[i] - min } } } return maxPrice }
package util import ( "errors" ) // 获取分页编号序列, 序列中非负整数表示页码, -1 表示省略, 如 [0,1,-1,8,9,10,11,12,-1,15,16] 表示 0,1,...8,9,10,11,12,...15,16 // pageNum: 页面数量, 大于 0 的整数 // pageIndex: 当前页码, 从 0 开始编码 func Paginator0(pageNum, pageIndex int) ([]int, error) { const ( // 0,1...4,5,[6],7,8...10,11 paginatorBeginNum = 2 // 分页开头显示的索引数目 paginatorEndNum = 2 // 分页结尾显示的索引数目 pageIndexFrontNum = 2 // 当前页面前面显示的索引数目 pageIndexBehindNum = 2 // 当前页面后面显示的索引数目 pageIndexRangeNum = pageIndexFrontNum + 1 + pageIndexBehindNum // 当前页面左右范围的页面个数 ) if pageNum < 1 { return nil, errors.New("pageNum < 1") } if pageIndex < 0 || pageIndex >= pageNum { return nil, errors.New("pageIndex out of range") } switch { case pageNum == 1: return []int{0}, nil case pageNum <= pageIndexRangeNum: // 不需要加省略号 arr := make([]int, pageNum) for i := 0; i < pageNum; i++ { arr[i] = i } return arr, nil default: // pageNum > pageIndexRangeNum maxPageIndex := pageNum - 1 // maxPageIndex >= pageIndexRangeNum // 确定当前页面这个游标块前后的页码 // 如 0,1...4,5,[6],7,8...10,11 里面的 4 和 8 rangeBeginPageIndex := pageIndex - pageIndexFrontNum rangeEndPageIndex := pageIndex + pageIndexBehindNum switch { case rangeBeginPageIndex < 0: rangeBeginPageIndex = 0 rangeEndPageIndex = pageIndexFrontNum + pageIndexBehindNum // maxPageIndex >= pageIndexRangeNum > pageIndexFrontNum + pageIndexBehindNum == rangeEndPageIndex, rangeEndPageIndex < maxPageIndex case rangeEndPageIndex > maxPageIndex: rangeEndPageIndex = maxPageIndex rangeBeginPageIndex = maxPageIndex - pageIndexFrontNum - pageIndexBehindNum // maxPageIndex >= pageIndexRangeNum > pageIndexFrontNum + pageIndexBehindNum, rangeBeginPageIndex > 0 } if rangeBeginPageIndex <= paginatorBeginNum { // 跟前面相连 if rangeEndPageIndex >= maxPageIndex-paginatorEndNum { // 跟后面相连 arr := make([]int, pageNum) for i := 0; i < pageNum; i++ { arr[i] = i } return arr, nil } else { //跟后面不连 arr := make([]int, 0, rangeEndPageIndex+1+1+paginatorEndNum) for i := 0; i <= rangeEndPageIndex; i++ { arr = append(arr, i) } arr = append(arr, -1) for i := pageNum - paginatorEndNum; i < pageNum; i++ { arr = append(arr, i) } return arr, nil } } else { // 跟前面不连 if rangeEndPageIndex >= maxPageIndex-paginatorEndNum { // 跟后面相连 arr := make([]int, 0, paginatorBeginNum+1+(pageNum-rangeBeginPageIndex)) for i := 0; i < paginatorBeginNum; i++ { arr = append(arr, i) } arr = append(arr, -1) for i := rangeBeginPageIndex; i < pageNum; i++ { arr = append(arr, i) } return arr, nil } else { //跟后面不连 arr := make([]int, 0, paginatorBeginNum+1+pageIndexRangeNum+1+paginatorEndNum) for i := 0; i < paginatorBeginNum; i++ { arr = append(arr, i) } arr = append(arr, -1) for i := rangeBeginPageIndex; i <= rangeEndPageIndex; i++ { arr = append(arr, i) } arr = append(arr, -1) for i := pageNum - paginatorEndNum; i < pageNum; i++ { arr = append(arr, i) } return arr, nil } } } } // 获取分页编号序列, 序列中正整数表示页码, -1 表示省略, 如 [1,2,-1,8,9,10,11,12,-1,15,16] 表示 1,2,...8,9,10,11,12,...15,16 // pageNum: 页面数量, 大于 0 的整数 // pageIndex: 当前页码, 从 1 开始编码 func Paginator1(pageNum, pageIndex int) ([]int, error) { pageIndex-- arr, err := Paginator0(pageNum, pageIndex) if err != nil { return nil, err } for i := 0; i < len(arr); i++ { if arr[i] != -1 { arr[i]++ } } return arr, nil } // 获取分页编号序列, 序列中非负整数表示页码, -1 表示省略, 如 [0,1,-1,8,9,10,11,12,-1,15,16] 表示 0,1,...8,9,10,11,12,...15,16 // totalNum: 总的记录数量, 不是页面数量 // numPerPage: 每页显示的数量 // pageIndex: 当前页码, 从 0 开始编码 func Paginator0Ex(totalNum, numPerPage, pageIndex int) (arr []int, pageNum int, err error) { if totalNum < 0 { err = errors.New("totalNum < 0") return } if numPerPage <= 0 { err = errors.New("numPerPage <= 0") return } if totalNum == 0 { pageNum = 1 } else { // totalNum > 0 pageNum = totalNum / numPerPage if pageNum*numPerPage < totalNum { pageNum++ } } if arr, err = Paginator0(pageNum, pageIndex); err != nil { return nil, 0, err } return } // 获取分页编号序列, 序列中正整数表示页码, -1 表示省略, 如 [1,2,-1,8,9,10,11,12,-1,15,16] 表示 1,2,...8,9,10,11,12,...15,16 // totalNum: 总的记录数量, 不是页面数量 // numPerPage: 每页显示的数量 // pageIndex: 当前页码, 从 1 开始编码 func Paginator1Ex(totalNum, numPerPage, pageIndex int) (arr []int, pageNum int, err error) { if totalNum < 0 { err = errors.New("totalNum < 0") return } if numPerPage <= 0 { err = errors.New("numPerPage <= 0") return } if totalNum == 0 { pageNum = 1 } else { // totalNum > 0 pageNum = totalNum / numPerPage if pageNum*numPerPage < totalNum { pageNum++ } } if arr, err = Paginator1(pageNum, pageIndex); err != nil { return nil, 0, err } return }
func search(nums []int, target int) int { left, right := 0, len(nums) - 1 for left <= right { md := (left + right) / 2 mdv := nums[md] if mdv == target{ return md } if mdv > nums[right]{ if target < mdv && nums[left] <= target{ right = md - 1 } else { left = md + 1 } } else { if target > mdv && nums[right] >= target{ left = md + 1 } else { right = md - 1 } } } return -1 }
package venom import ( "bytes" "context" "encoding/json" "fmt" "io" "os" "path" "path/filepath" "plugin" "sort" "strings" "github.com/confluentinc/bincover" "github.com/fatih/color" "github.com/ovh/cds/sdk/interpolate" "github.com/pkg/errors" "github.com/rockbears/yaml" "github.com/spf13/cast" ) var ( //Version is set with -ldflags "-X github.com/ovh/venom/venom.Version=$(VERSION)" Version = "snapshot" IsTest = "" ) func OSExit(exitCode int) { if IsTest != "" { bincover.ExitCode = exitCode } else { os.Exit(exitCode) } } // ContextKey can be added in context to store contextual infos. Also used by logger. type ContextKey string // New instantiates a new venom on venom run cmd func New() *Venom { v := &Venom{ LogOutput: os.Stdout, PrintFunc: fmt.Printf, executorsBuiltin: map[string]Executor{}, executorsPlugin: map[string]Executor{}, executorsUser: map[string]Executor{}, executorFileCache: map[string][]byte{}, variables: map[string]interface{}{}, secrets: map[string]interface{}{}, OutputFormat: "xml", } return v } type Venom struct { LogOutput io.Writer PrintFunc func(format string, a ...interface{}) (n int, err error) executorsBuiltin map[string]Executor executorsPlugin map[string]Executor executorsUser map[string]Executor executorFileCache map[string][]byte Tests Tests variables H secrets H LibDir string OutputFormat string OutputDir string StopOnFailure bool HtmlReport bool Verbose int } var trace = color.New(color.Attribute(90)).SprintFunc() func (v *Venom) Print(format string, a ...interface{}) { v.PrintFunc(format, a...) // nolint } func (v *Venom) Println(format string, a ...interface{}) { v.PrintFunc(format+"\n", a...) // nolint } func (v *Venom) PrintlnTrace(s string) { v.PrintlnIndentedTrace(s, "") } func (v *Venom) PrintlnIndentedTrace(s string, indent string) { v.Println("\t %s%s %s", indent, trace("[trac]"), trace(s)) // nolint } func (v *Venom) AddVariables(variables map[string]interface{}) { for k, variable := range variables { v.variables[k] = variable } } func (v *Venom) AddSecrets(secrets map[string]interface{}) { for k, s := range secrets { v.secrets[k] = s } } // RegisterExecutorBuiltin register builtin executors func (v *Venom) RegisterExecutorBuiltin(name string, e Executor) { v.executorsBuiltin[name] = e } // RegisterExecutorPlugin register plugin executors func (v *Venom) RegisterExecutorPlugin(name string, e Executor) { v.executorsPlugin[name] = e } // RegisterExecutorUser register User sxecutors func (v *Venom) RegisterExecutorUser(name string, e Executor) { v.executorsUser[name] = e } // GetExecutorRunner initializes a test by name // no type -> exec is default func (v *Venom) GetExecutorRunner(ctx context.Context, ts TestStep, h H) (context.Context, ExecutorRunner, error) { name, _ := ts.StringValue("type") script, _ := ts.StringValue("script") if name == "" && script != "" { name = "exec" } retry, err := ts.IntValue("retry") if err != nil { return nil, nil, err } retryIf, err := ts.StringSliceValue("retry_if") if err != nil { return nil, nil, err } delay, err := ts.IntValue("delay") if err != nil { return nil, nil, err } timeout, err := ts.IntValue("timeout") if err != nil { return nil, nil, err } info, _ := ts.StringSliceValue("info") vars, err := DumpStringPreserveCase(h) if err != nil { return ctx, nil, err } allKeys := []string{} for k, v := range vars { ctx = context.WithValue(ctx, ContextKey("var."+k), v) allKeys = append(allKeys, k) } ctx = context.WithValue(ctx, ContextKey("vars"), allKeys) if name == "" { return ctx, newExecutorRunner(nil, name, "builtin", retry, retryIf, delay, timeout, info), nil } if ex, ok := v.executorsBuiltin[name]; ok { return ctx, newExecutorRunner(ex, name, "builtin", retry, retryIf, delay, timeout, info), nil } if err := v.registerUserExecutors(ctx, name, vars); err != nil { Debug(ctx, "executor %q is not implemented as user executor - err:%v", name, err) } if ex, ok := v.executorsUser[name]; ok { return ctx, newExecutorRunner(ex, name, "user", retry, retryIf, delay, timeout, info), nil } if err := v.registerPlugin(ctx, name, vars); err != nil { Debug(ctx, "executor %q is not implemented as plugin - err:%v", name, err) } // then add the executor plugin to the map to not have to load it on each step if ex, ok := v.executorsUser[name]; ok { return ctx, newExecutorRunner(ex, name, "plugin", retry, retryIf, delay, timeout, info), nil } return ctx, nil, fmt.Errorf("executor %q is not implemented", name) } func (v *Venom) getUserExecutorFilesPath(vars map[string]string) (filePaths []string, err error) { var libpaths []string if v.LibDir != "" { p := strings.Split(v.LibDir, string(os.PathListSeparator)) libpaths = append(libpaths, p...) } libpaths = append(libpaths, path.Join(vars["venom.testsuite.workdir"], "lib")) for _, p := range libpaths { p = strings.TrimSpace(p) err = filepath.Walk(p, func(fp string, f os.FileInfo, err error) error { switch ext := filepath.Ext(fp); ext { case ".yml", ".yaml": filePaths = append(filePaths, fp) } return nil }) if err != nil { return nil, err } } sort.Strings(filePaths) if len(filePaths) == 0 { return nil, fmt.Errorf("no user executor yml file selected") } return filePaths, nil } func (v *Venom) registerUserExecutors(ctx context.Context, name string, vars map[string]string) error { executorsPath, err := v.getUserExecutorFilesPath(vars) if err != nil { return err } for _, f := range executorsPath { Info(ctx, "Reading %v", f) btes, ok := v.executorFileCache[f] if !ok { btes, err = os.ReadFile(f) if err != nil { return errors.Wrapf(err, "unable to read file %q", f) } v.executorFileCache[f] = btes } varsFromInput, err := getUserExecutorInputYML(ctx, btes) if err != nil { return err } // varsFromInput contains the default vars from the executor var varsFromInputMap map[string]string if len(varsFromInput) > 0 { varsFromInputMap, err = DumpStringPreserveCase(varsFromInput) if err != nil { return errors.Wrapf(err, "unable to parse variables") } } varsComputed := map[string]string{} for k, v := range vars { varsComputed[k] = v } for k, v := range varsFromInputMap { // we only take vars from varsFromInputMap if it's not already exist in vars from teststep vars if _, ok := vars[k]; !ok { varsComputed[k] = v } } content, err := interpolate.Do(string(btes), varsComputed) if err != nil { return err } ux := UserExecutor{Filename: f} if err := yaml.Unmarshal([]byte(content), &ux); err != nil { return errors.Wrapf(err, "unable to parse file %q with content %v", f, content) } Debug(ctx, "User executor %q revolved with content %v", f, content) for k, vr := range varsComputed { ux.Input.Add(k, vr) } v.RegisterExecutorUser(ux.Executor, ux) } return nil } func (v *Venom) registerPlugin(ctx context.Context, name string, vars map[string]string) error { workdir := vars["venom.testsuite.workdir"] // try to load from testsuite path p, err := plugin.Open(path.Join(workdir, "lib", name+".so")) if err != nil { // try to load from venom binary path p, err = plugin.Open(path.Join("lib", name+".so")) if err != nil { return fmt.Errorf("unable to load plugin %q.so", name) } } symbolExecutor, err := p.Lookup("Plugin") if err != nil { return err } executor := symbolExecutor.(Executor) v.RegisterExecutorPlugin(name, executor) return nil } func VarFromCtx(ctx context.Context, varname string) interface{} { i := ctx.Value(ContextKey("var." + varname)) return i } func StringVarFromCtx(ctx context.Context, varname string) string { i := ctx.Value(ContextKey("var." + varname)) return cast.ToString(i) } func StringSliceVarFromCtx(ctx context.Context, varname string) []string { i := ctx.Value(ContextKey("var." + varname)) return cast.ToStringSlice(i) } func IntVarFromCtx(ctx context.Context, varname string) int { i := ctx.Value(ContextKey("var." + varname)) return cast.ToInt(i) } func BoolVarFromCtx(ctx context.Context, varname string) bool { i := ctx.Value(ContextKey("var." + varname)) return cast.ToBool(i) } func StringMapInterfaceVarFromCtx(ctx context.Context, varname string) map[string]interface{} { i := ctx.Value(ContextKey("var." + varname)) return cast.ToStringMap(i) } func StringMapStringVarFromCtx(ctx context.Context, varname string) map[string]string { i := ctx.Value(ContextKey("var." + varname)) return cast.ToStringMapString(i) } func AllVarsFromCtx(ctx context.Context) H { i := ctx.Value(ContextKey("vars")) allKeys := cast.ToStringSlice(i) res := H{} for _, k := range allKeys { res.Add(k, VarFromCtx(ctx, k)) } return res } func JSONUnmarshal(btes []byte, i interface{}) error { var d = json.NewDecoder(bytes.NewReader(btes)) d.UseNumber() return d.Decode(i) }
package foundationdb import ( "github.com/apple/foundationdb/bindings/go/src/fdb" "github.com/blevesearch/bleve/index/store" "github.com/blevesearch/bleve/registry" ) const ( // Name is the name of this KVStore Name = "foundationdb" ) // Store is a FoundationDB implementation of the KVStore interface type Store struct { mo store.MergeOperator db fdb.Database } // New returns a new Store func New(mo store.MergeOperator, config map[string]interface{}) (store.KVStore, error) { err := fdb.APIVersion(600) if err != nil { return nil, err } db, err := fdb.OpenDefault() if err != nil { return nil, err } return &Store{ mo: mo, db: db, }, nil } // Writer returns a KVWriter which can be used to // make changes to the FDB. If a writer cannot // be obtained a non-nil error is returned. func (s *Store) Writer() (store.KVWriter, error) { return &Writer{ store: s, }, nil } // Reader returns a KVReader which can be used to // read data from the KVStore. If a reader cannot // be obtained a non-nil error is returned. func (s *Store) Reader() (store.KVReader, error) { return &Reader{ db: s.db, }, nil } // Close closes the KVStore func (s *Store) Close() error { return nil } // make this store available to bleve func init() { registry.RegisterKVStore(Name, New) }
// Copyright 2020 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 in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package collate import ( "github.com/pingcap/tidb/util/collate/ucadata" "github.com/pingcap/tidb/util/stringutil" ) const ( // magic number indicate weight has 2 uint64, should get from `longRuneMap` longRune uint64 = 0xFFFD ) //go:generate go run ./ucaimpl/main.go -- unicode_0400_ci_generated.go type unicode0400Impl struct { } func (unicode0400Impl) Preprocess(s string) string { return truncateTailingSpace(s) } func (unicode0400Impl) GetWeight(r rune) (first, second uint64) { if r > 0xFFFF { return 0xFFFD, 0 } if ucadata.DUCET0400Table.MapTable4[r] == longRune { return ucadata.DUCET0400Table.LongRuneMap[r][0], ucadata.DUCET0400Table.LongRuneMap[r][1] } return ucadata.DUCET0400Table.MapTable4[r], 0 } func (unicode0400Impl) Pattern() WildcardPattern { return &unicodePattern{} } type unicodePattern struct { patChars []rune patTypes []byte } // Compile implements WildcardPattern interface. func (p *unicodePattern) Compile(patternStr string, escape byte) { p.patChars, p.patTypes = stringutil.CompilePatternInner(patternStr, escape) } // DoMatch implements WildcardPattern interface. func (p *unicodePattern) DoMatch(str string) bool { return stringutil.DoMatchInner(str, p.patChars, p.patTypes, func(a, b rune) bool { if a > 0xFFFF || b > 0xFFFF { return a == b } ar, br := ucadata.DUCET0400Table.MapTable4[a], ucadata.DUCET0400Table.MapTable4[b] if ar != br { return false } if ar == longRune { return a == b } return true }) }
package openflow import ( "errors" "testing" "github.com/quilt/quilt/minion/ovsdb" "github.com/quilt/quilt/minion/ovsdb/mocks" "github.com/stretchr/testify/assert" ) func TestAddReplaceFlows(t *testing.T) { anErr := errors.New("err") ovsdb.Open = func() (ovsdb.Client, error) { return nil, anErr } assert.EqualError(t, ReplaceFlows(nil), "ovsdb-server connection: err") assert.EqualError(t, AddFlows(nil), "ovsdb-server connection: err") client := new(mocks.Client) ovsdb.Open = func() (ovsdb.Client, error) { return client, nil } var action string var flows []string ofctl = func(a string, f []string) error { action = a flows = f return nil } client.On("Disconnect").Return(nil) client.On("OpenFlowPorts").Return(map[string]int{}, nil) assert.NoError(t, ReplaceFlows(nil)) client.AssertCalled(t, "Disconnect") client.AssertCalled(t, "OpenFlowPorts") assert.Equal(t, "replace-flows", action) assert.Equal(t, allFlows(nil), flows) assert.NoError(t, AddFlows(nil)) client.AssertCalled(t, "Disconnect") client.AssertCalled(t, "OpenFlowPorts") assert.Equal(t, "add-flows", action) assert.Equal(t, containerFlows(nil), flows) ofctl = func(a string, f []string) error { return anErr } assert.EqualError(t, ReplaceFlows(nil), "ovs-ofctl: err") client.AssertCalled(t, "Disconnect") client.AssertCalled(t, "OpenFlowPorts") assert.EqualError(t, AddFlows(nil), "ovs-ofctl: err") client.AssertCalled(t, "Disconnect") client.AssertCalled(t, "OpenFlowPorts") } func TestAllFlows(t *testing.T) { t.Parallel() flows := allFlows([]container{ {patch: 4, veth: 5, mac: "66:66:66:66:66:66"}, {patch: 9, veth: 8, mac: "99:99:99:99:99:99"}}) exp := append(staticFlows, "table=0,priority=1000,in_port=5,dl_src=66:66:66:66:66:66,"+ "actions=load:0x1->NXM_NX_REG0[],load:0x5->NXM_NX_REG1[],"+ "load:0x4->NXM_NX_REG2[],resubmit(,1)", "table=0,priority=1000,in_port=4,"+ "actions=load:0x2->NXM_NX_REG0[],load:0x5->NXM_NX_REG1[],"+ "load:0x4->NXM_NX_REG2[],resubmit(,1)", "table=2,priority=1000,dl_dst=66:66:66:66:66:66,actions=output:5", "table=0,priority=1000,in_port=8,dl_src=99:99:99:99:99:99,"+ "actions=load:0x1->NXM_NX_REG0[],load:0x8->NXM_NX_REG1[],"+ "load:0x9->NXM_NX_REG2[],resubmit(,1)", "table=0,priority=1000,in_port=9,"+ "actions=load:0x2->NXM_NX_REG0[],load:0x8->NXM_NX_REG1[],"+ "load:0x9->NXM_NX_REG2[],resubmit(,1)", "table=2,priority=1000,dl_dst=99:99:99:99:99:99,actions=output:8", "table=1,priority=850,dl_dst=ff:ff:ff:ff:ff:ff,actions=output:5,output:8") assert.Equal(t, exp, flows) } func TestResolveContainers(t *testing.T) { t.Parallel() res := resolveContainers(map[string]int{"a": 3, "b": 4}, []Container{ {Veth: "a", Patch: "b", Mac: "mac"}, {Veth: "c", Patch: "d", Mac: "mac2"}}) assert.Equal(t, []container{{veth: 3, patch: 4, mac: "mac"}}, res) }
package main import ( "net/http" "strings" "testing" ) func TestRememberBodyLazy(t *testing.T) { resp := Response{ http: &http.Response{ Header: map[string][]string{"Content-Type": {"application/json"}}, }, body: []byte(`# invalid body so it fails if parsed`), } err := rememberBody(&resp, map[string]string{}, NewVars("")) if err != nil { t.Error(err) } } func TestRunSuite_InvalidUrlAndUnused_OnlyInvalidUrl(t *testing.T) { suite := TestSuite{ Cases: []TestCase{ { Calls: []Call{ { Args: map[string]interface{}{"a": 1}, On: On{ URL: "my-invalid-host", }, }, }, }, }, } results := runSuite(&RequestConfig{}, &RewriteConfig{}, suite) err := results[0].Traces[0].ErrorCause if err == nil || !strings.Contains(err.Error(), "Invalid url") { t.Error("Expected error not thrown", err) } } func TestConcatURL(t *testing.T) { t.Run("open base and closed path", func(t *testing.T) { base := "http://example.com" path := "/api/v1/example" url, _ := concatURL(base, path) if url != "http://example.com/api/v1/example" { t.Error("Incorrect url. Expected: http://example.com/api/v1/example. Actual: " + url) } }) t.Run("closed base and closed path", func(t *testing.T) { base := "http://example.com/api/" path := "/v1/example" url, _ := concatURL(base, path) if url != "http://example.com/api/v1/example" { t.Error("Incorrect url. Expected: http://example.com/api/v1/example. Actual: " + url) } }) t.Run("closed base and open path", func(t *testing.T) { base := "http://example.com/api/" path := "v1/example" url, _ := concatURL(base, path) if url != "http://example.com/api/v1/example" { t.Error("Incorrect url. Expected: http://example.com/api/v1/example. Actual: " + url) } }) t.Run("open base and open path", func(t *testing.T) { base := "http://example.com/api" path := "v1/example" url, _ := concatURL(base, path) if url != "http://example.com/api/v1/example" { t.Error("Incorrect url. Expected: http://example.com/api/v1/example. Actual: " + url) } }) }
package listen import ( "database/sql" "fmt" "github.com/lib/pq" _ "github.com/lib/pq" ) type Listen interface { Listener(event Event) (*pq.Listener, error) } func connect(connParams DBConnParams) *sql.DB { connInfo := connInfo(connParams) db, err := sql.Open("postgres", connInfo) if err != nil { panic(err) } return db } func createNotifyEvent(db *sql.DB) error { _, err := db.Query(` CREATE OR REPLACE FUNCTION cdc_notify_event() RETURNS TRIGGER AS $$ DECLARE data json; notification json; BEGIN IF (TG_OP = 'DELETE') THEN data = row_to_json(OLD); ELSE data = row_to_json(NEW); END IF; notification = json_build_object( 'timestamp', NOW(), 'table',TG_TABLE_NAME, 'action', TG_OP, 'data', data); PERFORM pg_notify('events',notification::text); RETURN NULL; END; $$ LANGUAGE plpgsql; `) return err } func connInfo(connParams DBConnParams) string { return fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", connParams.Host, connParams.Port, connParams.User, connParams.Pass, connParams.Name) }
/* Copyright (c) 2017 Jason Ish * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package configdb import ( "database/sql" "github.com/jasonish/evebox/log" "github.com/jasonish/evebox/sqlite/common" _ "github.com/mattn/go-sqlite3" "os" "path" ) const driver = "sqlite3" const filename = "config.sqlite" type ConfigDB struct { DB *sql.DB InMemory bool } func NewConfigDB(directory string) (*ConfigDB, error) { var dsn string var inMemory bool if directory == ":memory:" { log.Info("Using in-memory configuration DB.") dsn = ":memory:" inMemory = true } else { dsn = path.Join(directory, filename) _, err := os.Stat(dsn) if err == nil { log.Info("Using configuration database file %s", dsn) } else { log.Info("Creating new configuration database %s", dsn) } } db, err := sql.Open(driver, dsn) if err != nil { return nil, err } configDB := &ConfigDB{ DB: db, InMemory: inMemory, } if err := configDB.migrate(); err != nil { return nil, err } return configDB, nil } func (db *ConfigDB) migrate() error { migrator := common.NewSqlMigrator(db.DB, "configdb") return migrator.Migrate() }