text
stringlengths
11
4.05M
package mowa import ( "context" "net/http" "net/http/httptest" "net/http/httputil" "testing" ) var testC *Context func init() { req, _ := http.NewRequest("Get", "http://localhost:1234/hello/world?name=chen&age=25&name=yun", nil) testC = &Context{ Request: req, } } func handle1(c *Context) (int, interface{}) { return 200, "handle1: hello world" } func handle2(c *Context) (int, interface{}) { return 203, map[string]interface{}{ "one": 1, "two": "two", } } func handle3(c *Context) (int, interface{}) { return 202, map[string]interface{}{ "one": 1, "age": c.Int("age", 20), } } func TestServer(t *testing.T) { api := New(context.Background()) go api.Run(":10000") api.Get("/test", func(c *Context) (int, interface{}) { return 200, "test" }) resp, err := http.Get("http://localhost:10000/test") if err != nil { t.Error(err) } content, err := httputil.DumpResponse(resp, true) if err != nil { t.Error(err) } t.Log(string(content)) } func TestServeHTTP(t *testing.T) { router := newRouter(context.Background()) router.Group("/api/v1").Get("/chen", handle1) router.Get("/yun", handle2) router.Get("/fei/:age", handle3) for _, uri := range []string{"/chen", "/api/v1/chen", "/yun", "/fei/aa", "/fei/25"} { req, err := http.NewRequest("GET", "http://localhost"+uri, nil) if err != nil { t.Error(err) } w := httptest.NewRecorder() router.ServeHTTP(w, req) t.Log("\n\nRequest for " + uri) t.Log(w.Code) t.Log(w.Body.String()) } }
package main import ( "runtime" "fmt" "time" ) func main() { //设置可以执行的cpu的最大数量 runtime.GOMAXPROCS(2) ch1 := make(chan int) ch2 := make(chan int) go pump1(ch1) go pump2(ch2) go suck(ch1, ch2) fmt.Println(runtime.NumCPU(),"================") time.Sleep(1e9) } func pump1(ch chan int) { for i := 0; ; i++ { ch <- i * 2 } } func pump2(ch chan int) { for i := 0; ; i++ { ch <- i + 5 } } func suck(ch1, ch2 chan int) { if <-ch2==2000 { } for i := 0; ; i++ { select { case v := <-ch1: fmt.Printf("%d -Received on channel 1:%d\n", i, v) case v := <-ch2: fmt.Printf("%d -Received on channel 2:%d\n", i, v) } } }
package settings import ( "Golang-Echo-MVC-Pattern/constant" "Golang-Echo-MVC-Pattern/utils" "context" "fmt" "github.com/jackc/pgx/v4/pgxpool" "github.com/joho/godotenv" "os" ) var db *pgxpool.Pool type Database struct{} func init() { err := godotenv.Load() if err != nil { println(constant.MessageEnvironment) } host := os.Getenv(constant.DBHost) dbname := os.Getenv(constant.DBName) user := os.Getenv(constant.DBUser) password := os.Getenv(constant.DBPassword) schema := os.Getenv(constant.DBSchema) psqlInfo := fmt.Sprintf("postgres://%s:%s@%s/%s?sslmode=disable&search_path=%s", user, password, host, dbname, schema) db, err = pgxpool.Connect(context.Background(), psqlInfo) if err != nil { utils.LogError(err, utils.DetailFunction()) os.Exit(1) } } func (Database Database) GetDatabase() *pgxpool.Pool { return db }
package stemsrepo_test import ( "fmt" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" . "github.com/bosh-io/web/stemcell/stemsrepo" ) var _ = Describe("NewS3Stemcell", func() { type ExtractedPieces struct { Version string Name string InfName string HvName string DiskFormat string OSName string OSVersion string AgentType string } var examples = map[string]ExtractedPieces{ "bosh-stemcell/aws/bosh-stemcell-891-aws-xen-ubuntu.tgz": ExtractedPieces{ Name: "bosh-aws-xen-ubuntu", Version: "891", InfName: "aws", HvName: "xen", OSName: "ubuntu", OSVersion: "lucid", AgentType: "ruby", }, "bosh-stemcell/aws/bosh-stemcell-2311-aws-xen-centos-go_agent.tgz": ExtractedPieces{ Name: "bosh-aws-xen-centos-go_agent", Version: "2311", InfName: "aws", HvName: "xen", OSName: "centos", OSVersion: "", AgentType: "go", }, "bosh-stemcell/aws/bosh-stemcell-2446-aws-xen-ubuntu-lucid-go_agent.tgz": ExtractedPieces{ Name: "bosh-aws-xen-ubuntu-lucid-go_agent", Version: "2446", InfName: "aws", HvName: "xen", OSName: "ubuntu", OSVersion: "lucid", AgentType: "go", }, "micro-bosh-stemcell/aws/light-micro-bosh-stemcell-891-aws-xen-ubuntu.tgz": ExtractedPieces{ Name: "bosh-aws-xen-ubuntu", Version: "891", InfName: "aws", HvName: "xen", OSName: "ubuntu", OSVersion: "lucid", AgentType: "ruby", }, "micro-bosh-stemcell/warden/bosh-stemcell-56-warden-boshlite-ubuntu-lucid-go_agent.tgz": ExtractedPieces{ Name: "bosh-warden-boshlite-ubuntu-lucid-go_agent", Version: "56", InfName: "warden", HvName: "boshlite", OSName: "ubuntu", OSVersion: "lucid", AgentType: "go", }, "bosh-stemcell/aws/light-bosh-stemcell-2579-aws-xen-centos.tgz": ExtractedPieces{ Name: "bosh-aws-xen-centos", Version: "2579", InfName: "aws", HvName: "xen", OSName: "centos", OSVersion: "", AgentType: "ruby", }, "bosh-stemcell/aws/light-bosh-stemcell-2579-aws-xen-centos-go_agent.tgz": ExtractedPieces{ Name: "bosh-aws-xen-centos-go_agent", Version: "2579", InfName: "aws", HvName: "xen", OSName: "centos", OSVersion: "", AgentType: "go", }, "bosh-stemcell/aws/light-bosh-stemcell-2579.1-aws-xen-centos-go_agent.tgz": ExtractedPieces{ Name: "bosh-aws-xen-centos-go_agent", Version: "2579.1", InfName: "aws", HvName: "xen", OSName: "centos", OSVersion: "", AgentType: "go", }, "bosh-stemcell/aws/light-bosh-stemcell-2579.1-aws-xen-hvm-centos-go_agent.tgz": ExtractedPieces{ Name: "bosh-aws-xen-hvm-centos-go_agent", Version: "2579.1", InfName: "aws", HvName: "xen-hvm", OSName: "centos", OSVersion: "", AgentType: "go", }, "bosh-stemcell/aws/light-bosh-stemcell-2579.1-aws-xen-hvm-ubuntu-trusty-go_agent.tgz": ExtractedPieces{ Name: "bosh-aws-xen-hvm-ubuntu-trusty-go_agent", Version: "2579.1", InfName: "aws", HvName: "xen-hvm", OSName: "ubuntu", OSVersion: "trusty", AgentType: "go", }, // Notice no top-level folder prefix "aws/bosh-stemcell-3306-aws-xen-ubuntu-trusty-go_agent.tgz": ExtractedPieces{ Name: "bosh-aws-xen-ubuntu-trusty-go_agent", Version: "3306", InfName: "aws", HvName: "xen", OSName: "ubuntu", OSVersion: "trusty", AgentType: "go", }, // Notice no folder prefixes "bosh-stemcell-2776-warden-boshlite-centos-go_agent.tgz": ExtractedPieces{ Name: "bosh-warden-boshlite-centos-go_agent", Version: "2776", InfName: "warden", HvName: "boshlite", OSName: "centos", OSVersion: "", AgentType: "go", }, // Disk format "bosh-stemcell/openstack/bosh-stemcell-56-openstack-kvm-ubuntu-trusty-go_agent-raw.tgz": ExtractedPieces{ Name: "bosh-openstack-kvm-ubuntu-trusty-go_agent-raw", Version: "56", InfName: "openstack", HvName: "kvm", DiskFormat: "raw", OSName: "ubuntu", OSVersion: "trusty", AgentType: "go", }, // Numeric OS version "bosh-stemcell/vsphere/bosh-stemcell-2922-vsphere-esxi-centos-7-go_agent.tgz": ExtractedPieces{ Name: "bosh-vsphere-esxi-centos-7-go_agent", Version: "2922", InfName: "vsphere", HvName: "esxi", DiskFormat: "", OSName: "centos", OSVersion: "7", AgentType: "go", }, // Stemcell in China "light-china-bosh-stemcell-3130-aws-xen-hvm-ubuntu-trusty-go_agent.tgz": ExtractedPieces{ Name: "bosh-aws-xen-hvm-ubuntu-trusty-go_agent", Version: "3130", InfName: "aws", HvName: "xen-hvm", OSName: "ubuntu", OSVersion: "trusty", AgentType: "go", }, "light-bosh-stemcell-1709.3-google-kvm-windows2016-go_agent.tgz": ExtractedPieces{ Name: "bosh-google-kvm-windows2016-go_agent", Version: "1709.3", InfName: "google", HvName: "kvm", OSName: "windows", OSVersion: "2016", AgentType: "go", }, "light-bosh-stemcell-1089.0-aws-xen-hvm-windows2012R2-go_agent.tgz": ExtractedPieces{ Name: "bosh-aws-xen-hvm-windows2012R2-go_agent", Version: "1089.0", InfName: "aws", HvName: "xen-hvm", OSName: "windows", OSVersion: "2012R2", AgentType: "go", }, "light-bosh-stemcell-1089.0-azure-hyperv-windows2012R2-go_agent.tgz": ExtractedPieces{ Name: "bosh-azure-hyperv-windows2012R2-go_agent", Version: "1089.0", InfName: "azure", HvName: "hyperv", OSName: "windows", OSVersion: "2012R2", AgentType: "go", }, "light-bosh-stemcell-1089.0-google-kvm-windows2012R2-go_agent.tgz": ExtractedPieces{ Name: "bosh-google-kvm-windows2012R2-go_agent", Version: "1089.0", InfName: "google", HvName: "kvm", OSName: "windows", OSVersion: "2012R2", AgentType: "go", }, // Softlayer stemcell "light-bosh-stemcell-3232.4-softlayer-esxi-ubuntu-trusty-go_agent.tgz": ExtractedPieces{ Name: "bosh-softlayer-esxi-ubuntu-trusty-go_agent", Version: "3232.4", InfName: "softlayer", HvName: "esxi", OSName: "ubuntu", OSVersion: "trusty", AgentType: "go", }, // Ubuntu xenial "azure/bosh-stemcell-40-azure-hyperv-ubuntu-xenial-go_agent.tgz": ExtractedPieces{ Name: "bosh-azure-hyperv-ubuntu-xenial-go_agent", Version: "40", InfName: "azure", HvName: "hyperv", OSName: "ubuntu", OSVersion: "xenial", AgentType: "go", }, // Ubuntu bionic "azure/bosh-stemcell-40-azure-hyperv-ubuntu-bionic-go_agent.tgz": ExtractedPieces{ Name: "bosh-azure-hyperv-ubuntu-bionic-go_agent", Version: "40", InfName: "azure", HvName: "hyperv", OSName: "ubuntu", OSVersion: "bionic", AgentType: "go", }, } for p, e := range examples { path := p example := e It(fmt.Sprintf("correctly interprets '%s'", path), func() { s3Stemcell := NewS3Stemcell(path, "", "", 0, "", "") Expect(s3Stemcell).ToNot(BeNil()) Expect(s3Stemcell.Name()).To(Equal(example.Name)) Expect(s3Stemcell.Version().AsString()).To(Equal(example.Version)) Expect(s3Stemcell.InfName()).To(Equal(example.InfName)) Expect(s3Stemcell.HvName()).To(Equal(example.HvName)) Expect(s3Stemcell.DiskFormat()).To(Equal(example.DiskFormat)) Expect(s3Stemcell.OSName()).To(Equal(example.OSName)) Expect(s3Stemcell.OSVersion()).To(Equal(example.OSVersion)) Expect(s3Stemcell.AgentType()).To(Equal(example.AgentType)) }) } })
package utils import ( "bytes" "encoding/json" "io/ioutil" "net/http" "os" "strings" "github.com/kardianos/osext" uuid "github.com/satori/go.uuid" "github.com/sirupsen/logrus" "golang.org/x/crypto/bcrypt" ) func Digest(password string) (string, error) { hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) return string(hashedPassword), err } func Req(method string, url string, body interface{}, headers map[string]string, model interface{}) (int, error) { var r *http.Request logrus.Info(url, "호출합니다.") if body == nil { r, _ = http.NewRequest(method, url, nil) } else { bodyBytes, _ := json.Marshal(body) r, _ = http.NewRequest(method, url, bytes.NewBuffer(bodyBytes)) r.Header.Add("Content-Type", "application/json") } if headers != nil { for key, value := range headers { r.Header.Add(key, value) } } client := &http.Client{} w, err := client.Do(r) if err != nil { logrus.WithError(err).Error("요청 실패", err) return 0, err } if w.StatusCode >= 200 && w.StatusCode <= 400 { if model != nil { resBody, _ := ioutil.ReadAll(w.Body) if err := json.Unmarshal(resBody, model); err != nil { return -1, err } //logrus.Debug(w.StatusCode, ". BODY : ", string(resBody)) } } logrus.Info("요청 성공. 상태 : ", method, url, w.StatusCode) return w.StatusCode, nil } func GetHostname() string { if hostname, err := os.Hostname(); err == nil { return hostname } return "unknown" } func GetAppPath() string { apppath, _ := osext.ExecutableFolder() return apppath } func MakeFirstLowerCase(s string) string { if len(s) < 2 { return strings.ToLower(s) } bts := []byte(s) lc := bytes.ToLower([]byte{bts[0]}) rest := bts[1:] return string(bytes.Join([][]byte{lc, rest}, nil)) } func IsExistsTag(reqTags string, notiTypeTags string) bool { mapTag := map[string]bool{} for _, tag := range strings.Split(reqTags, ",") { mapTag[tag] = true } mapNotiTypeTags := map[string]bool{} for _, notiTypeTag := range strings.Split(notiTypeTags, ",") { mapNotiTypeTags[notiTypeTag] = true } for _, tag := range strings.Split(reqTags, ",") { if _, ok := mapNotiTypeTags[tag]; !ok { return false } } return true } func MakeUUID() string { uuid, _ := uuid.NewV4() return uuid.String() }
// DRUNKWATER TEMPLATE(add description and prototypes) // Question Title and Description on leetcode.com // Function Declaration and Function Prototypes on leetcode.com //796. Rotate String //We are given two strings, A and B. //A shift on A consists of taking string A and moving the leftmost character to the rightmost position. For example, if A = 'abcde', then it will be 'bcdea' after one shift on A. Return True if and only if A can become B after some number of shifts on A. //Example 1: //Input: A = 'abcde', B = 'cdeab' //Output: true //Example 2: //Input: A = 'abcde', B = 'abced' //Output: false //Note: //A and B will have length at most 100. //func rotateString(A string, B string) bool { //} // Time Is Money
package compress import ( "bytes" ) const ( x855595167=`HttpURLConnection httpConn = (HttpURLConnection) myURL.openConnection(); httpConn.setDoOutput(true); httpConn.setDoInput(true); httpConn.setUseCaches(false); httpConn.setRequestMethod("POST"); httpConn.setRequestProperty("Content-Type", "application/json;charset=utf-8"); httpConn.setConnectTimeout(5000); httpConn.setReadTimeout(2 * 5000); ` ) type File2GoModel struct{ buffer *bytes.Buffer } func NewFile2GoModel() File2GoModel{ return File2GoModel{ buffer:bytes.NewBuffer([]byte(x855595167)), } } func(m File2GoModel)Read(p []byte) (n int, err error){ return m.buffer.Read(p) }
package aes import ( "crypto/aes" "crypto/cipher" ) type Encrypter struct { Key Key Nonce []byte } func (e Encrypter) EncryptAES(plaintext []byte) ([]byte, error) { block, err := aes.NewCipher(e.Key) if err != nil { return nil, err } gcm, err := cipher.NewGCM(block) if err != nil { return nil, err } ciphertext := gcm.Seal(nil, e.Nonce, plaintext, nil) return ciphertext, nil }
package slack import ( "encoding/json" "net/http" "reflect" "testing" "github.com/stretchr/testify/assert" "github.com/slack-go/slack/internal/errorsx" ) var dummySlackErr = errorsx.String("dummy_error_from_slack") type viewsHandler struct { rawResponse string } func (h *viewsHandler) handler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.Write([]byte(h.rawResponse)) } func TestSlack_OpenView(t *testing.T) { once.Do(startServer) api := New("testing-token", OptionAPIURL("http://"+serverAddr+"/")) cases := []struct { caseName string triggerID string modalViewRequest ModalViewRequest rawResp string expectedResp *ViewResponse expectedErr error }{ { caseName: "pass empty trigger_id", triggerID: "", modalViewRequest: ModalViewRequest{}, rawResp: "", expectedResp: nil, expectedErr: ErrParametersMissing, }, { caseName: "raise an error for not having a unique block id", triggerID: "dummy_trigger_id", modalViewRequest: ModalViewRequest{ Blocks: Blocks{ BlockSet: []Block{ &InputBlock{ BlockID: "example", }, &InputBlock{ BlockID: "example", }, }, }, }, rawResp: "", expectedResp: nil, expectedErr: ErrBlockIDNotUnique, }, { caseName: "raise an error from Slack API", triggerID: "dummy_trigger_id", modalViewRequest: ModalViewRequest{}, rawResp: `{ "ok": false, "error": "dummy_error_from_slack", "response_metadata": { "warnings": [ "missing_charset" ], "messages": [ "[WARN] A Content-Type HTTP header was presented but did not declare a charset, such as a 'utf-8'" ] } }`, expectedResp: &ViewResponse{ SlackResponse{ Ok: false, Error: dummySlackErr.Error(), ResponseMetadata: ResponseMetadata{ Messages: []string{"[WARN] A Content-Type HTTP header was presented but did not declare a charset, such as a 'utf-8'"}, Warnings: []string{"missing_charset"}, }, }, View{}, }, expectedErr: dummySlackErr, }, { caseName: "success", triggerID: "dummy_trigger_id", modalViewRequest: ModalViewRequest{}, rawResp: `{ "ok": true, "view": { "id": "VMHU10V25", "team_id": "T8N4K1JN", "type": "modal", "title": { "type": "plain_text", "text": "Quite a plain modal" }, "submit": { "type": "plain_text", "text": "Create" }, "blocks": [ { "type": "input", "block_id": "a_block_id", "label": { "type": "plain_text", "text": "A simple label" }, "optional": false, "element": { "type": "plain_text_input", "placeholder": { "type": "plain_text", "text": "Placeholder text" }, "action_id": "an_action_id" } } ], "private_metadata": "Shh it is a secret", "callback_id": "identify_your_modals", "external_id": "", "state": { "values": {} }, "hash": "156772938.1827394", "clear_on_close": false, "notify_on_close": false, "root_view_id": "VMHU10V25", "app_id": "AA4928AQ", "bot_id": "BA13894H" } }`, expectedResp: &ViewResponse{ SlackResponse{ Ok: true, Error: "", }, View{ ID: "VMHU10V25", Type: VTModal, TeamID: "T8N4K1JN", Title: &TextBlockObject{ Type: PlainTextType, Text: "Quite a plain modal", }, Submit: &TextBlockObject{ Type: PlainTextType, Text: "Create", }, CallbackID: "identify_your_modals", PrivateMetadata: "Shh it is a secret", State: &ViewState{}, Hash: "156772938.1827394", RootViewID: "VMHU10V25", AppID: "AA4928AQ", BotID: "BA13894H", Blocks: Blocks{ BlockSet: []Block{ NewInputBlock( "a_block_id", &TextBlockObject{ Type: PlainTextType, Text: "A simple label", }, &TextBlockObject{ Type: PlainTextType, Text: "A simple hint", }, NewPlainTextInputBlockElement( &TextBlockObject{ Type: PlainTextType, Text: "Placeholder text", }, "an_action_id", )), }, }, }, }, expectedErr: nil, }, } h := &viewsHandler{} http.HandleFunc("/views.open", h.handler) for _, c := range cases { t.Run(c.caseName, func(t *testing.T) { h.rawResponse = c.rawResp resp, err := api.OpenView(c.triggerID, c.modalViewRequest) if c.expectedErr == nil && err != nil { t.Fatalf("unexpected error: %s\n", err) } if c.expectedErr != nil && err == nil { t.Fatalf("expected %s, but did not raise an error", c.expectedErr) } if c.expectedErr != nil && err != nil && c.expectedErr.Error() != err.Error() { t.Fatalf("expected %s as error but got %s\n", c.expectedErr, err) } if resp == nil || c.expectedResp == nil { return } if !reflect.DeepEqual(resp.ResponseMetadata.Messages, c.expectedResp.ResponseMetadata.Messages) { t.Fatalf("expected:\n\t%v\n but got:\n\t%v\n", c.expectedResp.ResponseMetadata.Messages, resp.ResponseMetadata.Messages) } if !reflect.DeepEqual(resp.ResponseMetadata.Warnings, c.expectedResp.ResponseMetadata.Warnings) { t.Fatalf("expected:\n\t%v\n but got:\n\t%v\n", c.expectedResp.ResponseMetadata.Warnings, resp.ResponseMetadata.Warnings) } }) } } func TestSlack_View_PublishView(t *testing.T) { once.Do(startServer) api := New("testing-token", OptionAPIURL("http://"+serverAddr+"/")) cases := []struct { caseName string userID string rawResp string expectedResp *ViewResponse expectedErr error }{ { caseName: "pass empty user_id", userID: "", rawResp: "", expectedResp: nil, expectedErr: ErrParametersMissing, }, { caseName: "raise an error from Slack API", userID: "dummy_user_id", rawResp: `{ "ok": false, "error": "dummy_error_from_slack", "response_metadata": { "warnings": [ "missing_charset" ], "messages": [ "[WARN] A Content-Type HTTP header was presented but did not declare a charset, such as a 'utf-8'" ] } }`, expectedResp: &ViewResponse{ SlackResponse{ Ok: false, Error: dummySlackErr.Error(), ResponseMetadata: ResponseMetadata{ Messages: []string{"[WARN] A Content-Type HTTP header was presented but did not declare a charset, such as a 'utf-8'"}, Warnings: []string{"missing_charset"}, }, }, View{}, }, expectedErr: dummySlackErr, }, { caseName: "success", userID: "dummy_user_id", rawResp: `{ "ok": true, "view": { "id": "VMHU10V25", "team_id": "T8N4K1JN", "type": "home", "close": null, "submit": null, "blocks": [ { "type": "input", "block_id": "a_block_id", "label": { "type": "plain_text", "text": "A simple label" }, "optional": false, "element": { "type": "plain_text_input", "placeholder": { "type": "plain_text", "text": "Placeholder text" }, "action_id": "an_action_id" } } ], "private_metadata": "Shh it is a secret", "callback_id": "identify_your_home_tab", "state": { "values": {} }, "hash": "156772938.1827394", "clear_on_close": false, "notify_on_close": false, "root_view_id": "VMHU10V25", "previous_view_id": null, "app_id": "AA4928AQ", "external_id": "", "bot_id": "BA13894H" } }`, expectedResp: &ViewResponse{ SlackResponse{ Ok: true, Error: "", }, View{ ID: "VMHU10V25", Type: VTHomeTab, TeamID: "T8N4K1JN", CallbackID: "identify_your_home_tab", PrivateMetadata: "Shh it is a secret", State: &ViewState{}, Hash: "156772938.1827394", RootViewID: "VMHU10V25", AppID: "AA4928AQ", BotID: "BA13894H", Blocks: Blocks{ BlockSet: []Block{ NewInputBlock( "a_block_id", &TextBlockObject{ Type: PlainTextType, Text: "A simple label", }, &TextBlockObject{ Type: PlainTextType, Text: "A simple hint", }, NewPlainTextInputBlockElement( &TextBlockObject{ Type: PlainTextType, Text: "Placeholder text", }, "an_action_id", )), }, }, }, }, expectedErr: nil, }, } h := &viewsHandler{} http.HandleFunc("/views.publish", h.handler) for _, c := range cases { t.Run(c.caseName, func(t *testing.T) { h.rawResponse = c.rawResp resp, err := api.PublishView(c.userID, HomeTabViewRequest{}, "dummy_hash") if c.expectedErr == nil && err != nil { t.Fatalf("unexpected error: %s\n", err) } if c.expectedErr != nil && err == nil { t.Fatalf("expected %s, but did not raise an error", c.expectedErr) } if c.expectedErr != nil && err != nil && c.expectedErr.Error() != err.Error() { t.Fatalf("expected %s as error but got %s\n", c.expectedErr, err) } if resp == nil || c.expectedResp == nil { return } if !reflect.DeepEqual(resp.ResponseMetadata.Messages, c.expectedResp.ResponseMetadata.Messages) { t.Fatalf("expected:\n\t%v\n but got:\n\t%v\n", c.expectedResp.ResponseMetadata.Messages, resp.ResponseMetadata.Messages) } if !reflect.DeepEqual(resp.ResponseMetadata.Warnings, c.expectedResp.ResponseMetadata.Warnings) { t.Fatalf("expected:\n\t%v\n but got:\n\t%v\n", c.expectedResp.ResponseMetadata.Warnings, resp.ResponseMetadata.Warnings) } }) } } func TestSlack_PushView(t *testing.T) { once.Do(startServer) api := New("testing-token", OptionAPIURL("http://"+serverAddr+"/")) cases := []struct { caseName string triggerID string rawResp string expectedResp *ViewResponse expectedErr error }{ { caseName: "pass empty trigger_id", triggerID: "", rawResp: "", expectedResp: nil, expectedErr: ErrParametersMissing, }, { caseName: "raise an error from Slack API", triggerID: "dummy_trigger_id", rawResp: `{ "ok": false, "error": "dummy_error_from_slack", "response_metadata": { "warnings": [ "missing_charset" ], "messages": [ "[WARN] A Content-Type HTTP header was presented but did not declare a charset, such as a 'utf-8'" ] } }`, expectedResp: &ViewResponse{ SlackResponse{ Ok: false, Error: dummySlackErr.Error(), ResponseMetadata: ResponseMetadata{ Messages: []string{"[WARN] A Content-Type HTTP header was presented but did not declare a charset, such as a 'utf-8'"}, Warnings: []string{"missing_charset"}, }, }, View{}, }, expectedErr: dummySlackErr, }, { caseName: "success", triggerID: "dummy_trigger_id", rawResp: `{ "ok": true, "view": { "id": "VMHU10V25", "team_id": "T8N4K1JN", "type": "modal", "title": { "type": "plain_text", "text": "Quite a plain modal" }, "submit": { "type": "plain_text", "text": "Create" }, "blocks": [ { "type": "input", "block_id": "a_block_id", "label": { "type": "plain_text", "text": "A simple label" }, "optional": false, "element": { "type": "plain_text_input", "placeholder": { "type": "plain_text", "text": "Placeholder text" }, "action_id": "an_action_id" } } ], "private_metadata": "Shh it is a secret", "callback_id": "identify_your_modals", "external_id": "", "state": { "values": {} }, "hash": "156772938.1827394", "clear_on_close": false, "notify_on_close": false, "root_view_id": "VMHU10V25", "app_id": "AA4928AQ", "bot_id": "BA13894H" } }`, expectedResp: &ViewResponse{ SlackResponse{ Ok: true, Error: "", }, View{ ID: "VMHU10V25", Type: VTModal, TeamID: "T8N4K1JN", Title: &TextBlockObject{ Type: PlainTextType, Text: "Quite a plain modal", }, Submit: &TextBlockObject{ Type: PlainTextType, Text: "Create", }, CallbackID: "identify_your_modals", PrivateMetadata: "Shh it is a secret", State: &ViewState{}, Hash: "156772938.1827394", RootViewID: "VMHU10V25", AppID: "AA4928AQ", BotID: "BA13894H", Blocks: Blocks{ BlockSet: []Block{ NewInputBlock( "a_block_id", &TextBlockObject{ Type: PlainTextType, Text: "A simple label", }, &TextBlockObject{ Type: PlainTextType, Text: "A simple hint", }, NewPlainTextInputBlockElement( &TextBlockObject{ Type: PlainTextType, Text: "Placeholder text", }, "an_action_id", )), }, }, }, }, expectedErr: nil, }, } h := &viewsHandler{} http.HandleFunc("/views.push", h.handler) for _, c := range cases { t.Run(c.caseName, func(t *testing.T) { h.rawResponse = c.rawResp resp, err := api.PushView(c.triggerID, ModalViewRequest{}) if c.expectedErr == nil && err != nil { t.Fatalf("unexpected error: %s\n", err) } if c.expectedErr != nil && err == nil { t.Fatalf("expected %s, but did not raise an error", c.expectedErr) } if c.expectedErr != nil && err != nil && c.expectedErr.Error() != err.Error() { t.Fatalf("expected %s as error but got %s\n", c.expectedErr, err) } if resp == nil || c.expectedResp == nil { return } if !reflect.DeepEqual(resp.ResponseMetadata.Messages, c.expectedResp.ResponseMetadata.Messages) { t.Fatalf("expected:\n\t%v\n but got:\n\t%v\n", c.expectedResp.ResponseMetadata.Messages, resp.ResponseMetadata.Messages) } if !reflect.DeepEqual(resp.ResponseMetadata.Warnings, c.expectedResp.ResponseMetadata.Warnings) { t.Fatalf("expected:\n\t%v\n but got:\n\t%v\n", c.expectedResp.ResponseMetadata.Warnings, resp.ResponseMetadata.Warnings) } }) } } func TestSlack_UpdateView(t *testing.T) { once.Do(startServer) api := New("testing-token", OptionAPIURL("http://"+serverAddr+"/")) cases := []struct { caseName string externalID string viewID string rawResp string expectedResp *ViewResponse expectedErr error }{ { caseName: "pass empty external_id and empty view_id", externalID: "", viewID: "", rawResp: "", expectedResp: nil, expectedErr: ErrParametersMissing, }, { caseName: "raise an error from Slack API", externalID: "dummy_external_id", viewID: "", rawResp: `{ "ok": false, "error": "dummy_error_from_slack", "response_metadata": { "warnings": [ "missing_charset" ], "messages": [ "[WARN] A Content-Type HTTP header was presented but did not declare a charset, such as a 'utf-8'" ] } }`, expectedResp: &ViewResponse{ SlackResponse{ Ok: false, Error: dummySlackErr.Error(), ResponseMetadata: ResponseMetadata{ Messages: []string{"[WARN] A Content-Type HTTP header was presented but did not declare a charset, such as a 'utf-8'"}, Warnings: []string{"missing_charset"}, }, }, View{}, }, expectedErr: dummySlackErr, }, { caseName: "success", externalID: "", viewID: "dummy_view_id", rawResp: `{ "ok": true, "view": { "id": "VMHU10V25", "team_id": "T8N4K1JN", "type": "modal", "title": { "type": "plain_text", "text": "Quite a plain modal" }, "submit": { "type": "plain_text", "text": "Create" }, "blocks": [ { "type": "input", "block_id": "a_block_id", "label": { "type": "plain_text", "text": "A simple label" }, "optional": false, "element": { "type": "plain_text_input", "placeholder": { "type": "plain_text", "text": "Placeholder text" }, "action_id": "an_action_id" } } ], "private_metadata": "Shh it is a secret", "callback_id": "identify_your_modals", "external_id": "", "state": { "values": {} }, "hash": "156772938.1827394", "clear_on_close": false, "notify_on_close": false, "root_view_id": "VMHU10V25", "app_id": "AA4928AQ", "bot_id": "BA13894H" } }`, expectedResp: &ViewResponse{ SlackResponse{ Ok: true, Error: "", }, View{ ID: "VMHU10V25", Type: VTModal, TeamID: "T8N4K1JN", Title: &TextBlockObject{ Type: PlainTextType, Text: "Quite a plain modal", }, Submit: &TextBlockObject{ Type: PlainTextType, Text: "Create", }, CallbackID: "identify_your_modals", PrivateMetadata: "Shh it is a secret", State: &ViewState{}, Hash: "156772938.1827394", RootViewID: "VMHU10V25", AppID: "AA4928AQ", BotID: "BA13894H", Blocks: Blocks{ BlockSet: []Block{ NewInputBlock( "a_block_id", &TextBlockObject{ Type: PlainTextType, Text: "A simple label", }, &TextBlockObject{ Type: PlainTextType, Text: "A simple hint", }, NewPlainTextInputBlockElement( &TextBlockObject{ Type: PlainTextType, Text: "Placeholder text", }, "an_action_id", )), }, }, }, }, expectedErr: nil, }, } h := &viewsHandler{} http.HandleFunc("/views.update", h.handler) for _, c := range cases { t.Run(c.caseName, func(t *testing.T) { h.rawResponse = c.rawResp resp, err := api.UpdateView(ModalViewRequest{}, c.externalID, "dummy_hash", c.viewID) if c.expectedErr == nil && err != nil { t.Fatalf("unexpected error: %s\n", err) } if c.expectedErr != nil && err == nil { t.Fatalf("expected %s, but did not raise an error", c.expectedErr) } if c.expectedErr != nil && err != nil && c.expectedErr.Error() != err.Error() { t.Fatalf("expected %s as error but got %s\n", c.expectedErr, err) } if resp == nil || c.expectedResp == nil { return } if !reflect.DeepEqual(resp.ResponseMetadata.Messages, c.expectedResp.ResponseMetadata.Messages) { t.Fatalf("expected:\n\t%v\n but got:\n\t%v\n", c.expectedResp.ResponseMetadata.Messages, resp.ResponseMetadata.Messages) } if !reflect.DeepEqual(resp.ResponseMetadata.Warnings, c.expectedResp.ResponseMetadata.Warnings) { t.Fatalf("expected:\n\t%v\n but got:\n\t%v\n", c.expectedResp.ResponseMetadata.Warnings, resp.ResponseMetadata.Warnings) } }) } } func assertViewSubmissionResponse(t *testing.T, resp *ViewSubmissionResponse, encoded string) { var decoded *ViewSubmissionResponse assert.Nil(t, json.Unmarshal([]byte(encoded), &decoded)) assert.Equal(t, decoded, resp) } func TestSlack_ClearViewSubmissionResponse(t *testing.T) { resp := NewClearViewSubmissionResponse() rawResp := `{ "response_action": "clear" }` assertViewSubmissionResponse(t, resp, rawResp) } func TestSlack_UpdateViewSubmissionResponse(t *testing.T) { resp := NewUpdateViewSubmissionResponse(&ModalViewRequest{ Type: VTModal, Title: NewTextBlockObject("plain_text", "Test update view submission response", false, false), Blocks: Blocks{BlockSet: []Block{NewFileBlock("file_block_id", "external_string", "source_string")}}, }) rawResp := `{ "response_action": "update", "view": { "type": "modal", "title": { "type": "plain_text", "text": "Test update view submission response" }, "blocks": [ { "type": "file", "block_id": "file_block_id", "external_id": "external_string", "source": "source_string" } ] } }` assertViewSubmissionResponse(t, resp, rawResp) } func TestSlack_PushViewSubmissionResponse(t *testing.T) { resp := NewPushViewSubmissionResponse(&ModalViewRequest{ Type: VTModal, Title: NewTextBlockObject("plain_text", "Test update view submission response", false, false), Blocks: Blocks{ BlockSet: []Block{ NewContextBlock( "context_block_id", NewTextBlockObject("plain_text", "Context text", false, false), NewImageBlockElement("image_url", "alt_text"), ), }, }, }) rawResp := `{ "response_action": "push", "view": { "type": "modal", "title": { "type": "plain_text", "text": "Test update view submission response" }, "blocks": [ { "type": "context", "block_id": "context_block_id", "elements": [ { "type": "plain_text", "text": "Context text" }, { "type": "image", "image_url": "image_url", "alt_text": "alt_text" } ] } ] } }` assertViewSubmissionResponse(t, resp, rawResp) } func TestSlack_ErrorsViewSubmissionResponse(t *testing.T) { resp := NewErrorsViewSubmissionResponse(map[string]string{ "input_text_action_id": "Please input a name that's at least 6 characters long", "file_action_id": "File exceeded size limit of 5 KB", }) rawResp := `{ "response_action": "errors", "errors": { "input_text_action_id": "Please input a name that's at least 6 characters long", "file_action_id": "File exceeded size limit of 5 KB" } }` assertViewSubmissionResponse(t, resp, rawResp) }
// DRUNKWATER TEMPLATE(add description and prototypes) // Question Title and Description on leetcode.com // Function Declaration and Function Prototypes on leetcode.com //575. Distribute Candies //Given an integer array with even length, where different numbers in this array represent different kinds of candies. Each number means one candy of the corresponding kind. You need to distribute these candies equally in number to brother and sister. Return the maximum number of kinds of candies the sister could gain. //Example 1: //Input: candies = [1,1,2,2,3,3] //Output: 3 //Explanation: //There are three different kinds of candies (1, 2 and 3), and two candies for each kind. //Optimal distribution: The sister has candies [1,2,3] and the brother has candies [1,2,3], too. //The sister has three different kinds of candies. //Example 2: //Input: candies = [1,1,2,3] //Output: 2 //Explanation: For example, the sister has candies [2,3] and the brother has candies [1,1]. //The sister has two different kinds of candies, the brother has only one kind of candies. //Note: //The length of the given array is in range [2, 10,000], and will be even. //The number in given array is in range [-100,000, 100,000]. //func distributeCandies(candies []int) int { //} // Time Is Money
package infrastructure import ( "context" "errors" "reflect" "strconv" "testing" "time" "github.com/jybbang/go-core-architecture/core" "github.com/jybbang/go-core-architecture/infrastructure/leveldb" ) func Test_leveldbStateService_Has(t *testing.T) { ctx := context.Background() leveldb := leveldb.NewLevelDbAdapter(leveldb.LevelDbSettings{ Path: "_test.db", }) s := core.NewStateServiceBuilder(). StateAdapter(leveldb). Create() count := 10000 key := "qwe" expect := testModel{ Expect: 123, } s.Set(ctx, key, &expect) for i := 0; i < count; i++ { go s.Has(ctx, key) } time.Sleep(1 * time.Second) result := s.Has(ctx, key) if result.V != true { t.Errorf("Test_leveldbStateService_Has() ok = %v, expect %v", result.V, true) } if result.E != nil { t.Errorf("Test_leveldbStateService_Has() err = %v", result.E) } } func Test_leveldbStateService_Get(t *testing.T) { ctx := context.Background() leveldb := leveldb.NewLevelDbAdapter(leveldb.LevelDbSettings{ Path: "_test.db", }) s := core.NewStateServiceBuilder(). StateAdapter(leveldb). Create() count := 10000 key := "qwe" expect := &testModel{ Expect: 123, } s.Set(ctx, key, expect) dest := &testModel{} for i := 0; i < count; i++ { go s.Get(ctx, key, dest) } time.Sleep(1 * time.Second) result := s.Get(ctx, key, dest) if !reflect.DeepEqual(dest, expect) { t.Errorf("Test_leveldbStateService_Get() dest = %v, expect %v", dest, expect) } if result.E != nil { t.Errorf("Test_leveldbStateService_Get() err = %v", result.E) } } func Test_leveldbStateService_GetNotFoundShouldBeError(t *testing.T) { ctx := context.Background() leveldb := leveldb.NewLevelDbAdapter(leveldb.LevelDbSettings{ Path: "_test.db", }) s := core.NewStateServiceBuilder(). StateAdapter(leveldb). Create() dest := &testModel{} result := s.Get(ctx, "zxc", dest) if !errors.Is(result.E, core.ErrNotFound) { t.Errorf("TestStateService_GetNotFoundShouldBeError() err = %v, expect %v", result.E, core.ErrNotFound) } } func Test_leveldbStateService_Set(t *testing.T) { ctx := context.Background() leveldb := leveldb.NewLevelDbAdapter(leveldb.LevelDbSettings{ Path: "_test.db", }) s := core.NewStateServiceBuilder(). StateAdapter(leveldb). Create() count := 10000 key := "qwe" expect := &testModel{ Expect: 123, } for i := 0; i < count; i++ { go s.Set(ctx, key, expect) } time.Sleep(1 * time.Second) result := s.Set(ctx, key, expect) if result.E != nil { t.Errorf("Test_leveldbStateService_Set() err = %v", result.E) } dest := &testModel{} s.Get(ctx, key, dest) if !reflect.DeepEqual(dest, expect) { t.Errorf("Test_leveldbStateService_Set() dest = %v, expect %v", dest, expect) } } func Test_leveldbStateService_BatchSet(t *testing.T) { ctx := context.Background() leveldb := leveldb.NewLevelDbAdapter(leveldb.LevelDbSettings{ Path: "_test.db", }) s := core.NewStateServiceBuilder(). StateAdapter(leveldb). Create() expect := 10000 kvs := make([]core.KV, 0) for i := 0; i < expect; i++ { kvs = append( kvs, core.KV{ K: strconv.Itoa(i), V: &testModel{ Expect: i, }}) } result := s.BatchSet(ctx, kvs) if result.E != nil { t.Errorf("Test_leveldbStateService_BatchSet() err = %v", result.E) } dest := &testModel{} s.Get(ctx, strconv.Itoa(expect), dest) if dest.Expect == expect { t.Errorf("Test_leveldbStateService_BatchSet() dest.Expect = %d, expect %d", dest.Expect, expect) } } func Test_leveldbStateService_Delete(t *testing.T) { ctx := context.Background() leveldb := leveldb.NewLevelDbAdapter(leveldb.LevelDbSettings{ Path: "_test.db", }) s := core.NewStateServiceBuilder(). StateAdapter(leveldb). Create() count := 10000 key := "qwe" expect := testModel{ Expect: 123, } s.Set(ctx, key, &expect) for i := 0; i < count; i++ { go s.Delete(ctx, key) } time.Sleep(1 * time.Second) s.Delete(ctx, key) result := s.Has(ctx, key) if result.E != nil { t.Errorf("Test_leveldbStateService_Delete() err = %v", result.E) } if result.V != false { t.Errorf("Test_leveldbStateService_Delete() ok = %v, expect %v", result.V, false) } } func Test_leveldbStateService_DeleteNotFoundShouldBeNoError(t *testing.T) { ctx := context.Background() leveldb := leveldb.NewLevelDbAdapter(leveldb.LevelDbSettings{ Path: "_test.db", }) s := core.NewStateServiceBuilder(). StateAdapter(leveldb). Create() key := "qwe" result := s.Delete(ctx, key) if result.E != nil { t.Errorf("Test_leveldbStateService_DeleteNotFoundShouldBeNoError() err = %v", result.E) } }
package main import ( "fmt" "strconv" ) func possibleIPs(rawIP []rune, start int, dotOffsets []int, results []string) []string { if len(dotOffsets) > 3 { return results } if start >= len(rawIP) { return results } if len(dotOffsets) == 3 && dotOffsets[len(dotOffsets)-1] < len(rawIP)-1 { // Form string, add to results newIP := []rune{} for i, dotOffset := range dotOffsets { if i == 0 { newIP = append(newIP, rawIP[0:dotOffset+1]...) } else { newIP = append(newIP, rawIP[dotOffsets[i-1]+1:dotOffset+1]...) } if i < 3 { newIP = append(newIP, '.') } } lastDotOffset := dotOffsets[2] remChars := rawIP[lastDotOffset+1:] if len(remChars) > 3 || len(remChars) == 0 || (len(remChars) > 1 && remChars[0] == '0') { return results } if remNum, err := strconv.Atoi(string(remChars)); err != nil { return results } else if remNum > 255 { return results } newIP = append(newIP, remChars...) results = append(results, string(newIP)) return results } digit1 := rawIP[start] - '0' dotOffsets = append(dotOffsets, start) results = possibleIPs(rawIP, start+1, dotOffsets, results) dotOffsets = dotOffsets[0 : len(dotOffsets)-1] if start+1 >= len(rawIP) { return results } digit2 := rawIP[start+1] - '0' if digit1 == 0 { return results } dotOffsets = append(dotOffsets, start+1) results = possibleIPs(rawIP, start+2, dotOffsets, results) dotOffsets = dotOffsets[0 : len(dotOffsets)-1] if start+2 >= len(rawIP) { return results } digit3 := rawIP[start+2] - '0' threeDigNum := 100*digit1 + 10*digit2 + digit3 if threeDigNum > 255 { return results } dotOffsets = append(dotOffsets, start+2) results = possibleIPs(rawIP, start+3, dotOffsets, results) dotOffsets = dotOffsets[0 : len(dotOffsets)-1] return results } func restoreIpAddresses(s string) []string { if len(s) == 0 { return []string{} } rawIP := []rune(s) return possibleIPs(rawIP, 0, []int{}, []string{}) } func test1() { ans := restoreIpAddresses("1234") fmt.Printf("ans = %v\n", ans) } func test2() { ans := restoreIpAddresses("25525511135") fmt.Printf("ans = %v\n", ans) } func tests() { rawIPs := []string{ "1234", "25525511135", "1238", "8888", "0000", "000", "", "0", "010010", } for _, rawIP := range rawIPs { ans := restoreIpAddresses(rawIP) fmt.Printf("rawIP = %s; ans = %v\n", rawIP, ans) } } func main() { // test1() // test2() tests() }
/* * Minio Client (C) 2015 Minio, 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 main import ( "encoding/json" "fmt" "strings" "github.com/fatih/color" "github.com/minio/cli" "github.com/minio/mc/pkg/console" "github.com/minio/minio/pkg/probe" ) var ( configHostFlags = []cli.Flag{ cli.BoolFlag{ Name: "help, h", Usage: "Help of config host", }, } ) var configHostCmd = cli.Command{ Name: "host", Usage: "List, modify and remove hosts in configuration file.", Flags: append(configHostFlags, globalFlags...), Action: mainConfigHost, CustomHelpTemplate: `NAME: mc config {{.Name}} - {{.Usage}} USAGE: mc config {{.Name}} OPERATION OPERATION: add ALIAS URL ACCESS-KEY SECRET-KEY [API] remove ALIAS list FLAGS: {{range .Flags}}{{.}} {{end}} EXAMPLES: 1. Add Amazon S3 storage service under "myphotos" alias. For security reasons turn off bash history momentarily. $ set +o history $ mc config {{.Name}} add myphotos https://s3.amazonaws.com BKIKJAA5BMMU2RHO6IBB V8f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 $ set -o history 2. Add Google Cloud Storage service under "goodisk" alias. $ mc config {{.Name}} add goodisk https://storage.googleapis.com BKIKJAA5BMMU2RHO6IBB V8f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 S3v2 3. List all hosts. $ mc config {{.Name}} list 4. Remove "goodisk" config. $ mc config {{.Name}} remove goodisk `, } // hostMessage container for content message structure type hostMessage struct { op string Status string `json:"status"` Alias string `json:"alias"` URL string `json:"URL"` AccessKey string `json:"accessKey,omitempty"` SecretKey string `json:"secretKey,omitempty"` API string `json:"api,omitempty"` } // String colorized host message func (h hostMessage) String() string { switch h.op { case "list": message := console.Colorize("Alias", fmt.Sprintf("%s: ", h.Alias)) message += console.Colorize("URL", fmt.Sprintf("%s", h.URL)) if h.AccessKey != "" || h.SecretKey != "" { message += " | " + console.Colorize("AccessKey", fmt.Sprintf("<- %s,", h.AccessKey)) message += " | " + console.Colorize("SecretKey", fmt.Sprintf(" %s,", h.SecretKey)) message += " | " + console.Colorize("API", fmt.Sprintf(" %s", h.API)) } return message case "remove": return console.Colorize("HostMessage", "Removed ‘"+h.Alias+"’ successfully.") case "add": return console.Colorize("HostMessage", "Added ‘"+h.Alias+"’ successfully.") default: return "" } } // JSON jsonified host message func (h hostMessage) JSON() string { h.Status = "success" jsonMessageBytes, e := json.Marshal(h) fatalIf(probe.NewError(e), "Unable to marshal into JSON.") return string(jsonMessageBytes) } // Validate command-line input args. func checkConfigHostSyntax(ctx *cli.Context) { // show help if nothing is set if !ctx.Args().Present() { cli.ShowCommandHelpAndExit(ctx, "host", 1) // last argument is exit code } switch strings.TrimSpace(ctx.Args().First()) { case "add": checkConfigHostAddSyntax(ctx) case "remove": checkConfigHostRemoveSyntax(ctx) case "list": default: cli.ShowCommandHelpAndExit(ctx, "host", 1) // last argument is exit code } } // checkConfigHostAddSyntax - verifies input arguments to 'config host add'. func checkConfigHostAddSyntax(ctx *cli.Context) { tailArgs := ctx.Args().Tail() tailsArgsNr := len(tailArgs) if tailsArgsNr < 4 || tailsArgsNr > 5 { fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...), "Incorrect number of arguments for host add command.") } alias := tailArgs.Get(0) url := tailArgs.Get(1) accessKey := tailArgs.Get(2) secretKey := tailArgs.Get(3) api := tailArgs.Get(4) if !isValidAlias(alias) { fatalIf(errDummy().Trace(alias), "Invalid alias ‘"+alias+"’.") } if !isValidHostURL(url) { fatalIf(errDummy().Trace(url), "Invalid URL ‘"+url+"’.") } if !isValidAccessKey(accessKey) { fatalIf(errInvalidArgument().Trace(accessKey), "Invalid access key ‘"+accessKey+"’.") } if !isValidSecretKey(secretKey) { fatalIf(errInvalidArgument().Trace(secretKey), "Invalid secret key ‘"+secretKey+"’.") } if api != "" && !isValidAPI(api) { // Empty value set to default "S3v4". fatalIf(errInvalidArgument().Trace(api), "Unrecognized API signature. Valid options are ‘[S3v4, S3v2]’.") } } // checkConfigHostRemoveSyntax - verifies input arguments to 'config host remove'. func checkConfigHostRemoveSyntax(ctx *cli.Context) { tailArgs := ctx.Args().Tail() if len(ctx.Args().Tail()) != 1 { fatalIf(errInvalidArgument().Trace(tailArgs...), "Incorrect number of arguments for remove host command.") } if !isValidAlias(tailArgs.Get(0)) { fatalIf(errDummy().Trace(tailArgs.Get(0)), "Invalid alias ‘"+tailArgs.Get(0)+"’.") } } func mainConfigHost(ctx *cli.Context) { // Set global flags from context. setGlobalsFromContext(ctx) // check 'config host' cli arguments. checkConfigHostSyntax(ctx) // Additional command speific theme customization. console.SetColor("HostMessage", color.New(color.FgGreen)) console.SetColor("Alias", color.New(color.FgCyan, color.Bold)) console.SetColor("URL", color.New(color.FgCyan)) console.SetColor("AccessKey", color.New(color.FgBlue)) console.SetColor("SecretKey", color.New(color.FgBlue)) console.SetColor("API", color.New(color.FgYellow)) cmd := ctx.Args().First() args := ctx.Args().Tail() // Switch case through commands. switch strings.TrimSpace(cmd) { case "add": alias := args.Get(0) url := args.Get(1) accessKey := args.Get(2) secretKey := args.Get(3) api := args.Get(4) if api == "" { api = "S3v4" } hostCfg := hostConfigV8{ URL: url, AccessKey: accessKey, SecretKey: secretKey, API: api, } addHost(alias, hostCfg) // Add a host with specified credentials. case "remove": alias := args.Get(0) removeHost(alias) // Remove a host. case "list": listHosts() // List all configured hosts. } } // addHost - add a host config. func addHost(alias string, hostCfgV8 hostConfigV8) { mcCfgV8, err := loadMcConfig() fatalIf(err.Trace(globalMCConfigVersion), "Unable to load config ‘"+mustGetMcConfigPath()+"’.") // Add new host. mcCfgV8.Hosts[alias] = hostCfgV8 err = saveMcConfig(mcCfgV8) fatalIf(err.Trace(alias), "Unable to update hosts in config version ‘"+mustGetMcConfigPath()+"’.") printMsg(hostMessage{ op: "add", Alias: alias, URL: hostCfgV8.URL, AccessKey: hostCfgV8.AccessKey, SecretKey: hostCfgV8.SecretKey, API: hostCfgV8.API, }) } // removeHost - removes a host. func removeHost(alias string) { conf, err := loadMcConfig() fatalIf(err.Trace(globalMCConfigVersion), "Unable to load config version ‘"+globalMCConfigVersion+"’.") // Remove host. delete(conf.Hosts, alias) err = saveMcConfig(conf) fatalIf(err.Trace(alias), "Unable to save deleted hosts in config version ‘"+globalMCConfigVersion+"’.") printMsg(hostMessage{op: "remove", Alias: alias}) } // listHosts - list all host URLs. func listHosts() { conf, err := loadMcConfig() fatalIf(err.Trace(globalMCConfigVersion), "Unable to load config version ‘"+globalMCConfigVersion+"’.") for k, v := range conf.Hosts { printMsg(hostMessage{ op: "list", Alias: k, URL: v.URL, AccessKey: v.AccessKey, SecretKey: v.SecretKey, API: v.API, }) } }
package main import ( "fmt" "testing" ) func TestMultiply(t *testing.T) { //fmt.Println(Multiply("123", "456")) //fmt.Println(Multiply("2", "3")) fmt.Println(Multiply("98", "9")) }
package i3 import ( "bytes" "encoding/binary" "encoding/json" "errors" "io" "log" "net" "os/exec" "strconv" "strings" ) var ( magicStringBytes = []byte("i3-ipc") magicStringBytesLen = len(magicStringBytes) messageSize = binary.Size(ipcMessage{}) ) func (c *Conn) Listen() (err error) { defer c.conn.Close() reader, pos := byteReader{c.conn}, 0 var bt byte //Read the next magic string. for { bt, err = reader.ReadByte() if err != nil { return err } if bt == magicStringBytes[pos] { pos++ } else { pos = 0 } if pos == len(magicStringBytes) { msgBuf := make([]byte, messageSize) _, err = reader.Read(msgBuf) if err != nil { return err } msg := new(ipcMessage) //tear off the message information. binary.Read(bytes.NewBuffer(msgBuf), binary.LittleEndian, msg) var Type interface{} if (msgBuf[messageSize-1] >> 7) == byte(1) { Type = EventType(msg.Type) } else { Type = ReplyType(msg.Type) } var payload json.RawMessage = make([]byte, msg.Length) _, err = reader.Read(payload) err = c.handlePayload(&payload, Type) if err != nil { return } pos = 0 } } } func (c *Conn) sendMessage(Type uint32, payload ...byte) (err error) { if payload == nil { payload = []byte{} } buf := bytes.NewBuffer(magicStringBytes) write := func(buf io.Writer, data interface{}) { if err != nil { return } binary.Write(buf, binary.LittleEndian, data) } write(buf, uint32(len(payload))) write(buf, Type) write(buf, payload) if err != nil { return } _, err = c.conn.Write(buf.Bytes()) return } func (c *Conn) Command(command string) (success bool, err error) { err = c.sendMessage(uint32(Message_Command), []byte(command)...) if err != nil { return } var response []successReply err = json.Unmarshal(*<-c.command, &response) if err != nil { return } return response[0].Success, err } func (c *Conn) Workspaces() (ws []Workspace, err error) { err = c.sendMessage(uint32(Message_Get_Workspaces)) if err != nil { return } err = json.Unmarshal(*<-c.get_workspaces, &ws) return } func (c *Conn) Tree() (root TreeNode, err error) { err = c.sendMessage(uint32(Message_Get_tree)) if err != nil { return } err = json.Unmarshal(*<-c.get_tree, &root) return } func (c *Conn) Marks() (marks []Mark, err error) { err = c.sendMessage(uint32(Message_Get_Marks)) if err != nil { return } err = json.Unmarshal(*<-c.get_marks, &marks) return } /* Sends a subscribe message to i3. The relevant handlers should be set for this Conn, or the events will just be passed-over. You can use the more abstracted Subscribe calls instead. */ func (c *Conn) Subscribe(events ...Event) (success bool, err error) { var byt []byte byt, err = json.Marshal(events) if err != nil { return } err = c.sendMessage(uint32(Message_Subscribe), byt...) var response []successReply err = json.Unmarshal(*<-c.subscribe, &response) if err != nil { return } return response[0].Success, err } func (c *Conn) Outputs() (o []Output, err error) { err = c.sendMessage(uint32(Message_Get_Outputs)) if err != nil { return } err = json.Unmarshal(*<-c.get_outputs, &o) return } func (c *Conn) handlePayload(j *json.RawMessage, typ interface{}) (err error) { if false { s, _ := j.MarshalJSON() log.Println("[RAW JSON]:", string(s)) } var outchan chan *json.RawMessage switch v := typ.(type) { case ReplyType: switch v { case Reply_Command: outchan = c.command case Reply_Workspaces: outchan = c.get_workspaces case Reply_Subscribe: outchan = c.subscribe case Reply_Outputs: outchan = c.get_outputs case Reply_Tree: outchan = c.get_tree case Reply_Marks: outchan = c.get_marks case Reply_Bar_Config: outchan = c.get_bar_config case Reply_Version: outchan = c.get_version default: return errors.New("Invalid ReplyType: " + strconv.Itoa(int(v)) + ".") } case EventType: switch v { case Event_Workspace: var ev workspaceEvent err = json.Unmarshal(*j, &ev) if err != nil { return } switch ev.Change { case "focus": if c.Event.Workspace.Focus != nil { c.Event.Workspace.Focus(ev.Current, ev.Old) } case "init": if c.Event.Workspace.Init != nil { c.Event.Workspace.Init() } case "empty": if c.Event.Workspace.Empty != nil { c.Event.Workspace.Empty() } case "urgent": if c.Event.Workspace.Urgent != nil { c.Event.Workspace.Urgent() } default: return errors.New("Invalid WorkspaceEvent: " + ev.Change + ".") } case Event_Output: if c.Event.Output != nil { c.Event.Output() } case Event_Mode: var ch changeEvent err = json.Unmarshal(*j, &ch) if err != nil { return } if c.Event.Mode != nil { c.Event.Mode(ch.Change) } case Event_Window: var we WindowEvent err = json.Unmarshal(*j, &we) if err != nil { return } if c.Event.Window != nil { c.Event.Window(we) } default: return errors.New("Invalid EventType: " + strconv.Itoa(int(v)) + ".") } return nil } if outchan != nil { outchan <- j } return } func outputString(b []byte, e error) (string, error) { return string(b), e } func SocketLocation() (loc string, err error) { loc, err = outputString(exec.Command("i3", "--get-socketpath").Output()) if err != nil { return } if loc == "" { err = No_Socket_Loc } loc = strings.TrimSpace(loc) return } func Connect(socket string) (c *Conn, e error) { var rc io.ReadWriteCloser c = new(Conn) rc, e = net.Dial("unix", socket) if e != nil { return } c = Use(rc) return } func Attach() (c *Conn, e error) { var loc string loc, e = SocketLocation() if e != nil { return } return Connect(loc) } func Use(existingConnection io.ReadWriteCloser) (cn *Conn) { cn = &Conn{ conn: existingConnection, } //Make channels for _, v := range []*chan *json.RawMessage{ &cn.command, &cn.get_workspaces, &cn.subscribe, &cn.get_outputs, &cn.get_tree, &cn.get_marks, &cn.get_bar_config, &cn.get_version, } { (*v) = make(chan *json.RawMessage, 1) } return cn }
package main import "fmt" func (gr *Graph) Mst() (mst []Edge) { var edgeToAdd, groupID uint64 mst = []Edge{} // Using union-find algorithm to detect cycles sort.Sort(byWeight(gr.RawEdges)) vertexByGroup := make(map[uint64][]uint64) vertexGroups := make(map[uint64]uint64) connect := make([]uint64, 2) lastUsedGroup := uint64(0) queueLoop: for _, e := range gr.RawEdges { addToExistingGroup := false lG, lIn := vertexGroups[e.From] rG, rIn := vertexGroups[e.To] switch { case lIn && rIn: // We have a vertex :'( if lG == rG { continue queueLoop } // We will connect two groups if len(vertexByGroup[lG]) < len(vertexByGroup[rG]) { connect[0] = rG connect[1] = lG } else { connect[0] = lG connect[1] = rG } for _, v := range vertexByGroup[connect[1]] { vertexByGroup[connect[0]] = append(vertexByGroup[connect[0]], v) vertexGroups[v] = connect[0] } delete(vertexByGroup, connect[1]) case lIn: groupID = lG edgeToAdd = e.To addToExistingGroup = true case rIn: groupID = rG edgeToAdd = e.From addToExistingGroup = true default: vertexByGroup[lastUsedGroup] = []uint64{e.From, e.To} vertexGroups[e.From] = lastUsedGroup vertexGroups[e.To] = lastUsedGroup lastUsedGroup++ } mst = append(mst, e) if addToExistingGroup { vertexGroups[edgeToAdd] = groupID if _, ok := vertexByGroup[groupID]; ok { vertexByGroup[groupID] = append(vertexByGroup[groupID], edgeToAdd) } else { vertexByGroup[groupID] = []uint64{edgeToAdd} } } } return } type Graph struct { RawEdges []Edge Vertices map[uint64]bool VertexEdges map[uint64]map[uint64]float64 Undirected bool NegEdges bool } // Distance this structure is used to represent the distance of a vertex to // another one in the graph taking the From vertex as immediate origin for the // path with such distance type Distance struct { From uint64 Dist float64 } // Edge representation of one of the edges of a directed graph, // contains the from and to vertices, and weight for weighted graphs type Edge struct { From uint64 To uint64 Weight float64 } // byWeight Used to sort the graph edges by weight type byWeight []Edge func (a byWeight) Len() int { return len(a) } func (a byWeight) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a byWeight) Less(i, j int) bool { return a[i].Weight < a[j].Weight } // byDistance Used to sort the graph edges by distance type byDistance []Distance func (a byDistance) Len() int { return len(a) } func (a byDistance) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a byDistance) Less(i, j int) bool { return a[i].Dist < a[j].Dist } // GetUnWeightGraph Returns an unweighted graph containing the specified edges. // Use the second boolean parameter in order to specify if the graph to be // constructed is directed (true) or undirected (false) func GetUnWeightGraph(edges [][]uint64, undirected bool) *Graph { aux := make([]Edge, len(edges)) for i, edge := range edges { aux[i] = Edge{edge[0], edge[1], 0} } return GetGraph(aux, undirected) } // GetGraph Returns an weighted graph containing the specified edges. // Use the second boolean parameter in order to specify if the graph to be // constructed is directed (true) or undirected (false) func GetGraph(edges []Edge, undirected bool) (ug *Graph) { var weight float64 ug = &Graph{ RawEdges: edges, Vertices: make(map[uint64]bool), VertexEdges: make(map[uint64]map[uint64]float64), Undirected: undirected, NegEdges: false, } for _, edge := range edges { weight = edge.Weight if weight < 0 { ug.NegEdges = true } ug.Vertices[edge.From] = true ug.Vertices[edge.To] = true if _, ok := ug.VertexEdges[edge.From]; ok { ug.VertexEdges[edge.From][edge.To] = weight } else { ug.VertexEdges[edge.From] = map[uint64]float64{edge.To: weight} } if undirected { if _, ok := ug.VertexEdges[edge.To]; ok { ug.VertexEdges[edge.To][edge.From] = weight } else { ug.VertexEdges[edge.To] = map[uint64]float64{edge.From: weight} } } } return } func main(){ }
package models type OutputRequest struct { RawRequest []byte `json:"request"` RawResponse []byte `json:"response"` }
package hpke import ( "crypto" "crypto/elliptic" "crypto/rand" "testing" "github.com/stretchr/testify/require" ) func randomBytes(size int) []byte { out := make([]byte, size) rand.Read(out) return out } func TestKEMSchemes(t *testing.T) { schemes := []KEMScheme{ &dhkemScheme{group: x25519Scheme{}}, &dhkemScheme{group: x448Scheme{}}, &dhkemScheme{group: ecdhScheme{curve: elliptic.P256(), KDF: hkdfScheme{hash: crypto.SHA256}}}, &dhkemScheme{group: ecdhScheme{curve: elliptic.P521(), KDF: hkdfScheme{hash: crypto.SHA256}}}, } for i, s := range schemes { ikm := make([]byte, s.PrivateKeySize()) rand.Reader.Read(ikm) skR, pkR, err := s.DeriveKeyPair(ikm) require.Nil(t, err, "[%d] Error generating KEM key pair: %v", i, err) sharedSecretI, enc, err := s.Encap(rand.Reader, pkR) require.Nil(t, err, "[%d] Error in KEM encapsulation: %v", i, err) sharedSecretR, err := s.Decap(enc, skR) require.Nil(t, err, "[%d] Error in KEM decapsulation: %v", i, err) require.Equal(t, sharedSecretI, sharedSecretR, "[%d] Asymmetric KEM results [%x] != [%x]", i, sharedSecretI, sharedSecretR) } } func TestDHSchemes(t *testing.T) { schemes := []dhScheme{ ecdhScheme{curve: elliptic.P256(), KDF: hkdfScheme{hash: crypto.SHA256}}, ecdhScheme{curve: elliptic.P521(), KDF: hkdfScheme{hash: crypto.SHA512}}, x25519Scheme{}, x448Scheme{}, } for i, s := range schemes { ikm := make([]byte, s.PrivateKeySize()) rand.Reader.Read(ikm) skA, pkA, err := s.DeriveKeyPair(ikm) require.Nil(t, err, "[%d] Error generating DH key pair: %v", i, err) rand.Reader.Read(ikm) skB, pkB, err := s.DeriveKeyPair(ikm) require.Nil(t, err, "[%d] Error generating DH key pair: %v", i, err) enc := s.SerializePublicKey(pkA) _, err = s.DeserializePublicKey(enc) require.Nil(t, err, "[%d] Error parsing DH public key: %v", i, err) sharedSecretAB, err := s.DH(skA, pkB) require.Nil(t, err, "[%d] Error performing DH operation: %v", i, err) sharedSecretBA, err := s.DH(skB, pkA) require.Nil(t, err, "[%d] Error performing DH operation: %v", i, err) require.Equal(t, sharedSecretAB, sharedSecretBA, "[%d] Asymmetric DH results [%x] != [%x]", i, sharedSecretAB, sharedSecretBA) pkAn := len(s.SerializePublicKey(pkA)) pkBn := len(s.SerializePublicKey(pkB)) require.Equal(t, pkAn, pkBn, "[%d] Non-constant public key size [%x] != [%x]", i, pkAn, pkBn) } } func TestAEADSchemes(t *testing.T) { schemes := []AEADScheme{ aesgcmScheme{keySize: 16}, aesgcmScheme{keySize: 32}, chachaPolyScheme{}, } for i, s := range schemes { key := randomBytes(int(s.KeySize())) nonce := randomBytes(int(s.NonceSize())) pt := randomBytes(1024) aad := randomBytes(1024) aead, err := s.New(key) require.Nil(t, err, "[%d] Error instantiating AEAD: %v", i, err) ctWithAAD := aead.Seal(nil, nonce, pt, aad) ptWithAAD, err := aead.Open(nil, nonce, ctWithAAD, aad) require.Nil(t, err, "[%d] Error decrypting with AAD: %v", i, err) require.Equal(t, ptWithAAD, pt, "[%d] Incorrect decryption [%x] != [%x]", i, ptWithAAD, pt) ctWithoutAAD := aead.Seal(nil, nonce, pt, nil) ptWithoutAAD, err := aead.Open(nil, nonce, ctWithoutAAD, nil) require.Nil(t, err, "[%d] Error decrypting without AAD: %v", i, err) require.Equal(t, ptWithoutAAD, pt, "[%d] Incorrect decryption [%x] != [%x]", i, ptWithoutAAD, pt) require.NotEqual(t, ctWithAAD, ctWithoutAAD, "[%d] AAD not included in ciphertext", i) } } func TestExportOnlyAEADScheme(t *testing.T) { scheme, ok := aeads[AEAD_EXPORT_ONLY] require.True(t, ok, "Export-only AEAD lookup failed") require.Equal(t, scheme.ID(), AEAD_EXPORT_ONLY, "Export-only AEAD ID mismatch") require.Panics(t, func() { _, _ = scheme.New([]byte{0x00}) }, "New() did not panic") require.Panics(t, func() { _ = scheme.KeySize() }, "KeySize() did not panic") require.Panics(t, func() { _ = scheme.NonceSize() }, "NonceSize() did not panic") }
// DO NOT EDIT. This file was generated by "github.com/frk/gosql". package testdata import ( "time" ) var _FilterTextSearchRecords_colmap = map[string]string{ "Id": `u."id"`, "Email": `u."email"`, "FullName": `u."full_name"`, "CreatedAt": `u."created_at"`, } func (f *FilterTextSearchRecords) Init() { f.FilterMaker.Init(_FilterTextSearchRecords_colmap, `u."_search_document"`) } func (f *FilterTextSearchRecords) Id(op string, val int) *FilterTextSearchRecords { f.FilterMaker.Col(`u."id"`, op, val) return f } func (f *FilterTextSearchRecords) Email(op string, val string) *FilterTextSearchRecords { f.FilterMaker.Col(`u."email"`, op, val) return f } func (f *FilterTextSearchRecords) FullName(op string, val string) *FilterTextSearchRecords { f.FilterMaker.Col(`u."full_name"`, op, val) return f } func (f *FilterTextSearchRecords) CreatedAt(op string, val time.Time) *FilterTextSearchRecords { f.FilterMaker.Col(`u."created_at"`, op, val) return f } func (f *FilterTextSearchRecords) And(nest func(*FilterTextSearchRecords)) *FilterTextSearchRecords { if nest == nil { f.FilterMaker.And(nil) return f } f.FilterMaker.And(func() { nest(f) }) return f } func (f *FilterTextSearchRecords) Or(nest func(*FilterTextSearchRecords)) *FilterTextSearchRecords { if nest == nil { f.FilterMaker.Or(nil) return f } f.FilterMaker.Or(func() { nest(f) }) return f }
package main import ( "fmt" "log" "os" "os/exec" ) type makeVM struct { RHOSTemplate string datacenter string datastore string vmName string folder string memory int cpu int disksize int mac string ignitionbase64 string } func (mv *makeVM) createVM() { cloneVM := fmt.Sprintf(`govc vm.clone -vm %s -annotation=%s -c=%d -m=%d -net="VM Network" -net.address="%s" -on=false -folder=%s -ds=%s %s`, mv.RHOSTemplate, mv.vmName, mv.cpu, mv.memory, mv.mac, mv.folder, mv.datastore, mv.vmName) cmd := exec.Command("bash", "-c", cloneVM) cmd.Stderr = os.Stderr cmd.Stdin = os.Stdin cmd.Stdout = os.Stdout err := cmd.Start() if err != nil { log.Fatal("Start returned: %v\n", err) } err = cmd.Wait() if err != nil { log.Fatal("Wait returned: %v\n", err) } enableUUID := fmt.Sprintf(`govc vm.change -e="disk.enableUUID=1" -vm="/%s/vm/%s/%s"`, mv.datacenter,mv.folder, mv.vmName) guestigninfochange := fmt.Sprintf(`govc vm.change -e="guestinfo.ignition.config.data=changeme" -vm="/%s/vm/%s/%s"`, mv.datacenter, mv.folder, mv.vmName) guestignencoding := fmt.Sprintf(`govc vm.change -e="guestinfo.ignition.config.data.encoding=base64" -vm="/%s/vm/%s/%s"`, mv.datacenter, mv.folder, mv.vmName) vmchange := fmt.Sprintf(`govc vm.change -e="guestinfo.ignition.config.data=%s" -vm=%s`, mv.ignitionbase64, mv.vmName) diskchange := fmt.Sprintf(`govc vm.disk.change -vm %s -size %dG`, mv.vmName, mv.disksize) for _, v := range []string{enableUUID, guestigninfochange, guestignencoding, vmchange, diskchange} { cmd = exec.Command("bash", "-c", v) err := cmd.Run() if err != nil { fmt.Println(err) } } } func (mv *makeVM) powerONVM() { vmon := fmt.Sprintf(`govc vm.power -on %s`, mv.vmName) cmd := exec.Command("/bin/bash", "-c", vmon) err := cmd.Run() if err != nil { fmt.Println(err) } } func (mv *makeVM) powerOffVM() { vmoff := fmt.Sprintf(`govc vm.power -off -force %s`, mv.vmName) cmd := exec.Command("/bin/bash", "-c", vmoff) err := cmd.Run() if err != nil { fmt.Println(err) } } func (mv *makeVM) rebootVM() { rbvm := fmt.Sprintf(`govc vm.power -r %s`, mv.vmName) cmd := exec.Command("/bin/bash", "-c", rbvm) err := cmd.Run() if err != nil { fmt.Println(err) } } func (mv *makeVM) destroyVM() { destroyvm := fmt.Sprintf(`govc vm.destroy %s`, mv.vmName) fmt.Println(destroyvm) cmd := exec.Command("/bin/bash", "-c", destroyvm) cmd.Stderr = os.Stderr cmd.Stdin = os.Stdin cmd.Stdout = os.Stdout err := cmd.Start() if err != nil { fmt.Printf("Start returned: %v\n", err) } err = cmd.Wait() if err != nil { fmt.Printf("Wait returned: %v\n", err) } }
package main import "fmt" func main() { x, y := 10, 20 a := [...]*int{ &x, &y, } p := &a fmt.Printf("%T, %v\n", a, a) fmt.Printf("%T, %v\n", p, p) }
package main import ( "flag" "fmt" log "github.com/Sirupsen/logrus" "github.com/gorilla/mux" "github.com/k0kubun/pp" "github.com/satori/go.uuid" "io" "net" "net/http" "os" "reflect" "strconv" "strings" "sync" "time" ) var ( config *Config tokens *Tokens failedIP *FailedIP ) func init() { tokenAllowedFrom, _ := ParseNetworks("127.0.0.0/8,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16") config = &Config{ FargoAddr: "0.0.0.0:1236", FargoUser: "fargo", FargoPassword: "fargo", StoreDirectory: "/tmp", TokenAllowedFrom: tokenAllowedFrom, TokenTTL: 300, FileTTL: 600, } tokens = &Tokens{token: make(map[string]*Token)} failedIP = &FailedIP{ip: make(map[string]time.Time)} } type Config struct { FargoAddr string FargoUser string FargoPassword string StoreDirectory string TokenAllowedFrom []*net.IPNet TokenTTL int64 //sec FileTTL int64 //sec sync.Mutex } type Token struct { ID string //UUIDv4 Filename string CreatedAt time.Time PushdAt time.Time } type Tokens struct { token map[string]*Token //Key: Token.ID, Value: Token sync.Mutex } type FailedIP struct { ip map[string]time.Time sync.Mutex } func helpHandler(w http.ResponseWriter, r *http.Request) { var body []string body = append(body, fmt.Sprintf("1. curl --user fargo:fargo http://%s/token", config.FargoAddr)) body = append(body, fmt.Sprintf("2. curl -F file=@somefile http://%s/push/<TOKEN>", config.FargoAddr)) body = append(body, fmt.Sprintf("3. curl http://%s/get/<TOKEN>", config.FargoAddr)) w.WriteHeader(200) w.Write([]byte(strings.Join(body, "\n"))) } func tokenHandler(w http.ResponseWriter, r *http.Request) { // maybe TODO, think about X-Forwarded-For tcpAddr, _ := net.ResolveTCPAddr("tcp", r.RemoteAddr) allowed := false for _, cidr := range config.TokenAllowedFrom { if cidr.Contains(tcpAddr.IP) { allowed = true } } if !allowed { log.Info("token access not allowed from ", tcpAddr.IP) w.WriteHeader(403) w.Write([]byte("[ERROR] 403 Forbidden")) return } username, password, ok := r.BasicAuth() if !(username == config.FargoUser && password == config.FargoPassword && ok) { log.Info("token access not allowed with user \"", username, "\"") w.WriteHeader(401) w.Write([]byte("[ERROR] 401 Unauthorized")) return } var newToken string duplicated := true for duplicated { newToken = uuid.NewV4().String() tokens.Lock() if _, exist := tokens.token[newToken]; !exist { tokens.token[newToken] = &Token{ID: newToken, CreatedAt: time.Now()} duplicated = false } tokens.Unlock() } pushURL := fmt.Sprintf("curl -F file=@somefile http://%s/push/%s", config.FargoAddr, newToken) w.Write([]byte(pushURL)) } func pushHandler(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) token := vars["token"] log.Debug(token) log.Debug(tokens.token) if _, exist := tokens.token[token]; !exist { log.Warn("token not found.", token) w.WriteHeader(404) w.Write([]byte("[ERROR] 404 Not Found")) return } if tokens.token[token].CreatedAt.Add(time.Duration(config.TokenTTL) * time.Second).Before(time.Now()) { log.Warn("token expired.", token) log.Debug("token:", tokens.token[token]) log.Debug("expired at:", tokens.token[token].CreatedAt.Add(time.Duration(config.TokenTTL)*time.Second)) w.WriteHeader(403) w.Write([]byte("[ERROR] 403 Forbidden")) return } file, header, err := r.FormFile("file") if err != nil { log.Error(err) w.WriteHeader(500) w.Write([]byte("[ERROR] 500 Internal Server Error")) return } defer file.Close() tmpfile := reflect.ValueOf(header).Elem().FieldByName("tmpfile").String() filepath := StoreFilePath(token) if tmpfile == "" { out, err := os.Create(filepath) if err != nil { log.Error(err) w.WriteHeader(500) w.Write([]byte("[ERROR] 500 Internal Server Error")) return } defer out.Close() _, err = io.Copy(out, file) if err != nil { log.Error(err) w.WriteHeader(500) w.Write([]byte("[ERROR] 500 Internal Server Error")) return } } else { err = os.Rename(tmpfile, filepath) if err != nil { log.Error(err) w.WriteHeader(500) w.Write([]byte("[ERROR] 500 Internal Server Error")) return } } tokens.token[token].Filename = header.Filename tokens.token[token].PushdAt = time.Now() getURL := fmt.Sprintf("curl -o somefile http://%s/get/%s", config.FargoAddr, token) w.WriteHeader(200) w.Write([]byte(getURL)) } func getHandler(w http.ResponseWriter, r *http.Request) { tcpaddr, _ := net.ResolveTCPAddr("tcp", r.RemoteAddr) addr := tcpaddr.IP.String() if val, exist := failedIP.ip[addr]; exist { if val.Add(30 * time.Second).After(time.Now()) { log.Warn("access denied for failed IP.") w.WriteHeader(403) w.Write([]byte("[ERROR] 403 Forbidden")) return } } vars := mux.Vars(r) token := vars["token"] if _, exist := tokens.token[token]; !exist { log.Warn("token not found.", token) failedIP.Lock() failedIP.ip[addr] = time.Now() failedIP.Unlock() log.Debug("failedIP:", failedIP) w.WriteHeader(404) w.Write([]byte("[ERROR] 404 Not Found")) return } if tokens.token[token].CreatedAt.Add(time.Duration(config.TokenTTL) * time.Second).Before(time.Now()) { log.Warn("token expired.", token) failedIP.Lock() failedIP.ip[addr] = time.Now() failedIP.Unlock() w.WriteHeader(403) w.Write([]byte("[ERROR] 403 Forbidden")) return } failedIP.Lock() delete(failedIP.ip, addr) failedIP.Unlock() filepath := StoreFilePath(token) contentDescription := fmt.Sprintf("attachment; filename=\"%s\"", tokens.token[token].Filename) w.Header().Add("Content-Disposition", contentDescription) w.Header().Set("Content-Type", "application/octet-stream") http.ServeFile(w, r, filepath) } func fileGC() { for { for k := range tokens.token { if tokens.token[k].PushdAt.After(tokens.token[k].CreatedAt) && tokens.token[k].PushdAt.Add(time.Duration(config.FileTTL)*time.Second).Before(time.Now()) { log.Debug("file gc: clean up ", k) filepath := StoreFilePath(k) if err := os.Remove(filepath); err != nil { log.Error("failed to remove file. ", err) } tokens.Lock() delete(tokens.token, k) tokens.Unlock() } } time.Sleep(10 * time.Second) } } func StoreFilePath(token string) string { filepath := fmt.Sprintf("%s%c%s", config.StoreDirectory, os.PathSeparator, token) return filepath } func ParseNetworks(description string) ([]*net.IPNet, error) { var networks []*net.IPNet for _, cidr := range strings.Split(description, ",") { _, network, err := net.ParseCIDR(cidr) if err != nil { log.Fatal(err) return nil, err } networks = append(networks, network) } return networks, nil } func main() { var err error log.SetOutput(os.Stderr) log.SetLevel(log.InfoLevel) var debug bool flag.BoolVar(&debug, "d", false, "debug logging (default: false)") flag.Parse() if debug { log.SetLevel(log.DebugLevel) } config.Lock() if envFargoAddr := os.Getenv("FARGO_ADDR"); envFargoAddr != "" { config.FargoAddr = envFargoAddr } if envFargoUser := os.Getenv("FARGO_USER"); envFargoUser != "" { config.FargoUser = envFargoUser } if envFargoPassword := os.Getenv("FARGO_PASSWORD"); envFargoPassword != "" { config.FargoPassword = envFargoPassword } if envTokenAllowedFrom := os.Getenv("TOKEN_ALLOWED_FROM"); envTokenAllowedFrom != "" { networks, err := ParseNetworks(envTokenAllowedFrom) if err != nil { log.Fatal(err) os.Exit(1) } config.TokenAllowedFrom = networks } if envFileTTL, err := strconv.ParseInt(os.Getenv("FILE_TTL"), 10, 64); err == nil && envFileTTL != 0 { config.FileTTL = envFileTTL } if envStoreDirectory := os.Getenv("STORE_DIR"); envStoreDirectory != "" { if _, err := os.Stat(envStoreDirectory); err != nil { err := os.Mkdir(envStoreDirectory, 0777) if err != nil { log.Fatal("cannot create ", envStoreDirectory, " : ", err) os.Exit(1) } } config.StoreDirectory = envStoreDirectory } if envTokenTTL, err := strconv.ParseInt(os.Getenv("TOKEN_TTL"), 10, 64); err == nil && envTokenTTL != 0 { config.TokenTTL = envTokenTTL } config.Unlock() log.Debug("config: ", pp.Sprint(config)) r := mux.NewRouter() r.HandleFunc("/token/", tokenHandler).Methods("GET") r.HandleFunc("/token", tokenHandler).Methods("GET") r.HandleFunc("/push/{token}", pushHandler).Methods("POST") r.HandleFunc("/get/{token}", getHandler).Methods("GET") r.HandleFunc("/help/", helpHandler).Methods("GET") r.HandleFunc("/help", helpHandler).Methods("GET") r.HandleFunc("/", helpHandler).Methods("GET") http.Handle("/", r) go fileGC() log.Debug("http server started") err = http.ListenAndServe(config.FargoAddr, nil) if err != nil { log.Error(err) } }
package orm import ( "database/sql" "gorm.io/driver/mysql" "gorm.io/gorm" "time" ) var db *gorm.DB var err error var sqlDB *sql.DB func init() { dsn := "aitifen:aitifen@tcp(10.16.4.250:3310)/gsvip_crm?charset=utf8mb4&parseTime=True&loc=Local" db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{}) sqlDB, err = db.DB() // SetMaxIdleConns 设置空闲连接池中连接的最大数量 sqlDB.SetMaxIdleConns(10) // SetMaxOpenConns 设置打开数据库连接的最大数量。 sqlDB.SetMaxOpenConns(100) // SetConnMaxLifetime 设置了连接可复用的最大时间。 sqlDB.SetConnMaxLifetime(time.Hour) }
package main const sizeOfSlice = 1000000 const pi float64 = 3.141592653589793238462643 const eulerNum float64 = 2.718281828459045235360287 const bigFloat float64 = 10987654321.123456789 func fpBenchmark(i int) { multiples := make([]float64, sizeOfSlice) results := make([]float64, sizeOfSlice) // initializes slice with a random floating point number that is the result of a floating point operation for i := 0; i < sizeOfSlice; i++ { multiples[i] = pi * (bigFloat * pi) * (eulerNum * eulerNum) } // multiplies number by big floating point numbers for i := 0; i < sizeOfSlice; i++ { results[i] = multiples[i] * bigFloat * pi * eulerNum } // division of floating point numbers for i := 0; i < sizeOfSlice; i++ { results[i] = (results[i]) / ((pi * bigFloat) * (eulerNum / ((bigFloat * pi * pi) / eulerNum))) } waitGroup.Done() } // RunFpBenchmark runs the Floating Point algorithms func RunFpBenchmark(amountOfThreads int) { // fmt.Println("Floating point tests starting...") // start := time.Now() waitGroup.Add(amountOfThreads) for i := 0; i < amountOfThreads; i++ { go fpBenchmark(i) } waitGroup.Wait() // timeOfExecution := time.Since(start) // fmt.Println("Floating point benchmarks done in: ", timeOfExecution) }
package filter import ( "fmt" "strings" "fxkt.tech/bj21/internal/pkg/ffmpeg/math" ) type Stream string const ( StreamAudio Stream = "a" StreamVideo Stream = "v" ) func SelectStream(idx int, s Stream, must bool) string { var qm string if !must { qm = "?" } return fmt.Sprintf("%d:%s%s", idx, s, qm) } type LogoPos string const ( LogoTopLeft LogoPos = "TopLeft" LogoTopRight LogoPos = "TopRight" LogoBottomRight LogoPos = "BottomRight" LogoBottomLeft LogoPos = "BottomLeft" ) func Logo(dx, dy int64, pos LogoPos) string { switch pos { case LogoTopLeft: return fmt.Sprintf("overlay=%d:y=%d", dx, dy) case LogoTopRight: return fmt.Sprintf("overlay=W-w-%d:y=%d", dx, dy) case LogoBottomRight: return fmt.Sprintf("overlay=W-w-%d:y=H-h-%d", dx, dy) case LogoBottomLeft: return fmt.Sprintf("overlay=%d:y=H-h-%d", dx, dy) } return "" } // func Overlay(x, y int64, eofaction string) string { // } func Scale(w, h int64) string { return fmt.Sprintf("scale=%d:%d", math.CeilOdd(w), math.CeilOdd(h), ) } func Split(n int) string { return fmt.Sprintf("split=%d", n) } func Trim(s, e int64) string { var ps []string if s != 0 { ps = append(ps, fmt.Sprintf("start=%d", s)) } if e != 0 { ps = append(ps, fmt.Sprintf("end=%d", e)) } var eqs string var psstr string = strings.Join(ps, ":") if psstr != "" { eqs = "=" } return fmt.Sprintf("trim%s%s", eqs, psstr) } func Delogo(x, y, w, h int64) string { return fmt.Sprintf("delogo=%d:%d:%d:%d", x+1, y+1, w-2, h-2, ) }
package main import ( "log" "net/http" "github.com/gorilla/mux" mgo "gopkg.in/mgo.v2" ) func main() { session, err := mgo.Dial("localhost") if err != nil { panic(err) } defer session.Close() session.SetMode(mgo.Monotonic, true) database := session.DB("golang") controller := NewController(database) router := mux.NewRouter() router.HandleFunc("/v1/posts", controller.CreatePost).Methods("POST") router.HandleFunc("/v1/posts/{id}", controller.GetPost).Methods("GET") log.Fatal(http.ListenAndServe(":8080", router)) }
package plik import ( "crypto/tls" "encoding/json" "io" "net/http" "runtime" "github.com/root-gg/plik/server/common" ) // Client manage the process of communicating with a Plik server via the HTTP API type Client struct { *UploadParams // Default upload params for the Client. Those can be overridden per upload Debug bool // Display HTTP request and response and other helpful debug data URL string // URL of the Plik server ClientName string // X-ClientApp HTTP Header setting ClientVersion string // X-ClientVersion HTTP Header setting ClientUserAgent string // User-Agent HTTP Header setting HTTPClient *http.Client // HTTP Client ot use to make the requests } // NewClient creates a new Plik Client func NewClient(url string) (c *Client) { c = &Client{} // Default upload params c.UploadParams = &UploadParams{} c.URL = url // Default values for X-ClientApp and X-ClientVersion HTTP Headers c.ClientName = "plik_client" c.ClientVersion = runtime.GOOS + "-" + runtime.GOARCH + "-" + common.GetBuildInfo().Version c.ClientUserAgent = c.ClientName + "/" + common.GetBuildInfo().Version c.HTTPClient = NewHTTPClient(false) return c } // Insecure mode does not verify the server's certificate chain and host name func (c *Client) Insecure() { c.HTTPClient = NewHTTPClient(true) } // NewUpload create a new Upload object with the client default upload params func (c *Client) NewUpload() *Upload { return newUpload(c) } // UploadFile is a handy wrapper to upload a file from the filesystem func (c *Client) UploadFile(path string) (upload *Upload, file *File, err error) { upload = c.NewUpload() file, err = upload.AddFileFromPath(path) if err != nil { return nil, nil, err } // Create upload and upload the file err = upload.Upload() if err != nil { // Return the upload and file to get a chance to get the file error return upload, file, err } return upload, file, nil } // UploadReader is a handy wrapper to upload a single arbitrary data stream func (c *Client) UploadReader(name string, reader io.Reader) (upload *Upload, file *File, err error) { upload = c.NewUpload() file = upload.AddFileFromReader(name, reader) // Create upload and upload the file err = upload.Upload() if err != nil { // Return the upload and file to get a chance to get the file error return upload, file, err } return upload, file, nil } // GetServerVersion return the remote server version func (c *Client) GetServerVersion() (bi *common.BuildInfo, err error) { var req *http.Request req, err = http.NewRequest("GET", c.URL+"/version", nil) if err != nil { return nil, err } resp, err := c.MakeRequest(req) if err != nil { return nil, err } defer func() { _ = resp.Body.Close() }() body, err := io.ReadAll(resp.Body) if err != nil { return nil, err } // Parse json response bi = &common.BuildInfo{} err = json.Unmarshal(body, bi) if err != nil { return nil, err } return bi, nil } // GetServerConfig return the remote server configuration func (c *Client) GetServerConfig() (config *common.Configuration, err error) { var req *http.Request req, err = http.NewRequest("GET", c.URL+"/config", nil) if err != nil { return nil, err } resp, err := c.MakeRequest(req) if err != nil { return nil, err } defer func() { _ = resp.Body.Close() }() body, err := io.ReadAll(resp.Body) if err != nil { return nil, err } // Parse json response config = &common.Configuration{} err = json.Unmarshal(body, config) if err != nil { return nil, err } return config, nil } // GetUpload fetch upload metadata from the server func (c *Client) GetUpload(id string) (upload *Upload, err error) { return c.GetUploadProtectedByPassword(id, c.Login, c.Password) } // GetUploadProtectedByPassword fetch upload metadata from the server with login and password func (c *Client) GetUploadProtectedByPassword(id string, login string, password string) (upload *Upload, err error) { uploadParams := c.NewUpload().getParams() uploadParams.ID = id uploadParams.Login = login uploadParams.Password = password upload, err = c.getUploadWithParams(uploadParams) if err != nil { return nil, err } upload.Login = login upload.Password = password return upload, nil } // NewHTTPClient Create a new HTTP client with ProxyFromEnvironment and InsecureSkipVerify setup func NewHTTPClient(insecure bool) *http.Client { return &http.Client{ Transport: &http.Transport{ Proxy: http.ProxyFromEnvironment, TLSClientConfig: &tls.Config{InsecureSkipVerify: insecure}, }, } }
package cmd import ( "github.com/steviebps/realm/utils" ) type RealmConfig struct { Client ClientConfig `json:"client,omitempty"` Server ServerConfig `json:"server,omitempty"` } type ServerConfig struct { StorageType string `json:"storage"` StorageOptions map[string]string `json:"options"` Port string `json:"port"` CertFile string `json:"certFile"` KeyFile string `json:"keyFile"` LogLevel string `json:"logLevel"` Inheritable bool `json:"inheritable"` } type ClientConfig struct { Address string `json:"address"` } func parseConfig(path string) (RealmConfig, error) { var config RealmConfig file, err := utils.OpenFile(path) if err != nil { return config, err } defer file.Close() err = utils.ReadInterfaceWith(file, &config) return config, err }
package base const ( // The username of the special "GUEST" user GuestUsername = "GUEST" ISO8601Format = "2006-01-02T15:04:05.000Z07:00" //kTestURL = "http://localhost:8091" kTestURL = "walrus:" ) func UnitTestUrl() string { return kTestURL }
package v040_test import ( "encoding/json" "fmt" "testing" "github.com/stretchr/testify/require" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/legacy/v039" v039 "github.com/provenance-io/provenance/x/marker/legacy/v039" v040 "github.com/provenance-io/provenance/x/marker/legacy/v040" ) func TestMigrate(t *testing.T) { encodingConfig := simapp.MakeTestEncodingConfig() clientCtx := client.Context{}. WithInterfaceRegistry(encodingConfig.InterfaceRegistry). WithTxConfig(encodingConfig.TxConfig). WithLegacyAmino(encodingConfig.Amino). WithJSONMarshaler(encodingConfig.Marshaler) addr1, err := sdk.AccAddressFromBech32("cosmos16xyempempp92x9hyzz9wrgf94r6j9h5f06pxxv") require.NoError(t, err) gs := v039.GenesisState{ Markers: []v039.MarkerAccount{ { BaseAccount: &authtypes.BaseAccount{ Address: addr1, Coins: sdk.NewCoins(sdk.NewCoin("test", sdk.OneInt())), AccountNumber: 5, Sequence: 4, }, Manager: addr1, Status: v039.MustGetMarkerStatus("active"), Denom: "hotdog", Supply: sdk.OneInt(), MarkerType: "COIN", AccessControls: []v039.AccessGrant{{Address: addr1, Permissions: []string{"mint", "burn", "grant"}}}, }, }, } migrated := v040.Migrate(gs) expected := fmt.Sprintf(`{ "markers": [ { "access_control": [ { "address": "%s", "permissions": [ "ACCESS_MINT", "ACCESS_BURN", "ACCESS_ADMIN" ] } ], "allow_governance_control": false, "base_account": { "account_number": "5", "address": "%s", "pub_key": null, "sequence": "4" }, "denom": "hotdog", "manager": "%s", "marker_type": "MARKER_TYPE_COIN", "status": "MARKER_STATUS_ACTIVE", "supply": "1", "supply_fixed": false } ], "params": { "enable_governance": true, "max_total_supply": "100000000000", "unrestricted_denom_regex": "[a-zA-Z][a-zA-Z0-9/]{2,64}" } }`, addr1.String(), addr1.String(), addr1.String()) bz, err := clientCtx.JSONMarshaler.MarshalJSON(migrated) require.NoError(t, err) // Indent the JSON bz correctly. var jsonObj map[string]interface{} err = json.Unmarshal(bz, &jsonObj) require.NoError(t, err) indentedBz, err := json.MarshalIndent(jsonObj, "", " ") require.NoError(t, err) require.Equal(t, expected, string(indentedBz)) }
package maintChain import ( sdk "github.com/cosmos/cosmos-sdk/types" "time" ) // Record is a struct that contains all the metadata of a maintenance record type Record struct { Id string `json:"id"` Time time.Time `json:"time"` Vin sdk.AccAddress `json:"vin"` Org sdk.AccAddress `json:"organization"` Content string `json:"content"` }
package main import "fmt" const ( a11 = 454 b11 string = "b11" ) const ( x = 2017 + iota y = 2017 + iota z = 2017 + iota ) func main() { a := 42 fmt.Printf("%d\t%b\t#x", a, a, a) b := (42 >= 45) fmt.Println(b) fmt.Println(a11) fmt.Println(b11) fmt.Println(x) fmt.Println(y) }
package token import ( "camp/lib" "camp/week2/api" "time" ) func (t *TokenModel) Add(user *api.User) (token string, err error) { c := t.GetC() defer c.Database.Session.Close() now := time.Now() str := now.String() + "-+-" + user.Password token = lib.HashSha256(str) aHour, _ := time.ParseDuration("24h") timeOut := now.Add(aHour) tokenObj := api.Token{user.Id, token, timeOut.Unix()} return token, c.Insert(tokenObj) }
package user import ( "camp/lib" "camp/week2/api" "camp/week2/service" "encoding/json" "github.com/simplejia/clog/api" "net/http" ) type LoginReq struct { Email string `json:"email"` Password string `json:"password"` } func (l *LoginReq) Register() (ok bool) { if l == nil || l.Email == "" || l.Password == "" { return true } return } type LoginRes struct { Token string `json:"token"` } // @prefilter("Cors") // @postfilter("Boss") func (userController *User) Login(w http.ResponseWriter, r *http.Request) { fun := "week2.userController.Login" var loginReq *LoginReq if err := json.Unmarshal(userController.ReadBody(r), &loginReq); err != nil || loginReq.Register() { clog.Error("%s param err: %v, req: %v", fun, err, loginReq) userController.ReplyFail(w, lib.CodePara) return } userApi := api.NewUser() userApi.Email = loginReq.Email token, err := service.NewUserService().Login(userApi, loginReq.Password) if err != nil { clog.Error("%s param err: %v, req: %v", fun, err, loginReq) userController.ReplyFailWithDetail(w, lib.CodePara, err.Error()) return } resp := &LoginRes{token} userController.ReplyOk(w, resp) }
package ssh import ( "testing" ) func TestSsh(t *testing.T) { addr := "x3.tc" alive := Ssh(addr, 50) t.Log("[%v]:[%v]\n", addr, alive) }
package main import ( "bufio" "fmt" "os" "strconv" ) func main() { reader := bufio.NewReaderSize(os.Stdin, 100009) l, _, _ := reader.ReadLine() t, _ := strconv.Atoi(string(l)) for ; t > 0; t-- { s, _, _ := reader.ReadLine() removed := -1 for i := 0; i < len(s)/2; i++ { a := s[i] b := s[len(s)-1-i] if a == b { continue } else { if checker(s, i) { removed = i } else { removed = len(s) - 1 - i } break } } fmt.Println(removed) } } func checker(s []byte, skip int) bool { off := 0 for i := 0; i < len(s)/2; i++ { if i == skip { off = 1 continue } a := s[i] b := s[len(s)-1-i+off] if a == b { continue } else { return false } } return true }
// Copyright (c) 2018 Palantir Technologies. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable 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 witchcraft_test import ( "bytes" "context" "encoding/json" "testing" "github.com/palantir/witchcraft-go-error" "github.com/palantir/witchcraft-go-logging/conjure/witchcraft/api/logging" "github.com/palantir/witchcraft-go-server/config" "github.com/palantir/witchcraft-go-server/witchcraft" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) // TestFatalErrorLogging verifies that the server logs errors and panics before returning. func TestFatalErrorLogging(t *testing.T) { for _, test := range []struct { Name string InitFn witchcraft.InitFunc VerifyLog func(t *testing.T, logOutput []byte) }{ { Name: "error returned by init function", InitFn: func(ctx context.Context, info witchcraft.InitInfo) (cleanup func(), rErr error) { return nil, werror.Error("oops", werror.SafeParam("k", "v")) }, VerifyLog: func(t *testing.T, logOutput []byte) { var log logging.ServiceLogV1 require.NoError(t, json.Unmarshal(logOutput, &log)) assert.Equal(t, logging.LogLevelError, log.Level) assert.Equal(t, "oops", log.Message) assert.Equal(t, "v", log.Params["k"], "safe param not preserved") assert.NotEmpty(t, log.Stacktrace) }, }, { Name: "panic init function with error", InitFn: func(ctx context.Context, info witchcraft.InitInfo) (cleanup func(), rErr error) { panic(werror.Error("oops", werror.SafeParam("k", "v"))) }, VerifyLog: func(t *testing.T, logOutput []byte) { var log logging.ServiceLogV1 require.NoError(t, json.Unmarshal(logOutput, &log)) assert.Equal(t, logging.LogLevelError, log.Level) assert.Equal(t, "panic recovered", log.Message) assert.Equal(t, "v", log.Params["k"], "safe param not preserved") assert.NotEmpty(t, log.Stacktrace) }, }, { Name: "panic init function with object", InitFn: func(ctx context.Context, info witchcraft.InitInfo) (cleanup func(), rErr error) { panic(map[string]interface{}{"k": "v"}) }, VerifyLog: func(t *testing.T, logOutput []byte) { var log logging.ServiceLogV1 require.NoError(t, json.Unmarshal(logOutput, &log)) assert.Equal(t, logging.LogLevelError, log.Level) assert.Equal(t, "panic recovered", log.Message) assert.Equal(t, map[string]interface{}{"k": "v"}, log.UnsafeParams["recovered"]) assert.NotEmpty(t, log.Stacktrace) }, }, } { t.Run(test.Name, func(t *testing.T) { logOutputBuffer := &bytes.Buffer{} err := witchcraft.NewServer(). WithInitFunc(test.InitFn). WithInstallConfig(config.Install{UseConsoleLog: true}). WithRuntimeConfig(config.Runtime{}). WithLoggerStdoutWriter(logOutputBuffer). WithECVKeyProvider(witchcraft.ECVKeyNoOp()). WithDisableGoRuntimeMetrics(). WithSelfSignedCertificate(). Start() require.Error(t, err) test.VerifyLog(t, logOutputBuffer.Bytes()) }) } }
package interfaces import ( "github.com/georgerapeanu/CP-Crawlers/generic" "time" "errors" ) type GenericCrawler interface { GetSubmissions(handle string, beginTime time.Time, //the begin time point endTime time.Time) ([]generic.Submission,err error) // the end time point GetSubmissionsForTask(handle string, //handle of the user taskLink string, //link to the task beginTime time.Time, //the begin time point endTime time.Time) ([]generic.Submission,err error) // the end time point ParseSubmission(submissionLink string) (generic.Submission,err error) }
package main import ( "devbook-api/src/config" "devbook-api/src/router" "fmt" "log" "net/http" ) func init() { // loads values from .env into the system config.Load() } func main() { fmt.Printf("Running api in %d\n", config.ApiPort) r := router.Generate() log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", config.ApiPort), r)) }
package clients import ( "net/url" ) func UrlBasePath(u *url.URL) string { return u.Scheme + "://" + u.Host + "/" }
// Copyright 2019 John Papandriopoulos. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. package zydis /* #cgo CFLAGS: -I./lib/include #include <Zydis/Zydis.h> #include <stdlib.h> #define __paster2(a, b) a ## b #define __evaluator2(a, b) __paster2(a, b) const ZyanStatus statusOK = ZYAN_STATUS_SUCCESS; const ZyanStatus statusSkipToken = ZYDIS_STATUS_SKIP_TOKEN; const ZyanStatus statusCallbackFailure = ZYAN_MAKE_STATUS(1, ZYAN_MODULE_ZYDIS, 0x0B); // Ugh, the Zydis callback structure doesn't pass the ZydisFormatterFunction to // the callback: they've assumed that each function pointer is "hard wired" to // each formatter function... so we have to make one of each to discern between // them. // Go callbacks. extern ZyanStatus formatterXCallback(ZydisFormatterFunction, ZydisFormatterBuffer*, ZydisFormatterContext*); extern ZyanStatus formatterRegisterCallback(ZydisFormatterFunction, ZydisFormatterBuffer*, ZydisFormatterContext*, ZydisRegister); extern ZyanStatus formatterDecoratorCallback(ZydisFormatterFunction, ZydisFormatterBuffer*, ZydisFormatterContext*, ZydisDecorator); // C callbacks that forward to the above Go callbacks. #define CALLBACK_X(__name, __type) \ ZyanStatus __evaluator2(_hookXCallback, __name)( \ const ZydisFormatter* formatter, \ ZydisFormatterBuffer* buffer, \ ZydisFormatterContext* context \ ) { \ return formatterXCallback(__type, buffer, context); \ } \ typedef void *__evaluator2(_eatSemiColon, __name) CALLBACK_X(FormatterFunctionPreInstruction, ZYDIS_FORMATTER_FUNC_PRE_INSTRUCTION); CALLBACK_X(FormatterFunctionPostInstruction, ZYDIS_FORMATTER_FUNC_POST_INSTRUCTION); CALLBACK_X(FormatterFunctionFormatInstruction, ZYDIS_FORMATTER_FUNC_FORMAT_INSTRUCTION); CALLBACK_X(FormatterFunctionFormatPreOperand, ZYDIS_FORMATTER_FUNC_PRE_OPERAND); CALLBACK_X(FormatterFunctionFormatPostOperand, ZYDIS_FORMATTER_FUNC_POST_OPERAND); CALLBACK_X(FormatterFunctionFormatFormatOperandRegister, ZYDIS_FORMATTER_FUNC_FORMAT_OPERAND_REG); CALLBACK_X(FormatterFunctionFormatFormatOperandMemory, ZYDIS_FORMATTER_FUNC_FORMAT_OPERAND_MEM); CALLBACK_X(FormatterFunctionFormatFormatOperandPointer, ZYDIS_FORMATTER_FUNC_FORMAT_OPERAND_PTR); CALLBACK_X(FormatterFunctionFormatFormatOperandImmediate, ZYDIS_FORMATTER_FUNC_FORMAT_OPERAND_IMM); CALLBACK_X(FormatterFunctionPrintMnemonic, ZYDIS_FORMATTER_FUNC_PRINT_MNEMONIC); CALLBACK_X(FormatterFunctionPrintAddressAbsolute, ZYDIS_FORMATTER_FUNC_PRINT_ADDRESS_ABS); CALLBACK_X(FormatterFunctionPrintAddressRelative, ZYDIS_FORMATTER_FUNC_PRINT_ADDRESS_REL); CALLBACK_X(FormatterFunctionPrintAddressDisplacement, ZYDIS_FORMATTER_FUNC_PRINT_DISP); CALLBACK_X(FormatterFunctionPrintAddressImmediate, ZYDIS_FORMATTER_FUNC_PRINT_IMM); CALLBACK_X(FormatterFunctionPrintTypecast, ZYDIS_FORMATTER_FUNC_PRINT_TYPECAST); CALLBACK_X(FormatterFunctionPrintSegment, ZYDIS_FORMATTER_FUNC_PRINT_SEGMENT); CALLBACK_X(FormatterFunctionPrintPrefixes, ZYDIS_FORMATTER_FUNC_PRINT_PREFIXES); ZyanStatus _hookRegisterCallbackFormatterFunctionPrintRegister( const ZydisFormatter* formatter, ZydisFormatterBuffer* zbuffer, ZydisFormatterContext* zcontext, ZydisRegister zreg ) { return formatterRegisterCallback(ZYDIS_FORMATTER_FUNC_PRINT_REGISTER, zbuffer, zcontext, zreg); } ZyanStatus _hookDecoratorCallbackFormatterFunctionPrintDecorator( const ZydisFormatter* formatter, ZydisFormatterBuffer* zbuffer, ZydisFormatterContext* zcontext, ZydisDecorator zdecorator ) { return formatterDecoratorCallback(ZYDIS_FORMATTER_FUNC_PRINT_DECORATOR, zbuffer, zcontext, zdecorator); } // Without these wrappers, cgo thinks we're passing Go pointers to C, when // using the ZydisFormatterTokenConst* token values. ZyanStatus __ZydisFormatterTokenizeInstructionEx( const ZydisFormatter* formatter, const ZydisDecodedInstruction* instruction, void* buffer, ZyanUSize length, ZyanU64 runtime_address, ZyanUPointer* token, void* user_data ) { return ZydisFormatterTokenizeInstructionEx( formatter, instruction, buffer, length, runtime_address, (ZydisFormatterTokenConst**)token, user_data ); } ZyanStatus __ZydisFormatterTokenizeOperandEx( const ZydisFormatter* formatter, const ZydisDecodedInstruction* instruction, ZyanU8 index, void* buffer, ZyanUSize length, ZyanU64 runtime_address, ZyanUPointer* token, void* user_data ) { return ZydisFormatterTokenizeOperandEx( formatter, instruction, index, buffer, length, runtime_address, (ZydisFormatterTokenConst**)token, user_data ); } ZyanStatus __ZydisFormatterTokenGetValue(ZyanUPointer token, ZydisTokenType* type, char** value) { return ZydisFormatterTokenGetValue((const ZydisFormatterToken*)token, type, (const char **)value); } ZyanStatus __ZydisFormatterTokenNext(ZyanUPointer token, ZyanUPointer *nextToken) { const ZyanStatus ret = ZydisFormatterTokenNext((ZydisFormatterTokenConst**)&token); *nextToken = (ZyanUPointer)token; return ret; } */ import "C" import ( "fmt" "reflect" "unsafe" ) // Formatter translates decoded instructions into human-readable text. type Formatter struct { zfmtr *C.ZydisFormatter hookForType map[FormatterFunction]interface{} // FormatterFunc, FormatterRegisterFunc, FormatterDecoratorFunc } // FormatterStyle is an enum that determines the formatting style. type FormatterStyle int // FormatterStyle enum values. const ( // Generates AT&T-style disassembly. FormatterStyleATT FormatterStyle = iota // Generates Intel-style disassembly. FormatterStyleIntel // Generates MASM-style disassembly that is directly accepted as input // for the MASM assembler. FormatterStyleIntelMASM ) // NewFormatter returns a new Formatter. func NewFormatter(style FormatterStyle) (*Formatter, error) { var zfmtr C.ZydisFormatter ret := C.ZydisFormatterInit(&zfmtr, C.ZydisFormatterStyle(style)) if zyanFailure(ret) { return nil, fmt.Errorf("zydis: failed to create formatter: 0x%x", ret) } return &Formatter{ zfmtr: &zfmtr, hookForType: make(map[FormatterFunction]interface{}), }, nil } // RuntimeAddressNone should be used as value for runtimeAddress in // ZydisFormatterFormatInstruction/ZydisFormatterFormatInstructionEx or // ZydisFormatterFormatOperand/ZydisFormatterFormatOperandEx to print relative // values for all addresses. const RuntimeAddressNone = int64(-1) // Padding is an enum of padding styles. type Padding int // Padding enum values. const ( // Disables padding. PaddingDisabled Padding = 0 // Padds the value to the current stack-width for addresses, or to the // operand-width for immediate values (hexadecimal only). PAddingAuto Padding = -1 ) // Signedness is an enum to control formatting of a value's sign. type Signedness int // Signedness enun values. const ( // SignednessAuto automatically chooses the most suitable mode based on // the operand's DecodedOperand.Imm.IsSigned attribute. SignednessAuto Signedness = iota // SignednessSigned forces signed values. SignednessSigned // SignednessUnsigned forces unsigned values. SignednessUnsigned ) // FormatterProperty is an enum of formatter property keys. type FormatterProperty int const ( /* * General */ // FormatterPropertyForceSize controls the printing of effective operand-size // suffixes (AT&T) or operand-sizes of memory operands (Intel). // // Pass true as value to force the formatter to always print the size, // or false to only print it if needed. FormatterPropertyForceSize FormatterProperty = iota // FormatterPropertyForceSegment controls the printing of segment prefixes. // // Pass true as value to force the formatter to always print the segment // register of memory-operands or false to omit implicit DS/SS segments. FormatterPropertyForceSegment // FormatterPropertyForceRelativeBranches controls the printing of branch // addresses. // // Pass true as value to force the formatter to always print relative branch // addresses or false to use absolute addresses, if a runtimeAddress // different to RuntimeAddressNone was passed. FormatterPropertyForceRelativeBranches // FormatterPropertyForceRelativeRIPRel controls the printing of EIP/RIP- // relative addresses. // // Pass true as value to force the formatter to always print relative // addresses for EIP/RIP-relative operands or false to use absolute // addresses, if a runtimeAddress different to RuntimeAddressNone was passed. FormatterPropertyForceRelativeRIPRel // FormatterPropertyPrintBranchSize controls the printing of branch- // instructions sizes. // // Pass true as value to print the size (short, near) of branch // instructions or false to hide it. // // Note that the far/l modifier is always printed. FormatterPropertyPrintBranchSize // FormatterPropertyDetailedPrefixes controls the printing of instruction // prefixes. // // Pass true as value to print all instruction-prefixes (even ignored or // duplicate ones) or false to only print prefixes that are effectively // used by the instruction. FormatterPropertyDetailedPrefixes /* * Numeric values */ // FormatterPropertyAddrBase controls the base of address values. FormatterPropertyAddrBase // FormatterPropertyAddrSignedness controls the signedness of relative // addresses. Absolute addresses are always unsigned. FormatterPropertyAddrSignedness // FormatterPropertyAddrPaddingAbsolute controls the padding of absolute // address values. // // Pass PaddingDisabled to disable padding, PaddingAuto to padd all addresses // to the current stack width (hexadecimal only), or any other integer value // for custom padding. FormatterPropertyAddrPaddingAbsolute // FormatterPropertyAddrPaddingRelative controls the padding of relative // address values. // // Pass PaddingDisabled to disable padding, PaddingAuto to padd all addresses // to the current stack width (hexadecimal only), or any other integer value // for custom padding. FormatterPropertyAddrPaddingRelative // FormatterPropertyDispBase controls the base of displacement values. FormatterPropertyDispBase // FormatterPropertyDispSignedness controls the signedness of displacement // values. FormatterPropertyDispSignedness // FormatterPropertyDispPadding controls the padding of displacement values. // // Pass PaddingDisabled to disable padding, or any other integer value for // custom padding. FormatterPropertyDispPadding // FormatterPropertyImmBase controls the base of immediate values. FormatterPropertyImmBase // FormatterPropertyImmSignedness controls the signedness of immediate values. // // Pass SignednessAuto to automatically choose the most suitable mode based // on the operands DecodedOperand.Imm.IsSigned attribute. FormatterPropertyImmSignedness // FormatterPropertyImmPadding controls the padding of immediate values. // // Pass PaddingDisabled to disable padding, PaddingAuto to padd all // immediates to the operand-width (hexadecimal only), or any other integer // value for custom padding. FormatterPropertyImmPadding /* * Text formatting */ // FormatterPropertyUppercasePrefixes controls the letter-case for prefixes. // // Pass true as value to format in uppercase or false to format in lowercase. FormatterPropertyUppercasePrefixes // FormatterPropertyUppercaseMnemonic controls the letter-case for // the mnemonic. // // Pass true as value to format in uppercase or false to format in lowercase. FormatterPropertyUppercaseMnemonic // FormatterPropertyUppercaseRegisters controls the letter-case for registers. // // Pass true as value to format in uppercase or false to format in lowercase. FormatterPropertyUppercaseRegisters // FormatterPropertyUppercaseTypecasts controls the letter-case for typecasts. // // Pass true as value to format in uppercase or false to format in lowercase. FormatterPropertyUppercaseTypecasts // FormatterPropertyUppercaseDecorators controls the letter-case for // decorators. // // Pass true as value to format in uppercase or false to format in lowercase. FormatterPropertyUppercaseDecorators /* * Number formatting */ // FormatterPropertyDecPrefix controls the prefix for decimal values. // // Pass a string with a maximum length of 10 characters to set a custom // prefix, or the empty string to disable it. FormatterPropertyDecPrefix // FormatterPropertyDecSuffix controls the suffix for decimal values. // // Pass a string with a maximum length of 10 characters to set a custom // suffix, or the empty string to disable it. FormatterPropertyDecSuffix // FormatterPropertyHexUppercase controls the letter-case of hexadecimal // values. // // Pass true as value to format in uppercase and false to format in lowercase. FormatterPropertyHexUppercase // default true // FormatterPropertyHexPrefix controls the prefix for hexadecimal values. // // Pass a string with a maximum length of 10 characters to set a custom // prefix, or the empty string to disable it. FormatterPropertyHexPrefix // FormatterPropertyHexSuffix controls the suffix for hexadecimal values. // // Pass a string with a maximum length of 10 characters to set a custom // suffix, or the empty string to disable it. FormatterPropertyHexSuffix ) // SetProperty changes the value of the specified formatter property. func (fmtr *Formatter) SetProperty(property FormatterProperty, value interface{}) error { var zvalue C.ZyanUPointer v := reflect.ValueOf(value) switch v.Type().Kind() { case reflect.String: if str := v.String(); str != "" { cs := C.CString(str) defer C.free(unsafe.Pointer(cs)) zvalue = C.ZyanUPointer(uintptr(unsafe.Pointer(cs))) } else { zvalue = C.ZyanUPointer(0) // ZYAN_NULL } case reflect.Bool: if v.Bool() { zvalue = C.ZyanUPointer(1) // ZYAN_TRUE } else { zvalue = C.ZyanUPointer(0) // ZYAN_FALSE } case reflect.Int, reflect.Int64: zvalue = C.ZyanUPointer(v.Int()) case reflect.Uint, reflect.Uint64: zvalue = C.ZyanUPointer(v.Uint()) default: panic("zydis: unsupported property value type") } ret := C.ZydisFormatterSetProperty( fmtr.zfmtr, C.ZydisFormatterProperty(property), zvalue, ) if zyanFailure(ret) { return fmt.Errorf("zydis: failed to set property: 0x%x", ret) } return nil } // FormatterContext is the context used with a FormatterFunc. type FormatterContext struct { // A pointer to the `ZydisDecodedInstruction` struct. Instruction *DecodedInstruction // A pointer to the `ZydisDecodedOperand` struct. Operand *DecodedOperand // The runtime address of the instruction. RuntimeAddress uint64 } // FormatterBuffer represents a formatter buffer. type FormatterBuffer struct { // The buffer contains a token stream (true), or a simple string (false). IsTokenList bool Value string } // FormatterXFunc is a callback used with keys: // * FormatterFunctionPreInstruction // * FormatterFunctionPostInstruction // * FormatterFunctionFormatInstruction // * FormatterFunctionFormatPreOperand † // * FormatterFunctionFormatPostOperand † // * FormatterFunctionFormatFormatOperandRegister † // * FormatterFunctionFormatFormatOperandMemory † // * FormatterFunctionFormatFormatOperandPointer † // * FormatterFunctionFormatFormatOperandImmediate † // * FormatterFunctionPrintMnemonic // * FormatterFunctionPrintAddressAbsolute // * FormatterFunctionPrintAddressRelative // * FormatterFunctionPrintAddressDisplacement // * FormatterFunctionPrintAddressImmediate // * FormatterFunctionPrintTypecast // * FormatterFunctionPrintSegment // * FormatterFunctionPrintPrefixes // // For keys marked with †, returning true will instruct the formatter to omit // the whole operand. type FormatterXFunc func(fmtr *Formatter, fbuf *FormatterBuffer, context FormatterContext) (skipOperand bool, err error) // FormatterRegisterFunc is a callback used with keys: // * FormatterFunctionPrintRegister type FormatterRegisterFunc func(fmtr *Formatter, fbuf *FormatterBuffer, context FormatterContext, reg Register) error // Decorator is an enum that describes a decorator. type Decorator int // Decorator enum values const ( DecoratorInvalid Decorator = iota // The embedded-mask decorator. DecoratorMask // The broadcast decorator. DecoratorBroadcast // The rounding-control decorator. DecoratorRoundingControl // The suppress-all-exceptions decorator. DecoratorSuppressAllExceptions // The register-swizzle decorator. DecoratorSwizzle // The conversion decorator. DecoratorConversion // The eviction-hint decorator. DecoratorEvictionHint ) // FormatterDecoratorFunc is a callback used with keys: // * FormatterFunctionPrintDecorator type FormatterDecoratorFunc func(fmtr *Formatter, fbuf *FormatterBuffer, context FormatterContext, decorator Decorator) error // FormatterFunction is an enum of formatter function types. type FormatterFunction int // FormatterFunction enum values. const ( /* * Instruction */ // FormatterFunctionPreInstruction is invoked before the formatter formats an instruction. FormatterFunctionPreInstruction FormatterFunction = iota // FormatterFunc value // FormatterFunctionPostInstruction is invoked after the formatter formatted an instruction. FormatterFunctionPostInstruction // FormatterFunc value // This function refers to the main formatting function. // // Replacing this function allows for complete custom formatting, but // indirectly disables all other hooks except for // FormatterFunctionPreInstruction and FormatterFunctionPostInstruction. FormatterFunctionFormatInstruction // FormatterFunc value /* * Operands */ // This function is invoked before the formatter formats an operand. FormatterFunctionFormatPreOperand // FormatterFunc value // This function is invoked after the formatter formatted an operand. FormatterFunctionFormatPostOperand // FormatterFunc value // This function is invoked to format a register operand. FormatterFunctionFormatFormatOperandRegister // FormatterFunc value // This function is invoked to format a memory operand. // // Replacing this function might indirectly disable some specific calls to the // FormatterFunctionPrintTypecast, FormatterFunctionPrintSegment, // FormatterFunctionPrintAddressAbsolute and // FormatterFunctionPrintAddressDisplacement functions. FormatterFunctionFormatFormatOperandMemory // FormatterFunc value // This function is invoked to format a pointer operand. FormatterFunctionFormatFormatOperandPointer // FormatterFunc value // This function is invoked to format an immediate operand. // // Replacing this function might indirectly disable some specific calls to the // FormatterFunctionPrintAddressAbsolute, FormatterFunctionPrintAddressRelative and // FormatterFunctionPrintAddressImmediate functions. FormatterFunctionFormatFormatOperandImmediate // FormatterFunc value /* * Elemental tokens */ // This function is invoked to print the instruction mnemonic. FormatterFunctionPrintMnemonic // FormatterFunc value // This function is invoked to print a register. FormatterFunctionPrintRegister // FormatterRegisterFunc value // This function is invoked to print absolute addresses. // // Conditionally invoked, if a runtime-address different to RuntimeAddressNone // was passed: // * IMM operands with relative address (e.g. JMP, CALL, ...) // * MEM operands with EIP/RIP-relative address (e.g. MOV RAX, [RIP+0x12345678]) // Always invoked for: // * MEM operands with absolute address (e.g. MOV RAX, [0x12345678]) FormatterFunctionPrintAddressAbsolute // FormatterFunc value // This function is invoked to print relative addresses. // // Conditionally invoked, if RuntimeAddressNone was passed as runtime-address: // * IMM operands with relative address (e.g. JMP, CALL, ...) FormatterFunctionPrintAddressRelative // FormatterFunc value // This function is invoked to print a memory displacement value. // // If the memory displacement contains an address and a runtime-address // different to RuntimeAddressNone was passed, // FormatterFunctionPrintAddressAbsolute is called instead. FormatterFunctionPrintAddressDisplacement // FormatterFunc value // This function is invoked to print an immediate value. // // If the immediate contains an address and a runtime-address different to // RuntimeAddressNone was passed, FormatterFunctionPrintAddressAbsolute is // called instead. // // If the immediate contains an address and RuntimeAddressNone was passed as // runtime-address, FormatterFunctionPrintAddressRelative is called instead. FormatterFunctionPrintAddressImmediate // FormatterFunc value /* * Optional tokens */ // This function is invoked to print the size of a memory operand (Intel only). FormatterFunctionPrintTypecast // FormatterFunc value // This function is invoked to print the segment-register of a memory operand. FormatterFunctionPrintSegment // FormatterFunc value // This function is invoked to print the instruction prefixes. FormatterFunctionPrintPrefixes // FormatterFunc value // This function is invoked after formatting an operand to print a EVEX/MVEX decorator. FormatterFunctionPrintDecorator // FormatterDecoratorFunc value ) type formatterCallbackContext struct { fmtr *Formatter instr *DecodedInstruction } // SetHookX configures a FormatterXFunc callback function for // an associated formatter function type. func (fmtr *Formatter) SetHookX(_type FormatterFunction, callback FormatterXFunc) error { var ptr unsafe.Pointer switch _type { case FormatterFunctionPreInstruction: ptr = unsafe.Pointer(C._hookXCallbackFormatterFunctionPreInstruction) case FormatterFunctionPostInstruction: ptr = unsafe.Pointer(C._hookXCallbackFormatterFunctionPostInstruction) case FormatterFunctionFormatInstruction: ptr = unsafe.Pointer(C._hookXCallbackFormatterFunctionFormatInstruction) case FormatterFunctionFormatPreOperand: ptr = unsafe.Pointer(C._hookXCallbackFormatterFunctionFormatPreOperand) case FormatterFunctionFormatPostOperand: ptr = unsafe.Pointer(C._hookXCallbackFormatterFunctionFormatPostOperand) case FormatterFunctionFormatFormatOperandRegister: ptr = unsafe.Pointer(C._hookXCallbackFormatterFunctionFormatFormatOperandRegister) case FormatterFunctionFormatFormatOperandMemory: ptr = unsafe.Pointer(C._hookXCallbackFormatterFunctionFormatFormatOperandMemory) case FormatterFunctionFormatFormatOperandPointer: ptr = unsafe.Pointer(C._hookXCallbackFormatterFunctionFormatFormatOperandPointer) case FormatterFunctionFormatFormatOperandImmediate: ptr = unsafe.Pointer(C._hookXCallbackFormatterFunctionFormatFormatOperandImmediate) case FormatterFunctionPrintMnemonic: ptr = unsafe.Pointer(C._hookXCallbackFormatterFunctionPrintMnemonic) case FormatterFunctionPrintAddressAbsolute: ptr = unsafe.Pointer(C._hookXCallbackFormatterFunctionPrintAddressAbsolute) case FormatterFunctionPrintAddressRelative: ptr = unsafe.Pointer(C._hookXCallbackFormatterFunctionPrintAddressRelative) case FormatterFunctionPrintAddressDisplacement: ptr = unsafe.Pointer(C._hookXCallbackFormatterFunctionPrintAddressDisplacement) case FormatterFunctionPrintAddressImmediate: ptr = unsafe.Pointer(C._hookXCallbackFormatterFunctionPrintAddressImmediate) case FormatterFunctionPrintTypecast: ptr = unsafe.Pointer(C._hookXCallbackFormatterFunctionPrintTypecast) case FormatterFunctionPrintSegment: ptr = unsafe.Pointer(C._hookXCallbackFormatterFunctionPrintSegment) case FormatterFunctionPrintPrefixes: ptr = unsafe.Pointer(C._hookXCallbackFormatterFunctionPrintPrefixes) default: panic("zydis: invalid formatter function type") } if callback == nil { ptr = nil } ret := C.ZydisFormatterSetHook( fmtr.zfmtr, C.ZydisFormatterFunction(_type), &ptr, ) if zyanFailure(ret) { return fmt.Errorf("zydis: failed to set hook 0x%x", ret) } if callback != nil { fmtr.hookForType[_type] = callback } else { delete(fmtr.hookForType, _type) } return nil } // SetHookRegister configures a FormatterRegisterFunc callback function for // an associated formatter function type. func (fmtr *Formatter) SetHookRegister(_type FormatterFunction, callback FormatterRegisterFunc) error { var ptr unsafe.Pointer switch _type { case FormatterFunctionPrintRegister: ptr = unsafe.Pointer(C._hookRegisterCallbackFormatterFunctionPrintRegister) default: panic("zydis: invalid formatter function type") } if callback == nil { ptr = nil } ret := C.ZydisFormatterSetHook( fmtr.zfmtr, C.ZydisFormatterFunction(_type), &ptr, ) if zyanFailure(ret) { return fmt.Errorf("zydis: failed to set hook 0x%x", ret) } if callback != nil { fmtr.hookForType[_type] = callback } else { delete(fmtr.hookForType, _type) } return nil } // SetHookDecorator configures a FormatterDecoratorFunc callback function for // an associated formatter function type. func (fmtr *Formatter) SetHookDecorator(_type FormatterFunction, callback FormatterDecoratorFunc) error { var ptr unsafe.Pointer switch _type { case FormatterFunctionPrintDecorator: ptr = unsafe.Pointer(C._hookDecoratorCallbackFormatterFunctionPrintDecorator) default: panic("zydis: invalid formatter function type") } if callback == nil { ptr = nil } ret := C.ZydisFormatterSetHook( fmtr.zfmtr, C.ZydisFormatterFunction(_type), &ptr, ) if zyanFailure(ret) { return fmt.Errorf("zydis: failed to set hook 0x%x", ret) } if callback != nil { fmtr.hookForType[_type] = callback } else { delete(fmtr.hookForType, _type) } return nil } // FormatInstruction formats the given instruction and writes it into // the output buffer. // Pass RuntimeAddressNone as the runtimeAddress to print relative addresses. func (fmtr *Formatter) FormatInstruction(instr *DecodedInstruction, runtimeAddress uint64) (string, error) { context := formatterCallbackContext{ fmtr: fmtr, instr: instr, } buffer := make([]byte, 256) ret := C.ZydisFormatterFormatInstructionEx( fmtr.zfmtr, instr.zdi, (*C.char)(unsafe.Pointer(&buffer[0])), C.ZyanUSize(len(buffer)), C.ZyanU64(runtimeAddress), formatterCallbackMap.NewToken(&context), ) if zyanFailure(ret) { return "", fmt.Errorf("zydis: failed to format instruction: 0x%x", ret) } return string(buffer), nil } // FormatOperand formats the given operand and writes it into the output buffer. func (fmtr *Formatter) FormatOperand(instr *DecodedInstruction, operand *DecodedOperand, runtimeAddress uint64) (string, error) { context := formatterCallbackContext{ fmtr: fmtr, instr: instr, } // Find operand index operandIndex := -1 for i := 0; i < len(instr.Operands); i++ { op := &instr.Operands[i] if op == operand { operandIndex = i break } } if operandIndex < 0 { panic("zydis: operand is not from the provided decoded instruction") } buffer := make([]byte, 256) ret := C.ZydisFormatterFormatOperandEx( fmtr.zfmtr, instr.zdi, C.ZyanU8(operandIndex), (*C.char)(unsafe.Pointer(&buffer[0])), C.ZyanUSize(len(buffer)), C.ZyanU64(runtimeAddress), formatterCallbackMap.NewToken(&context), ) if zyanFailure(ret) { return "", fmt.Errorf("zydis: failed to format operand: 0x%x", ret) } return string(buffer), nil } // TokenType is an enum of token types. type TokenType uint8 // TokenType enum values. const ( TokenTypeInvalid TokenType = 0x00 // A whitespace character. TokenTypeWhitespace TokenType = 0x01 // A delimiter character (like ',', ':', '+', '-', '*'). TokenTypeDelimiter TokenType = 0x02 // An opening parenthesis character (like '(', '[', '{'). TokenTypeParenthesisOpen TokenType = 0x03 // A closing parenthesis character (like ')', ']', '}'). TokenTypeParenthesisClose TokenType = 0x04 // A prefix literal (like "LOCK", "REP"). TokenTypePrefix TokenType = 0x05 // A mnemonic literal (like "MOV", "VCMPPSD", "LCALL"). TokenTypeMnemonic TokenType = 0x06 // A register literal (like "RAX", "DS", "%ECX"). TokenTypeRegister TokenType = 0x07 // An absolute address literal (like 0x00400000). TokenTypeAddressAbsolute TokenType = 0x08 // A relative address literal (like -0x100). TokenTypeAddressRelative TokenType = 0x09 // A displacement literal (like 0xFFFFFFFF, -0x100, +0x1234). TokenTypeDisplacement TokenType = 0x0A // An immediate literal (like 0xC0, -0x1234, $0x0000). TokenTypeImmediate TokenType = 0x0B // A typecast literal (like DWORD PTR). TokenTypeTypecast TokenType = 0x0C // A decorator literal (like "Z", "1TO4"). TokenTypeDecorator TokenType = 0x0D // A symbol literal. TokenTypeSymbol TokenType = 0x0E // The base for user-defined token types. TokenTypeUser TokenType = 0x80 ) // FormatterToken is a formatting token. type FormatterToken struct { TokenType Value string } // TokenizeInstruction tokenizes the given instruction and writes it into // the output buffer. func (fmtr *Formatter) TokenizeInstruction(instr *DecodedInstruction, runtimeAddress uint64) (string, []FormatterToken, error) { context := formatterCallbackContext{ fmtr: fmtr, instr: instr, } buffer := make([]byte, 256) var ztokenPtr C.ZyanUPointer ret := C.__ZydisFormatterTokenizeInstructionEx( fmtr.zfmtr, instr.zdi, unsafe.Pointer(&buffer[0]), C.ZyanUSize(len(buffer)), C.ZyanU64(runtimeAddress), &ztokenPtr, formatterCallbackMap.NewToken(&context), ) if zyanFailure(ret) { return "", nil, fmt.Errorf("zydis: failed to tokenize instruction: 0x%x", ret) } // Extract tokens var tokens []FormatterToken for { var ztokenType C.ZydisTokenType var ztokenStr *C.char ret = C.__ZydisFormatterTokenGetValue(ztokenPtr, &ztokenType, &ztokenStr) if zyanFailure(ret) { return "", nil, fmt.Errorf("zydis: failed to extract token: 0x%x", ret) } tokens = append(tokens, FormatterToken{ TokenType: TokenType(ztokenType), Value: C.GoString(ztokenStr), }) ret = C.__ZydisFormatterTokenNext(ztokenPtr, &ztokenPtr) if zyanFailure(ret) { break } } return string(buffer), tokens, nil } // TokenizeOperand tokenizes the given operand and writes it into // the output buffer. func (fmtr *Formatter) TokenizeOperand(instr *DecodedInstruction, operand *DecodedOperand, runtimeAddress uint64) (string, []FormatterToken, error) { context := formatterCallbackContext{ fmtr: fmtr, instr: instr, } // Find operand index operandIndex := -1 for i := 0; i < len(instr.Operands); i++ { op := &instr.Operands[i] if op == operand { operandIndex = i break } } if operandIndex < 0 { panic("zydis: operand is not from the provided decoded instruction") } buffer := make([]byte, 256) var ztokenPtr C.ZyanUPointer ret := C.__ZydisFormatterTokenizeOperandEx( fmtr.zfmtr, instr.zdi, C.ZyanU8(operandIndex), unsafe.Pointer(&buffer[0]), C.ZyanUSize(len(buffer)), C.ZyanU64(runtimeAddress), &ztokenPtr, formatterCallbackMap.NewToken(&context), ) if zyanFailure(ret) { return "", nil, fmt.Errorf("zydis: failed to tokenize operand: 0x%x", ret) } // Extract tokens var tokens []FormatterToken for { var ztokenType C.ZydisTokenType var ztokenStr *C.char ret = C.__ZydisFormatterTokenGetValue(ztokenPtr, &ztokenType, &ztokenStr) if zyanFailure(ret) { return "", nil, fmt.Errorf("zydis: failed to extract token: 0x%x", ret) } tokens = append(tokens, FormatterToken{ TokenType: TokenType(ztokenType), Value: C.GoString(ztokenStr), }) ret = C.__ZydisFormatterTokenNext(ztokenPtr, &ztokenPtr) if zyanFailure(ret) { break } } return string(buffer), tokens, nil }
package model import ( "time" ) type PlayerVersion struct { // Id of the resource Id string `json:"id,omitempty"` // Version of the Player Version string `json:"version,omitempty"` // URL of the specified player CdnUrl string `json:"cdnUrl,omitempty"` // Download URL of the specified player package DownloadUrl string `json:"downloadUrl,omitempty"` // Creation timestamp formatted in UTC: YYYY-MM-DDThh:mm:ssZ CreatedAt *time.Time `json:"createdAt,omitempty"` }
package dynamic_programming import ( "fmt" "testing" ) func Test_minimumTotal(t *testing.T) { nums := [][]int{ {2}, {3, 4}, {6, 5, 7}, {4, 1, 8, 3}, } res := minimumTotal(nums) fmt.Println(res) }
package store import ( "sync" "github.com/nikunjgit/crypto/event" ) type MemoryStore struct { memory map[string]event.Messages ttl int mutex *sync.Mutex } func NewMemoryStore(ttl int) *MemoryStore { return &MemoryStore{make(map[string]event.Messages), ttl, &sync.Mutex{}} } func (m *MemoryStore) Set(key string, message event.Messages) error { m.mutex.Lock() m.memory[key] = message m.mutex.Unlock() return nil } func (m *MemoryStore) Get(keys []string) (event.Messages, error) { vals := make(event.Messages, 0, 10) m.mutex.Lock() for _, key := range keys { val, ok := m.memory[key] if !ok { continue } vals = append(vals, val...) } m.mutex.Unlock() return vals, nil }
import "sort" func singleNumber(nums []int) int { return sol1(nums) } // using Sort.sort (quicksort or heapsort) // time: O(n*log(n)), space: O(1) func sol1(nums []int) int { sort.Ints(nums) for i := 0; i < len(nums); i = i + 2 { if i+1 < len(nums) && nums[i] != nums[i+1] { return nums[i] } } return nums[len(nums)-1] } // simple memoize // time: O(n), space: O(n/2) func sol2(nums []int) int { memo := make(map[int]int) for _, n := range nums { memo[n]++ } for k, v := range memo { if v == 1 { return k } } return -1 }
package main import ( "database/sql" "fmt" "html/template" "log" "net/http" _ "github.com/mattn/go-sqlite3" ) type brand struct { Company string Ltp string Change string Volume string Buy_price string Sell_price string Buy_qty string Sell_qty string } type Var struct { temp string Result_list []brand } var store brand func renderTemplate(w http.ResponseWriter, tmpl string) { t, _ := template.ParseFiles(tmpl + ".html") t.Execute(w, 1) } func query(w http.ResponseWriter, r *http.Request) { renderTemplate(w, "query") } func homehandler(w http.ResponseWriter, r *http.Request) { renderTemplate(w, "home") } func jobHandler(w http.ResponseWriter, r *http.Request) { job := r.FormValue("fill") if job == "query" { http.Redirect(w, r, "/query/", http.StatusFound) } else { http.Redirect(w, r, "/output/", http.StatusFound) } } func queryHandler(w http.ResponseWriter, r *http.Request) { company_name := r.FormValue("name_action") database, _ := sql.Open("sqlite3", "./live_shares.db") query := "SELECT * FROM shares WHERE company = '" + company_name + "'" rows, _ := database.Query(query) //fmt.Println(company_name) //fmt.Println(rows) for rows.Next() { rows.Scan(&store.Company, &store.Ltp, &store.Change, &store.Volume, &store.Buy_price, &store.Sell_price, &store.Buy_qty, &store.Sell_qty) } fmt.Println(store) http.Redirect(w, r, "/queryOutput/", http.StatusFound) } func queryOutputHandler(w http.ResponseWriter, r *http.Request) { t, _ := template.ParseFiles("queryOutput.html") fmt.Println("Hellllloooooo") fmt.Println(store) t.Execute(w, store) } func outputhandler(w http.ResponseWriter, r *http.Request) { database, _ := sql.Open("sqlite3", "./live_shares.db") rows, _ := database.Query("SELECT * FROM shares") var data []brand for rows.Next() { var temp brand rows.Scan(&temp.Company, &temp.Ltp, &temp.Change, &temp.Volume, &temp.Buy_price, &temp.Sell_price, &temp.Buy_qty, &temp.Sell_qty) data = append(data, temp) fmt.Println(temp) } fmt.Println(data[1]) var send_var Var send_var.Result_list = data t, _ := template.ParseFiles("output.html") t.Execute(w, send_var) } func main() { http.HandleFunc("/output/", outputhandler) http.HandleFunc("/home/", homehandler) http.HandleFunc("/jobHandler/", jobHandler) http.HandleFunc("/query/", query) http.HandleFunc("/queryHandler/", queryHandler) http.HandleFunc("/queryOutput/", queryOutputHandler) log.Fatal(http.ListenAndServe(":8080", nil)) }
package main import ( "flag" "fmt" "log" "math" "os" "sort" ) var ( wins = [][]int{ {1, 2, 3}, {1, 4, 7}, {1, 5, 9}, {2, 5, 8}, {3, 5, 7}, {3, 6, 9}, {4, 5, 6}, {7, 8, 9}} turn, count, total int win bool = false stat string ) type Game struct { board [][]string protected []int size int } type Piece struct { piece map[int]string player map[string]Info } type Info struct { moveSet []int agent string } func main() { //set game premise. size, player 1 and 2 size := flag.Int("size", 3, "Board is an mxm matrix where m=3 by default") player1 := flag.String("player1", "X", "Player 1 is X by default") player2 := flag.String("player2", "O", "Player 2 is O by default") flag.Parse() //initialise and register players players := []string{*player1, *player2} p := initPiece(players) var g Game //startGame g.startGame(p, *size) } func initPiece(p []string) Piece { a := "human" var player Piece player.piece, player.player = make(map[int]string), make(map[string]Info) for index, value := range p { player.piece[index] = value player.player[value] = Info{agent: a} } return player } func (g Game) startGame(pl Piece, size int) { g.setBoard(size) count, turn = 0, 0 //total number of moves is (mxm) total = int(math.Exp2(float64(size))) for { //display board markup and game board side by side displayBoard(g) //prompt user for input pl.play(turn, g) //check for win playerMoves := pl.player[pl.piece[turn]].moveSet for _, sub := range wins { win = CheckWin(playerMoves, sub) if win { stat = "W" } } //if no win and board is full call draw log.Println(count, ":", total) if count == total && !win { stat = "D" } //else continue for next player switch stat { case "W": displayBoard(g) msg(fmt.Sprintf("%s Won", pl.piece[turn])) case "D": displayBoard(g) msg("A draw") default: //update count and turn turn = findTurn(turn) count++ } } } func (p *Piece) play(t int, g Game) { //update player set var move int pl := p.piece[t] fmt.Printf("Player %d:\n", turn+1) for { fmt.Printf("Select where to place your piece \"%s\" :- ", pl) _, err := fmt.Scan(&move) if err != nil { fmt.Println("Wrong input, try again.") } else { if move < 1 || move > total+1 { fmt.Println("Position doesn't exist on board") } else { if g.protected[move-1] == move { fmt.Println("Position on the board is already occupied.") } else { break } } } } temp := p.player[pl].moveSet p.player[pl] = Info{moveSet: append(temp, move)} g.updateBoard(pl, move) } func (g *Game) updateBoard(player string, m int) { x, y := findCoordinates(m, g.size) g.board[x][y] = player g.protected[m-1] = m } func (g *Game) setBoard(size int) { g.board = make([][]string, size) g.protected = make([]int, int(math.Exp2(float64(size)))+1) g.size = size for in := range g.board { g.board[in] = make([]string, size) for index := range g.board[in] { g.board[in][index] = "*" } } } func findCoordinates(value, matrixSize int) (int, int) { x, y, initialValue := int(math.Ceil(float64(value)/float64(matrixSize))-1), matrixSize-1, value for { if value%matrixSize == 0 { y -= (value - initialValue) break } else { value++ } } return x, y } func CheckWin(super, sub []int) bool { super, sub = sort.IntSlice(super), sort.IntSlice(sub) check := 0 for _, value := range super { for _, val := range sub { if val == value { check += 1 continue } } if check == len(sub) { return true } } return false } func msg(str string) { fmt.Println(str) os.Exit(1) } func findTurn(t int) int { if t == 0 { return 1 } else { return 0 } } func displayBoard(b Game) { board := b.board matrixEdge, boardUI, layout := len(board)-1, "", "" divider := fmt.Sprintf("\t\t-----------\n") l := 1 for index := range board { for i, value := range board[index] { if i == matrixEdge { boardUI += fmt.Sprintf(" %s \n", value) layout += fmt.Sprintf(" %d \n", l) } else if i == 0 { boardUI += fmt.Sprintf("\t\t %s |", value) layout += fmt.Sprintf("\t\t %d |", l) } else { boardUI += fmt.Sprintf(" %s |", value) layout += fmt.Sprintf(" %d |", l) } l++ } if index != matrixEdge { boardUI += divider layout += divider } } fmt.Printf("%s\n%s", layout, boardUI) }
package easy import ( "fmt" "testing" ) func Test20(t *testing.T) { a := "()[]{]}" isValid(a) } func fan(s string) string { switch s { case "{": return "}" case "(": return ")" case "[": return "]" case "}": return "{" case ")": return "(" case "]": return "[" } return "" } func isValid(s string) bool { ha := NewHaha() for _,v := range s{ if ha.new() == fan(string(v)) { ha.pop() } else { ha.push(string(v)) } } if len(ha.element)==0{ fmt.Println("true") return true } else { fmt.Println("false") return false } } type haha struct { element []string } func NewHaha() *haha { return &haha{} } func (h *haha) push(s string) { h.element = append(h.element, s) } func (h *haha) pop() { size := len(h.element) if size == 0 { return } h.element = h.element[:size-1] } func (h *haha) new() string{ size := len(h.element) if size == 0 { return "" } return h.element[size-1] } func Test21(t *testing.T){ } func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode { var result *ListNode result = new(ListNode) if l1 == nil{ return l2 } if l2 == nil{ return l1 } p1 := l1 p2 := l2 tmp := result for { if p1==nil || p2==nil{ break } if p1.Val <= p2.Val { tmp.Next = p1 tmp = tmp.Next p1 = p1.Next }else { tmp.Next = p2 tmp = tmp.Next p2 = p2.Next } } if p1 != nil { tmp.Next = p1 } if p2 != nil { tmp.Next = p2 } return result.Next // result self has 0 } type ListNode struct { Val int Next *ListNode } func Test26(t *testing.T) { a := []int{0,0,1,1,2,3,4,4,4} b := removeDuplicates(a) fmt.Println(a) println(b) } func removeDuplicates(nums []int) int { index := 0 if len(nums)==0{ return 0 } tmp := nums[0]-1 for _,v := range nums{ if tmp != v { nums[index]=v tmp = v index++ } } return index } func Test27(t *testing.T) { nums := []int{3,2,4,3,3,2,6,7,2,3} val := 3 b := removeElement(nums,val) fmt.Println(nums) fmt.Println(b) } func removeElement(nums []int, val int) int { index := 0 if len(nums)==0 { return 0 } for _,v := range nums{ if v != val { nums[index]=v index++ } } return index } func Test28(t *testing.T) { h := "hello" n := "ll" r := strStr(h,n) fmt.Println(r) } func strStr(haystack string, needle string) int { index := -1 if needle == "" { return 0 } for k,v := range haystack { if k+len(needle) >len(haystack){ break } if string(v) == string(needle[0]) { index = k for m,n := range needle { if string(haystack[k+m]) != string(n) { index = -1 break } } } if index != -1{ break } } return index }
package daemons import ( "fmt" "docktor/server/middleware" "docktor/server/types" "github.com/labstack/echo/v4" ) // AddRoute add route on echo func AddRoute(e *echo.Group) { daemons := e.Group("/daemons") // Basic daemon request daemons.GET("", getAll) daemons.GET("/rundeck", getAllRundeck, middleware.WithAdmin) daemons.POST("", save, middleware.WithAdmin) { daemon := daemons.Group(fmt.Sprintf("/:%s", types.DAEMON_ID_PARAM)) daemon.GET("", getByID) daemon.DELETE("", deleteByID, middleware.WithAdmin) { // Compose requests compose := daemon.Group("/compose") compose.Use(middleware.WithAdmin) compose.GET("/services", getComposeServices) compose.GET("/status", getDaemonComposeStatus) compose.POST("/status", updateDaemonComposeStatus) } { // Docker requests docker := daemon.Group("/docker") docker.GET("/containers", getContainers, middleware.WithAdmin) docker.GET("/containers/saved", getSavedContainers, middleware.WithAdmin) docker.POST("/containers/status", updateContainersStatus) docker.GET(fmt.Sprintf("/containers/:%s/log", types.CONTAINER_ID_PARAM), getContainerLog, middleware.WithDaemonContainer) docker.GET(fmt.Sprintf("/containers/:%s/term", types.CONTAINER_ID_PARAM), getContainerTerm, middleware.WithDaemonContainer, middleware.WithIsAllowShellContainer) docker.POST(fmt.Sprintf("/containers/:%s/exec/:%s", types.CONTAINER_ID_PARAM, types.COMMAND_ID_PARAM), execContainer, middleware.WithDaemonContainer) docker.GET("/images", getImages, middleware.WithAdmin) docker.DELETE(fmt.Sprintf("/images/:%s", types.DOCKER_IMAGE_PARAM), deleteImages, middleware.WithAdmin) } { // SSH requests ssh := daemon.Group("/ssh") ssh.Use(middleware.WithAdmin) ssh.GET("/term", getSSHTerm) ssh.POST("/exec", execSSH) } { // CAdvisor requests cadvisor := daemon.Group("/cadvisor") cadvisor.Use(middleware.WithAdmin) cadvisor.GET("", getCAdvisorInfo) } } }
// Copyright 2022 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to 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 reader import ( "os" "testing" "time" "github.com/Shopify/sarama" pb "github.com/pingcap/tidb/tidb-binlog/proto/go-binlog" "github.com/stretchr/testify/require" ) type testOffset struct { producer sarama.SyncProducer config *sarama.Config addr string available bool topic string } var to testOffset func Setup() { to.topic = "test" to.addr = "192.168.198.61" if os.Getenv("HOSTIP") != "" { to.addr = os.Getenv("HOSTIP") } to.config = sarama.NewConfig() to.config.Producer.Partitioner = sarama.NewManualPartitioner to.config.Producer.Return.Successes = true to.config.Net.DialTimeout = time.Second * 3 to.config.Net.ReadTimeout = time.Second * 3 to.config.Net.WriteTimeout = time.Second * 3 // need at least version to delete topic to.config.Version = sarama.V0_10_1_0 var err error to.producer, err = sarama.NewSyncProducer([]string{to.addr + ":9092"}, to.config) if err == nil { to.available = true } } func deleteTopic(t *testing.T) { broker := sarama.NewBroker(to.addr + ":9092") err := broker.Open(to.config) require.NoError(t, err) defer broker.Close() broker.DeleteTopics(&sarama.DeleteTopicsRequest{Topics: []string{to.topic}, Timeout: 10 * time.Second}) } func TestOffset(t *testing.T) { Setup() if !to.available { t.Skip("no kafka available") } deleteTopic(t) defer deleteTopic(t) topic := to.topic sk, err := NewKafkaSeeker([]string{to.addr + ":9092"}, to.config) require.NoError(t, err) to.producer, err = sarama.NewSyncProducer([]string{to.addr + ":9092"}, to.config) require.NoError(t, err) defer to.producer.Close() var testPoss = map[int64]int64{ 10: 0, 20: 0, 30: 0, } for ts := range testPoss { testPoss[ts], err = procudeMessage(ts, topic) require.NoError(t, err) // c.Log("produce ", ts, " at ", testPoss[ts]) } var testCases = map[int64]int64{ 1: testPoss[10], 10: testPoss[20], 15: testPoss[20], 20: testPoss[30], 35: testPoss[30] + 1, } for ts, offset := range testCases { offsetFounds, err := sk.Seek(topic, ts, []int32{0}) t.Log("check: ", ts) require.NoError(t, err) require.Len(t, offsetFounds, 1) require.Equal(t, offset, offsetFounds[0]) } } func procudeMessage(ts int64, topic string) (offset int64, err error) { binlog := new(pb.Binlog) binlog.CommitTs = ts var data []byte data, err = binlog.Marshal() if err != nil { return } msg := &sarama.ProducerMessage{ Topic: topic, Partition: int32(0), Key: sarama.StringEncoder("key"), Value: sarama.ByteEncoder(data), } _, offset, err = to.producer.SendMessage(msg) if err == nil { return } return offset, err }
package saml import ( "bytes" "encoding/base64" "encoding/xml" "log" "net/http" "text/template" ) var redirectFormTemplate = `<!DOCTYPE html> <html> <head></head> <body> <form id="redirect" method="POST" action="{{.FormAction}}"> <input type="hidden" name="RelayState" value="{{.RelayState}}" /> <input type="hidden" name="SAMLResponse" value="{{.SAMLResponse}}" /> </form> <script type="text/javascript"> document.getElementById("redirect").submit(); </script> </body> </html>` // Authenticator defines an authentication function that returns a // *saml.Session value. type Authenticator func(w http.ResponseWriter, r *http.Request) (*Session, error) type redirectForm struct { FormAction string RelayState string SAMLResponse string } // LoginRequest represents a login request that the IdP creates in order to try // autenticating against a SP. type LoginRequest struct { spMetadataURL string metadata *Metadata authFn Authenticator idp *IdentityProvider } // PostForm creates and serves a form that is used to authenticate to the SP. func (lr *LoginRequest) PostForm(w http.ResponseWriter, r *http.Request) { ctx := r.Context() sess, err := lr.authFn(w, r) if err != nil { log.Printf("authFn: %v", err) return } authnRequest := &AuthnRequest{} idpAuthnRequest := &IdpAuthnRequest{ IDP: lr.idp, Address: r.RemoteAddr, Request: *authnRequest, ServiceProviderMetadata: lr.metadata, } if err = idpAuthnRequest.MakeAssertion(sess); err != nil { log.Printf("Failed to build assertion %v", err) writeErr(w, err) return } err = idpAuthnRequest.MarshalAssertion() if err != nil { log.Printf("Failed to marshal assertion %v", err) writeErr(w, err) return } err = idpAuthnRequest.MakeResponse() if err != nil { log.Printf("Failed to build response %v", err) writeErr(w, err) return } buf, err := xml.MarshalIndent(idpAuthnRequest.Response, "", "\t") if err != nil { log.Printf("Failed to format response %v", err) writeErr(w, err) return } // RelayState is an opaque string that can be used to keep track of this // session on our side. var relayState string token := ctx.Value("saml.RelayState") if token != nil { relayState, _ = token.(string) } form := redirectForm{ FormAction: lr.metadata.SPSSODescriptor.AssertionConsumerService[0].Location, RelayState: relayState, SAMLResponse: base64.StdEncoding.EncodeToString(buf), } formTpl, err := template.New("").Parse(redirectFormTemplate) if err != nil { log.Printf("Failed to create form %v", err) writeErr(w, err) return } formBuf := bytes.NewBuffer(nil) if err := formTpl.Execute(formBuf, form); err != nil { log.Printf("Failed to build form %v", err) writeErr(w, err) return } w.Header().Set("Content-Type", "text/html") w.Write(formBuf.Bytes()) }
/* Copyright SecureKey Technologies Inc. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package hashing import ( "crypto/sha256" "testing" "github.com/stretchr/testify/require" ) const algSHA256 = 5 func TestHash(t *testing.T) { t.Run("success", func(t *testing.T) { test := []byte("hello world") h, err := GetHash(algSHA256, test) require.NoError(t, err) require.NotEmpty(t, h) expected := sha256.Sum256(test) require.Equal(t, expected[:], h) }) t.Run("error - hash code not supported", func(t *testing.T) { test := []byte("test data") h, err := GetHash(55, test) require.Error(t, err) require.Empty(t, h) require.Contains(t, err.Error(), "hash function not available for: 55") }) }
package routers import ( "github.com/astaxie/beego" "sago/controllers" ) func init() { beego.Router("/", &controllers.MainController{}) beego.AutoRouter(&controllers.UserController{}) // beego.Router("/user/test", &controllers.UserController{}, "*:Test") // beego.Router("/user/:id", &controllers.UserController{}, "*:test") // beego.Router("/user/:id", &controllers.UserController{}) }
package dcmdata import ( "github.com/grayzone/godcm/ofstd" ) type DcmElement struct { DcmObject /// current byte order of attribute value in memory fByteOrder E_ByteOrder /// required information to load value later fLoadValue DcmInputStreamFactory /// value of the element fValue uint16 } /** get a pointer to the element value of the current element as type string. * Requires element to be of corresponding VR, otherwise an error is returned. * This method does not copy, but returns a pointer to the element value, * which remains under control of this object and is valid only until the next * read, write or put operation. * @param val pointer to value returned in this parameter upon success * @return EC_Normal upon success, an error code otherwise */ /** constructor. * Create new element from given tag and length. * @param tag DICOM tag for the new element * @param len value length for the new element */ func NewDcmElement(tag DcmTag, l uint32) *DcmElement { var result DcmElement obj := NewDcmObject(tag, l) result.DcmObject = *obj result.fByteOrder = GLocalByteOrder return &result } /** get a pointer to the element value of the current element as type string. * Requires element to be of corresponding VR, otherwise an error is returned. * This method does not copy, but returns a pointer to the element value, * which remains under control of this object and is valid only until the next * read, write or put operation. * @param val pointer to value returned in this parameter upon success * @return EC_Normal upon success, an error code otherwise */ func (e *DcmElement) GetString(val string) ofstd.OFCondition { // for strings e.errorFlag = EC_IllegalCall return e.errorFlag } /** calculate the value length (without attribute tag, VR and length field) * of this DICOM element when encoded with the given transfer syntax and * the given encoding type for sequences. Never returns undefined length. * @param xfer transfer syntax for length calculation * @param enctype sequence encoding type for length calculation * @return value length of DICOM element */ func (e *DcmElement) GetLength(xfer E_TransferSyntax, enctype E_EncodingType) uint32 { return e.length } /** calculate the length of this DICOM element when encoded with the * given transfer syntax and the given encoding type for sequences. * For elements, the length includes the length of the tag, length field, * VR field and the value itself, for items and sequences it returns * the length of the complete item or sequence including delimitation tags * if applicable. Never returns undefined length. * @param xfer transfer syntax for length calculation * @param enctype sequence encoding type for length calculation * @return length of DICOM element */ func (e *DcmElement) CalcElementLength(xfer E_TransferSyntax, enctype E_EncodingType) uint32 { xferSyn := NewDcmXfer(xfer) vr := e.GetVR() if (vr == EVR_UNKNOWN2B) || (vr == EVR_na) { vr = EVR_UN } headerLength := xferSyn.SizeofTagHeader(vr) elemLength := e.GetLength(xfer, enctype) if ofstd.Check32BitAddOverflow(headerLength, elemLength) { return DCM_UndefinedLength } else { return headerLength + elemLength } }
package main import "moriaty.com/cia/cia-common/auth" func main() { auth := auth.NewAuth("memory") auth.RemoveToken("1") }
package service import ( "errors" "fmt" "github.com/linxlib/logs" "github.com/robfig/cron/v3" "sync" ) func Init() { logs.Error(fmt.Errorf("Test Error: %+v",errors.New("error example"))) } type WeatherJob struct { mtx sync.Mutex running bool } func (w *WeatherJob) Run() { if !w.SetRun() { logs.Warn("天气服务正在运行") return } logs.Error(fmt.Errorf("Test Error: %+v",errors.New("error example"))) w.doneRun() } func (w *WeatherJob) SetRun() bool { w.mtx.Lock() defer w.mtx.Unlock() if w.running { return false } w.running = true return true } func (w *WeatherJob) doneRun() { w.mtx.Lock() w.running = false defer w.mtx.Unlock() } type SingleJob interface { cron.Job SetRun() bool doneRun() }
package libpq import ( "fmt" "github.com/yydzero/mnt/executor" "io" "net" "github.com/yydzero/mnt/executor/fake" "log" ) // ErrSSLRequired is returned when a client attemps to connect to a // secure server in clear text. const ErrSSLRequired = "cleartext connections are not permitted" const ( version30 = 0x30000 versionSSL = 0x4D2162F versionQE = 0x70030000 ) var ( sslSupported = []byte{'S'} sslUnsupported = []byte{'N'} ) // Server implements the server side of the PostgreSQL wire protocol. type Server struct { executor executor.Executor } func NewServer() Server { s := Server{ executor: &fake.FakeExecutor{}, } return s } // IsPQConnection returns true if rd appears to be a Postgres connection. func IsPQConnection(rd io.Reader) bool { var buf readBuffer _, err := buf.readUntypedMsg(rd) if err != nil { return false } version, err := buf.getInt32() if err != nil { return false } return version == version30 || version == versionSSL } // Serve serves a single connection, driving the handshake process // and delegating to the appropriate connection type. func (s *Server) Serve(conn net.Conn) error { var buf readBuffer _, err := buf.readUntypedMsg(conn) if err != nil { return err } log.Println("Processed startup message.") version, err := buf.getInt32() if err != nil { return err } log.Printf("libpq version = %d\n", version) if version == version30 || version == versionQE { sessionArgs, argsErr := parseOptions(buf.msg) // Make a connection regardless of argsErr. If there was an error parsing // the args, the connection will only be used to send a report of that error. pqConn := newPQConn(conn, s.executor, sessionArgs) defer pqConn.close() if argsErr != nil { return pqConn.sendInternalError(err.Error()) } return pqConn.serve(nil) } return fmt.Errorf("unknow protocol version %d", version) }
package main import ( "fmt" "strings" ) type opmap map[int]int type opcoderesult struct { opcode int matches map[int]bool } func getMatchIndexes(s state, ops []operation, om opmap, results chan opcoderesult) { count := map[int]bool{} for i, op := range ops { result := op.fn(s.beforeregs, s.inputreg1, s.inputreg2, s.outputreg) if result == s.afterregs { count[i] = true } } results <- opcoderesult{s.opcode, count} } func resolveops(samples []state, ops []operation) opmap { om := opmap{} results := make(chan opcoderesult) launched := 0 //evaluate all the samples in parallel for _, s := range samples { go getMatchIndexes(s, ops, om, results) launched++ } //aggregate results by opcode driven mergedresults := map[int]map[int]bool{} for ; launched > 0; launched-- { //accept result from channel matchresult := <-results //if we haven't seen this opcode before, we'll need to create the map if _, found := mergedresults[matchresult.opcode]; !found { mergedresults[matchresult.opcode] = map[int]bool{} } //for each key/value in the match result map, add to //results for the opcode that was tested. for k, v := range matchresult.matches { mergedresults[matchresult.opcode][k] = v } } //now identify which ops are which indexes! //keep going until we have a match for every opcode for len(om) < len(ops) { //remove identified opcodes for this pass for _, matchingindexes := range mergedresults { for _, index := range om { delete(matchingindexes, index) } } //look for any opcodes that now only have a single index for opcode, matchingindexes := range mergedresults { if len(matchingindexes) == 1 { for k := range matchingindexes { om[opcode] = k } } } } return om } func runprog(input string, om opmap, ops []operation) { var r regs for _, line := range strings.Split(input, "\n") { line = strings.TrimSpace(line) if line == "" { continue } //read in next instruction opcode, A, B, C := 0, 0, 0, 0 fmt.Sscanf(line, "%d %d %d %d]", &opcode, &A, &B, &C) //run instruction, using opmap to locate appropriate fn to drive r = ops[om[opcode]].fn(r, A, B, C) } //dump answer for part 2. fmt.Println("Value in Reg 0 at end of prog ", r[0]) } func main2(s []state, ops []operation) { om := resolveops(s, ops) runprog(testprog(), om, ops) } func testprog() string { return `` }
package main import ( "net/http" ) type fileHandler string func FileHandler(config map[string]string) http.Handler { return fileHandler(mustGet(config, "path")) } func (f fileHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, string(f)) }
// DRUNKWATER TEMPLATE(add description and prototypes) // Question Title and Description on leetcode.com // Function Declaration and Function Prototypes on leetcode.com //513. Find Bottom Left Tree Value //Given a binary tree, find the leftmost value in the last row of the tree. //Example 1: //Input: // 2 // / \ // 1 3 //Output: //1 //Example 2: //Input: // 1 // / \ // 2 3 // / / \ // 4 5 6 // / // 7 //Output: //7 //Note: You may assume the tree (i.e., the given root node) is not NULL. ///** // * Definition for a binary tree node. // * type TreeNode struct { // * Val int // * Left *TreeNode // * Right *TreeNode // * } // */ //func findBottomLeftValue(root *TreeNode) int { //} // Time Is Money
package golify type golifyBooleanObject struct { Value bool Err *golifyErr }
package goidc import ( "encoding/json" "fmt" "net/http" "strconv" "github.com/golang-jwt/jwt" "github.com/lyokato/goidc/authorization" "github.com/lyokato/goidc/bridge" "github.com/lyokato/goidc/flow" "github.com/lyokato/goidc/id_token" "github.com/lyokato/goidc/io" "github.com/lyokato/goidc/log" "github.com/lyokato/goidc/prompt" "github.com/lyokato/goidc/response_mode" "github.com/lyokato/goidc/scope" ) type AuthorizationEndpoint struct { di bridge.DataInterface policy *authorization.Policy logger log.Logger currentTime io.TimeBuilder } func NewAuthorizationEndpoint(di bridge.DataInterface, policy *authorization.Policy) *AuthorizationEndpoint { return &AuthorizationEndpoint{ di: di, policy: policy, logger: log.NewDefaultLogger(), currentTime: io.NowBuilder(), } } func (a *AuthorizationEndpoint) SetLogger(l log.Logger) { a.logger = l } func (a *AuthorizationEndpoint) SetTimeBuilder(builder io.TimeBuilder) { a.currentTime = builder } func (a *AuthorizationEndpoint) HandleRequest(w http.ResponseWriter, r *http.Request, callbacks bridge.AuthorizationCallbacks) bool { cid := r.FormValue("client_id") if cid == "" { a.logger.Debug(log.AuthorizationEndpointLog(r.URL.Path, log.MissingParam, map[string]string{ "param": "client_id", }, "'client_id' not found in request.")) callbacks.ShowErrorScreen(authorization.ErrMissingClientId) return false } ruri := r.FormValue("redirect_uri") if ruri == "" { a.logger.Debug(log.AuthorizationEndpointLog(r.URL.Path, log.MissingParam, map[string]string{ "param": "redirect_uri", }, "'redirect_uri' not found in request.")) callbacks.ShowErrorScreen(authorization.ErrMissingRedirectURI) return false } clnt, serr := a.di.FindClientById(cid) if serr != nil { if serr.Type() == bridge.ErrFailed { a.logger.Info(log.AuthorizationEndpointLog(r.URL.Path, log.NoEnabledClient, map[string]string{ "method": "FindClientById", "client_id": cid, }, "client associated with the client_id not found")) callbacks.ShowErrorScreen(authorization.ErrMissingClientId) return false } else if serr.Type() == bridge.ErrUnsupported { a.logger.Error(log.AuthorizationEndpointLog(r.URL.Path, log.InterfaceUnsupported, map[string]string{ "method": "FindClientById", }, "this method returns 'unsupported' error")) callbacks.ShowErrorScreen(authorization.ErrServerError) return false } else if serr.Type() == bridge.ErrServerError { a.logger.Error(log.AuthorizationEndpointLog(r.URL.Path, log.InterfaceError, map[string]string{ "method": "FindClientById", "client_id": cid, }, "this method returns ServerError")) callbacks.ShowErrorScreen(authorization.ErrServerError) return false } } else { if clnt == nil { a.logger.Error(log.AuthorizationEndpointLog(r.URL.Path, log.InterfaceError, map[string]string{ "method": "FindClientById", "client_id": cid, }, "this method returns (nil, nil).")) callbacks.ShowErrorScreen(authorization.ErrServerError) return false } } if !clnt.CanUseRedirectURI(ruri) { a.logger.Info(log.AuthorizationEndpointLog(r.URL.Path, log.RedirectURIMismatch, map[string]string{ "method": "CanUseRedirectURI", "client_id": cid, "redirect_uri": ruri, }, "this 'redirect_uri' is not allowed for this client.")) callbacks.ShowErrorScreen(authorization.ErrInvalidRedirectURI) return false } state := r.FormValue("state") rmode := r.FormValue("response_mode") rt := r.FormValue("response_type") if rt == "" { a.logger.Debug(log.AuthorizationEndpointLog(r.URL.Path, log.MissingParam, map[string]string{ "param": "response_type", }, "'response_type' not found in request.")) authorization.ResponseHandlerForMode(rmode, w, r).Error( ruri, "invalid_request", "missing 'response_type'", state) return false } f, err := flow.JudgeByResponseType(rt) if err != nil { a.logger.Debug(log.AuthorizationEndpointLog(r.URL.Path, log.InvalidResponseType, map[string]string{ "response_type": rt, }, "'response_type' is not appropriate.")) authorization.ResponseHandlerForMode(rmode, w, r).Error( ruri, "invalid_request", fmt.Sprintf("invalid 'response_type:%s'", rt), state) return false } var defaultRM string switch f.Type { case flow.AuthorizationCode: defaultRM = a.policy.DefaultAuthorizationCodeFlowResponseMode case flow.Implicit: defaultRM = a.policy.DefaultImplicitFlowResponseMode case flow.Hybrid: defaultRM = a.policy.DefaultImplicitFlowResponseMode default: defaultRM = a.policy.DefaultAuthorizationCodeFlowResponseMode } if rmode == "" { a.logger.Debug(log.AuthorizationEndpointLog(r.URL.Path, log.MissingParam, map[string]string{ "response_mode": defaultRM, }, "'response_mode' not found, so, set default for this flow.")) rmode = defaultRM } else { if !response_mode.Validate(rmode) { if a.policy.IgnoreInvalidResponseMode { a.logger.Debug(log.AuthorizationEndpointLog(r.URL.Path, log.InvalidResponseMode, map[string]string{ "response_mode": rmode, "default": defaultRM, }, "this 'response_mode' is invalid, so, set default")) rmode = defaultRM } else { a.logger.Debug(log.AuthorizationEndpointLog(r.URL.Path, log.InvalidResponseMode, map[string]string{ "response_mode": rmode, }, "this 'response_mode' is invalid, so return error")) authorization.ResponseHandlerForMode(defaultRM, w, r).Error( ruri, "invalid_request", fmt.Sprintf("unknown 'response_mode': '%s'", rmode), state) return false } } } if a.policy.RequireResponseModeSecurityLevelCheck { if !response_mode.CompareSecurityLevel(rmode, defaultRM) { if a.policy.IgnoreInvalidResponseMode { a.logger.Debug(log.AuthorizationEndpointLog(r.URL.Path, log.InvalidResponseMode, map[string]string{ "response_mode": rmode, "default": defaultRM, }, "this 'response_mode' is not secure than default, so set default.")) rmode = defaultRM } else { a.logger.Debug(log.AuthorizationEndpointLog(r.URL.Path, log.InvalidResponseMode, map[string]string{ "response_mode": rmode, }, "this 'response_mode' is not secure than default, so return error.")) authorization.ResponseHandlerForMode(defaultRM, w, r).Error( ruri, "invalid_request", fmt.Sprintf("'response_mode:%s' isn't allowed for 'response_type:%s'", rmode, rt), state) return false } } } rh := authorization.ResponseHandlerForMode(rmode, w, r) if !clnt.CanUseFlow(f.Type) { a.logger.Debug(log.AuthorizationEndpointLog(r.URL.Path, log.InvalidResponseType, map[string]string{ "response_type": rt, "flow_type": f.Type.String(), }, "this flow is not allowed for this client.")) rh.Error(ruri, "unauthorized_client", "", state) return false } display := authorization.DisplayTypePage d := r.FormValue("display") if d != "" { if d == authorization.DisplayTypePage || d == authorization.DisplayTypePopup || d == authorization.DisplayTypeWAP || d == authorization.DisplayTypeTouch { display = d } else { a.logger.Debug(log.AuthorizationEndpointLog(r.URL.Path, log.InvalidDisplay, map[string]string{ "display": d, }, "invalid 'display' parameter.")) rh.Error(ruri, "invalid_request", fmt.Sprintf("unknown 'display': '%s'", d), state) return false } } var ma int mas := r.FormValue("max_age") if mas != "" { ma, err = strconv.Atoi(mas) if err != nil { a.logger.Debug(log.AuthorizationEndpointLog(r.URL.Path, log.InvalidMaxAge, map[string]string{}, "'max_age' is not an integer value.")) rh.Error(ruri, "invalid_request", fmt.Sprintf("'max_age' should be integer: '%s'", mas), state) return false } if ma < a.policy.MinMaxAge { a.logger.Debug(log.AuthorizationEndpointLog(r.URL.Path, log.InvalidMaxAge, map[string]string{ "max_age": mas, }, "'max_age' is less than minimum.")) rh.Error(ruri, "invalid_request", fmt.Sprintf("'max_age' should be greater than %d", a.policy.MinMaxAge-1), state) return false } if ma > a.policy.MaxMaxAge { a.logger.Debug(log.AuthorizationEndpointLog(r.URL.Path, log.InvalidMaxAge, map[string]string{ "max_age": mas, }, "'max_age' is greater than maximum.")) rh.Error(ruri, "invalid_request", fmt.Sprintf("'max_age' should be less than %d", a.policy.MaxMaxAge+1), state) return false } } prmpt := "" p := r.FormValue("prompt") if p != "" { if prompt.Validate(p) { prmpt = p } else { a.logger.Debug(log.AuthorizationEndpointLog(r.URL.Path, log.InvalidPrompt, map[string]string{ "prompt": p, }, "unknown 'prompt' is set.")) rh.Error(ruri, "invalid_request", fmt.Sprintf("invalid 'prompt': '%s'", p), state) return false } } else { a.logger.Debug(log.AuthorizationEndpointLog(r.URL.Path, log.MissingParam, map[string]string{ "param": "prompt", }, "'prompt' not found.")) } scp := r.FormValue("scope") if scope.IncludeOfflineAccess(scp) { if f.Type == flow.Implicit || !prompt.IncludeConsent(prmpt) { a.logger.Debug(log.AuthorizationEndpointLog(r.URL.Path, log.InvalidScope, map[string]string{ "scope": "offline_access", }, "'offline_access' shouldn't be set with implicit-flow or without-consent. ignore.")) scp = scope.RemoveOfflineAccess(scp) } else if !a.policy.AllowEmptyScope { scp_for_check := scope.RemoveOpenID(scp) scp_for_check = scope.RemoveOfflineAccess(scp_for_check) if len(scp_for_check) == 0 { a.logger.Debug(log.AuthorizationEndpointLog(r.URL.Path, log.InvalidScope, map[string]string{ "scope": "offline_access", }, "'offline_access' should be set with other scope except for 'openid'.")) rh.Error(ruri, "invalid_request", "when you request 'offline_access' scope, you should set other scope except for 'openid'", state) return false } } } if scp == "" && !a.policy.AllowEmptyScope { a.logger.Debug(log.AuthorizationEndpointLog(r.URL.Path, log.InvalidScope, map[string]string{}, "'scope' shouldn't be empty")) rh.Error(ruri, "invalid_request", "missing 'scope'", state) return false } if f.RequireIdToken && !scope.IncludeOpenID(scp) { a.logger.Debug(log.AuthorizationEndpointLog(r.URL.Path, log.InvalidScope, map[string]string{ "response_type": rt, "scope": scp, }, "'scope' should include 'openid' for this 'response_type'.")) rh.Error(ruri, "invalid_request", fmt.Sprintf("'response_type:%s' requires id_token, but 'scope' doesn't include 'openid'", rt), state) return false } if !clnt.CanUseScope(f.Type, scp) { a.logger.Debug(log.AuthorizationEndpointLog(r.URL.Path, log.InvalidScope, map[string]string{ "scope": scp, "client_id": cid, }, "this 'scope' is not allowed for this client")) rh.Error(ruri, "invalid_scope", "", state) return false } n := r.FormValue("nonce") if f.Type != flow.AuthorizationCode && scope.IncludeOpenID(scp) && f.RequireIdToken && n == "" { a.logger.Debug(log.AuthorizationEndpointLog(r.URL.Path, log.MissingParam, map[string]string{ "param": "nonce", "response_type": rt, }, "'nonce' is required for this 'response_type'.")) rh.Error(ruri, "invalid_request", fmt.Sprintf("'response_type:%s' requires 'nonce' parameter", rt), state) return false } if n != "" && len(n) > a.policy.MaxNonceLength { a.logger.Debug(log.AuthorizationEndpointLog(r.URL.Path, log.InvalidNonce, map[string]string{ "nonce": n, }, "length of 'nonce' is too long.")) rh.Error(ruri, "invalid_request", fmt.Sprintf("length of 'nonce' should be less than %d", a.policy.MaxNonceLength+1), state) return false } verifier := r.FormValue("code_verifier") if verifier != "" && len(verifier) > a.policy.MaxCodeVerifierLength { a.logger.Debug(log.AuthorizationEndpointLog(r.URL.Path, log.InvalidCodeVerifier, map[string]string{ "code_verifier": verifier, }, "length of 'code_verifier' is too long.")) rh.Error(ruri, "invalid_request", fmt.Sprintf("length of 'code_verifier' should be less than %d", a.policy.MaxCodeVerifierLength+1), state) return false } locales := r.FormValue("ui_locales") locale, err := callbacks.ChooseLocale(locales) if err != nil { a.logger.Error(log.AuthorizationEndpointLog(r.URL.Path, log.InterfaceError, map[string]string{ "method": "ChooseLocale", }, err.Error())) rh.Error(ruri, "server_error", "", state) return false } req := &authorization.Request{ Flow: f, ClientId: cid, RedirectURI: ruri, Scope: scp, ResponseMode: rmode, State: state, Nonce: n, Display: display, Prompt: prmpt, MaxAge: int64(ma), UILocale: locale, CodeVerifier: verifier, IdTokenHint: r.FormValue("id_token_hint"), LoginHint: r.FormValue("login_hint"), } if req.Prompt == prompt.None { policy := clnt.GetNonePromptPolicy() switch policy { case prompt.NonePromptPolicyForbidden: a.logger.Debug(log.AuthorizationEndpointLog(r.URL.Path, log.InvalidPrompt, map[string]string{ "prompt": "none", }, "this 'prompt' not supported")) rh.Error(ruri, "interaction_required", "not allowed to use 'prompt:none'", state) return false case prompt.NonePromptPolicyAllowWithLoginSession: isLoginSession, err := callbacks.ConfirmLoginSession() if err != nil { a.logger.Error(log.AuthorizationEndpointLog(r.URL.Path, log.InterfaceError, map[string]string{ "method": "ConfirmLoginSession", }, err.Error())) rh.Error(ruri, "server_error", "", state) return false } if !isLoginSession { rh.Error(ruri, "login_required", "", state) return false } uid, err := callbacks.GetLoginUserId() if err != nil { a.logger.Error(log.AuthorizationEndpointLog(r.URL.Path, log.InterfaceError, map[string]string{ "method": "GetLoginUserId", }, err.Error())) rh.Error(ruri, "server_error", "", state) return false } info, serr := a.di.FindAuthInfoByUserIdAndClientId(uid, req.ClientId) if serr != nil { if serr.Type() == bridge.ErrUnsupported { rh.Error(ruri, "server_error", "", state) return false } else if serr.Type() == bridge.ErrServerError { rh.Error(ruri, "server_error", "", state) return false } else { // not found auth info rh.Error(ruri, "consent_required", "", state) return false } } else { if info == nil { rh.Error(ruri, "server_error", "", state) return false } if info.IsActive() && scope.Same(info.GetScope(), req.Scope) && info.GetAuthorizedAt()+int64(a.policy.ConsentOmissionPeriod) > a.currentTime().Unix() { return a.complete(callbacks, r, rh, info, req) } else { rh.Error(ruri, "consent_required", "", state) return false } } case prompt.NonePromptPolicyAllowIfLoginHintMatched: if req.LoginHint == "" { rh.Error(ruri, "invalid_request", "in case you pass 'none' for 'prompt', 'login_hint' is required.", state) return false } isLoginSession, err := callbacks.ConfirmLoginSession() if err != nil { a.logger.Error(log.AuthorizationEndpointLog(r.URL.Path, log.InterfaceError, map[string]string{ "method": "ConfirmLoginSession", }, err.Error())) rh.Error(ruri, "server_error", "", state) return false } if !isLoginSession { rh.Error(ruri, "login_required", "", state) return false } matched, err := callbacks.LoginUserIsMatchedToSubject(req.LoginHint) if err != nil { a.logger.Error(log.AuthorizationEndpointLog(r.URL.Path, log.InterfaceError, map[string]string{ "method": "LoginUserIsMatchedToHint", }, err.Error())) rh.Error(ruri, "server_error", "", state) return false } if !matched { rh.Error(ruri, "invalid_request", "'login_hint' doesn't match to current login user", state) return false } uid, err := callbacks.GetLoginUserId() if err != nil { a.logger.Error(log.AuthorizationEndpointLog(r.URL.Path, log.InterfaceError, map[string]string{ "method": "GetLoginUserId", }, err.Error())) rh.Error(ruri, "server_error", "", state) return false } info, serr := a.di.FindAuthInfoByUserIdAndClientId(uid, req.ClientId) if serr != nil { if serr.Type() == bridge.ErrUnsupported { rh.Error(ruri, "server_error", "", state) return false } else if serr.Type() == bridge.ErrServerError { rh.Error(ruri, "server_error", "", state) return false } else { // not found auth info rh.Error(ruri, "consent_required", "", state) return false } } else { if info == nil { rh.Error(ruri, "server_error", "", state) return false } if info.IsActive() && scope.Same(info.GetScope(), req.Scope) && info.GetAuthorizedAt()+int64(a.policy.ConsentOmissionPeriod) > a.currentTime().Unix() { return a.complete(callbacks, r, rh, info, req) } else { rh.Error(ruri, "consent_required", "", state) return false } } case prompt.NonePromptPolicyAllowIfIdTokenHintMatched: if req.IdTokenHint == "" { rh.Error(ruri, "invalid_request", "in case you pass 'none' for 'prompt', 'id_token_hint' is required.", state) return false } t, jwt_err := jwt.Parse(req.IdTokenHint, func(t *jwt.Token) (interface{}, error) { return clnt.GetIdTokenKey(), nil }) if jwt_err != nil { rh.Error(ruri, "invalid_request", "'id_token_hint' is invalid.", state) return false } if !t.Valid { rh.Error(ruri, "invalid_request", "'id_token_hint' is invalid.", state) return false } exp_exists := false claims := t.Claims.(jwt.MapClaims) switch num := claims["exp"].(type) { case json.Number: if _, err = num.Int64(); err == nil { exp_exists = true } case float64: exp_exists = true } if !exp_exists { rh.Error(ruri, "invalid_request", "'exp' not found in 'id_token_hint'.", state) return false } sub := "" if found, ok := claims["sub"].(string); ok { sub = found } else { rh.Error(ruri, "invalid_request", "'sub' not found in 'id_token_hint'.", state) return false } matched, err := callbacks.LoginUserIsMatchedToSubject(sub) if err != nil { a.logger.Error(log.AuthorizationEndpointLog(r.URL.Path, log.InterfaceError, map[string]string{ "method": "LoginUserIsMatchedToHint", }, err.Error())) rh.Error(ruri, "server_error", "", state) return false } if !matched { rh.Error(ruri, "invalid_request", "'id_token_hint' doesn't match to current login user", state) return false } uid, err := callbacks.GetLoginUserId() if err != nil { a.logger.Error(log.AuthorizationEndpointLog(r.URL.Path, log.InterfaceError, map[string]string{ "method": "GetLoginUserId", }, err.Error())) rh.Error(ruri, "server_error", "", state) return false } info, serr := a.di.FindAuthInfoByUserIdAndClientId(uid, req.ClientId) if serr != nil { if serr.Type() == bridge.ErrUnsupported { rh.Error(ruri, "server_error", "", state) return false } else if serr.Type() == bridge.ErrServerError { rh.Error(ruri, "server_error", "", state) return false } else { // not found auth info rh.Error(ruri, "consent_required", "", state) return false } } else { if info == nil { rh.Error(ruri, "server_error", "", state) return false } if info.IsActive() && scope.Same(info.GetScope(), req.Scope) && info.GetAuthorizedAt()+int64(a.policy.ConsentOmissionPeriod) > a.currentTime().Unix() { return a.complete(callbacks, r, rh, info, req) } else { rh.Error(ruri, "consent_required", "", state) return false } } } } else { isLoginSession, err := callbacks.ConfirmLoginSession() if err != nil { a.logger.Error(log.AuthorizationEndpointLog(r.URL.Path, log.InterfaceError, map[string]string{ "method": "ConfirmLoginSession", }, err.Error())) rh.Error(ruri, "server_error", "", state) return false } if !isLoginSession { a.logger.Debug(log.AuthorizationEndpointLog(r.URL.Path, log.LoginRequired, map[string]string{}, "this is non-signed-in-session, so, show login page.")) err = callbacks.ShowLoginScreen(req) if err != nil { a.logger.Error(log.AuthorizationEndpointLog(r.URL.Path, log.InterfaceError, map[string]string{ "method": "ShowLoginScreen", }, err.Error())) rh.Error(ruri, "server_error", "", state) return false } return false } } if prompt.IncludeLogin(req.Prompt) { isFromLogin, err := callbacks.RequestIsFromLogin() if err != nil { a.logger.Error(log.AuthorizationEndpointLog(r.URL.Path, log.InterfaceError, map[string]string{ "method": "RequestIsFromLogin", }, err.Error())) rh.Error(ruri, "server_error", "", state) return false } if !isFromLogin { a.logger.Debug(log.AuthorizationEndpointLog(r.URL.Path, log.LoginRequired, map[string]string{ "prompt": req.Prompt, }, "force-login is required by 'prompt'")) callbacks.ShowLoginScreen(req) return false } } authTime, err := callbacks.GetAuthTime() if err != nil { a.logger.Error(log.AuthorizationEndpointLog(r.URL.Path, log.InterfaceError, map[string]string{ "method": "GetAuthTime", }, err.Error())) rh.Error(ruri, "server_error", "", state) return false } if req.MaxAge > 0 { age := a.currentTime().Unix() - authTime if req.MaxAge < age { a.logger.Debug(log.AuthorizationEndpointLog(r.URL.Path, log.LoginRequired, map[string]string{ "max_age": mas, }, "'auth_time' is over 'max_age', so, show login page.")) callbacks.ShowLoginScreen(req) return false } } if !prompt.IncludeConsent(req.Prompt) { policy := clnt.GetNoConsentPromptPolicy() switch policy { case prompt.NoConsentPromptPolicyOmitConsentIfCan: uid, err := callbacks.GetLoginUserId() if err != nil { a.logger.Error(log.AuthorizationEndpointLog(r.URL.Path, log.InterfaceError, map[string]string{ "method": "GetLoginUserId", }, err.Error())) rh.Error(ruri, "server_error", "", state) return false } info, serr := a.di.FindAuthInfoByUserIdAndClientId(uid, req.ClientId) if serr != nil { if serr.Type() == bridge.ErrUnsupported { rh.Error(ruri, "server_error", "", state) return false } else if serr.Type() == bridge.ErrServerError { rh.Error(ruri, "server_error", "", state) return false } } else { if info == nil { rh.Error(ruri, "server_error", "", state) return false } if info.IsActive() && scope.Same(info.GetScope(), req.Scope) && info.GetAuthorizedAt()+int64(a.policy.ConsentOmissionPeriod) > a.currentTime().Unix() { return a.complete(callbacks, r, rh, info, req) } } case prompt.NoConsentPromptPolicyForceConsent: } } err = callbacks.ShowConsentScreen(clnt, req) if err != nil { a.logger.Error(log.AuthorizationEndpointLog(r.URL.Path, log.InterfaceError, map[string]string{ "method": "ShowConsentScreen", }, err.Error())) rh.Error(ruri, "server_error", "", state) return false } return true } func (a *AuthorizationEndpoint) CancelRequest(w http.ResponseWriter, r *http.Request, callbacks bridge.AuthorizationCallbacks) bool { req, err := callbacks.Continue() if err != nil { a.logger.Error(log.AuthorizationEndpointLog(r.URL.Path, log.InterfaceError, map[string]string{ "method": "Continue", }, err.Error())) return false } rh := authorization.ResponseHandlerForMode(req.ResponseMode, w, r) rh.Error(req.RedirectURI, "access_denied", "", req.State) return true } func (a *AuthorizationEndpoint) CompleteRequest(w http.ResponseWriter, r *http.Request, callbacks bridge.AuthorizationCallbacks) bool { req, err := callbacks.Continue() if err != nil { a.logger.Error(log.AuthorizationEndpointLog(r.URL.Path, log.InterfaceError, map[string]string{ "method": "Continue", }, err.Error())) return false } rh := authorization.ResponseHandlerForMode(req.ResponseMode, w, r) uid, err := callbacks.GetLoginUserId() if err != nil { a.logger.Error(log.AuthorizationEndpointLog(r.URL.Path, log.InterfaceError, map[string]string{ "method": "GetLoginUserId", }, err.Error())) rh.Error(req.RedirectURI, "server_error", "", req.State) return false } info, serr := a.di.CreateOrUpdateAuthInfo(uid, req.ClientId, req.Scope) if serr != nil { rh.Error(req.RedirectURI, "server_error", "", req.State) return false } return a.complete(callbacks, r, rh, info, req) } func (a *AuthorizationEndpoint) complete( callbacks bridge.AuthorizationCallbacks, r *http.Request, rh authorization.ResponseHandler, info bridge.AuthInfo, req *authorization.Request) bool { switch req.Flow.Type { case flow.AuthorizationCode: return a.completeAuthorizationCodeFlowRequest(callbacks, r, rh, info, req) case flow.Implicit: return a.completeImplicitFlowRequest(callbacks, r, rh, info, req) case flow.Hybrid: return a.completeHybridFlowRequest(callbacks, r, rh, info, req) } return false } func (a *AuthorizationEndpoint) completeAuthorizationCodeFlowRequest( callbacks bridge.AuthorizationCallbacks, r *http.Request, rh authorization.ResponseHandler, info bridge.AuthInfo, req *authorization.Request) bool { code, err := callbacks.CreateAuthorizationCode() if err != nil { a.logger.Error(log.AuthorizationEndpointLog(r.URL.Path, log.InterfaceError, map[string]string{ "method": "CreateAuthorizationCode", }, err.Error())) rh.Error(req.RedirectURI, "server_error", "", req.State) return false } authTime, err := callbacks.GetAuthTime() if err != nil { a.logger.Error(log.AuthorizationEndpointLog(r.URL.Path, log.InterfaceError, map[string]string{ "method": "GetAuthTime", }, err.Error())) rh.Error(req.RedirectURI, "server_error", "", req.State) return false } serr := a.di.CreateAuthSession(info, req.ToSession(code, int64(a.policy.AuthSessionExpiresIn), authTime)) if serr != nil { rh.Error(req.RedirectURI, "server_error", "", req.State) return false } params := make(map[string]string) params["code"] = code if req.State != "" { params["state"] = req.State } rh.Success(req.RedirectURI, params) return true } func (a *AuthorizationEndpoint) completeImplicitFlowRequest( callbacks bridge.AuthorizationCallbacks, r *http.Request, rh authorization.ResponseHandler, info bridge.AuthInfo, req *authorization.Request) bool { clnt, serr := a.di.FindClientById(req.ClientId) if serr != nil { rh.Error(req.RedirectURI, "server_error", "", req.State) return false } params := make(map[string]string) if req.State != "" { params["state"] = req.State } if req.Scope != "" { params["scope"] = req.Scope } at := "" if req.Flow.RequireAccessToken { t, serr := a.di.CreateOAuthToken(info, false) if serr != nil { rh.Error(req.RedirectURI, "server_error", "", req.State) return false } at = t.GetAccessToken() params["access_token"] = at params["token_type"] = "bearer" params["rexpires_in"] = fmt.Sprintf("%d", t.GetAccessTokenExpiresIn()) } authTime, err := callbacks.GetAuthTime() if err != nil { a.logger.Error(log.AuthorizationEndpointLog(r.URL.Path, log.InterfaceError, map[string]string{ "method": "GetAuthTime", }, err.Error())) rh.Error(req.RedirectURI, "server_error", "", req.State) return false } if req.Flow.RequireIdToken { idt, err := id_token.GenForImplicit( clnt.GetIdTokenAlg(), // id_token signing algorithm clnt.GetIdTokenKey(), // id_token signing key clnt.GetIdTokenKeyId(), // id_token signing key-id a.di.Issuer(), // issuer info.GetClientId(), // clientId info.GetSubject(), // subject req.Nonce, // nonce int64(a.policy.IdTokenExpiresIn), // expiresIn, authTime, // authTime at, // access token a.currentTime(), ) if err != nil { rh.Error(req.RedirectURI, "server_error", "", req.State) return false } params["id_token"] = idt } rh.Success(req.RedirectURI, params) return true } func (a *AuthorizationEndpoint) completeHybridFlowRequest( callbacks bridge.AuthorizationCallbacks, r *http.Request, rh authorization.ResponseHandler, info bridge.AuthInfo, req *authorization.Request) bool { code, err := callbacks.CreateAuthorizationCode() if err != nil { a.logger.Error(log.AuthorizationEndpointLog(r.URL.Path, log.InterfaceError, map[string]string{ "method": "CreateAuthorizationCode", }, err.Error())) rh.Error(req.RedirectURI, "server_error", "", req.State) return false } authTime, err := callbacks.GetAuthTime() if err != nil { a.logger.Error(log.AuthorizationEndpointLog(r.URL.Path, log.InterfaceError, map[string]string{ "method": "GetAuthTime", }, err.Error())) rh.Error(req.RedirectURI, "server_error", "", req.State) return false } serr := a.di.CreateAuthSession(info, req.ToSession(code, int64(a.policy.AuthSessionExpiresIn), authTime)) if serr != nil { rh.Error(req.RedirectURI, "server_error", "", req.State) return false } clnt, serr := a.di.FindClientById(req.ClientId) if serr != nil { rh.Error(req.RedirectURI, "server_error", "", req.State) return false } params := make(map[string]string) params["code"] = code if req.State != "" { params["state"] = req.State } if req.Scope != "" { params["scope"] = req.Scope } at := "" if req.Flow.RequireAccessToken { t, serr := a.di.CreateOAuthToken(info, false) if serr != nil { rh.Error(req.RedirectURI, "server_error", "", req.State) return false } at = t.GetAccessToken() params["access_token"] = at params["token_type"] = "bearer" params["expires_in"] = fmt.Sprintf("%d", t.GetAccessTokenExpiresIn()) } if req.Flow.RequireIdToken { idt, err := id_token.GenForHybrid( clnt.GetIdTokenAlg(), // id_token signing algorithm clnt.GetIdTokenKey(), // id_token signing key clnt.GetIdTokenKeyId(), // id_token signing key-id a.di.Issuer(), // issuer info.GetClientId(), // clientId info.GetSubject(), // subject req.Nonce, // nonce int64(a.policy.IdTokenExpiresIn), // expiresIn, authTime, // authTime at, // access_token code, // code a.currentTime(), ) if err != nil { rh.Error(req.RedirectURI, "server_error", "", req.State) return false } params["id_token"] = idt } rh.Success(req.RedirectURI, params) return true }
package awsupload import ( "fmt" "log" "os" "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/ec2" "github.com/aws/aws-sdk-go/service/s3" "github.com/aws/aws-sdk-go/service/s3/s3manager" ) type AWS struct { uploader *s3manager.Uploader ec2 *ec2.EC2 s3 *s3.S3 } func New(region, accessKeyID, accessKey, sessionToken string) (*AWS, error) { // Session credentials creds := credentials.NewStaticCredentials(accessKeyID, accessKey, sessionToken) // Create a Session with a custom region sess, err := session.NewSession(&aws.Config{ Credentials: creds, Region: aws.String(region), }) if err != nil { return nil, err } return &AWS{ uploader: s3manager.NewUploader(sess), ec2: ec2.New(sess), s3: s3.New(sess), }, nil } func (a *AWS) Upload(filename, bucket, key string) (*s3manager.UploadOutput, error) { file, err := os.Open(filename) if err != nil { return nil, err } log.Printf("[AWS] 🚀 Uploading image to S3: %s/%s", bucket, key) return a.uploader.Upload( &s3manager.UploadInput{ Bucket: aws.String(bucket), Key: aws.String(key), Body: file, }, ) } // WaitUntilImportSnapshotCompleted uses the Amazon EC2 API operation // DescribeImportSnapshots to wait for a condition to be met before returning. // If the condition is not met within the max attempt window, an error will // be returned. func WaitUntilImportSnapshotTaskCompleted(c *ec2.EC2, input *ec2.DescribeImportSnapshotTasksInput) error { return WaitUntilImportSnapshotTaskCompletedWithContext(c, aws.BackgroundContext(), input) } // WaitUntilImportSnapshotCompletedWithContext is an extended version of // WaitUntilImportSnapshotCompleted. With the support for passing in a // context and options to configure the Waiter and the underlying request // options. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. // // NOTE(mhayden): The MaxAttempts is set to zero here so that we will keep // checking the status of the image import until it succeeds or fails. This // process can take anywhere from 5 to 60+ minutes depending on how quickly // AWS can import the snapshot. func WaitUntilImportSnapshotTaskCompletedWithContext(c *ec2.EC2, ctx aws.Context, input *ec2.DescribeImportSnapshotTasksInput, opts ...request.WaiterOption) error { w := request.Waiter{ Name: "WaitUntilImportSnapshotTaskCompleted", MaxAttempts: 0, Delay: request.ConstantWaiterDelay(15 * time.Second), Acceptors: []request.WaiterAcceptor{ { State: request.SuccessWaiterState, Matcher: request.PathAllWaiterMatch, Argument: "ImportSnapshotTasks[].SnapshotTaskDetail.Status", Expected: "completed", }, { State: request.FailureWaiterState, Matcher: request.PathAllWaiterMatch, Argument: "ImportSnapshotTasks[].SnapshotTaskDetail.Status", Expected: "deleted", }, }, Logger: c.Config.Logger, NewRequest: func(opts []request.Option) (*request.Request, error) { var inCpy *ec2.DescribeImportSnapshotTasksInput if input != nil { tmp := *input inCpy = &tmp } req, _ := c.DescribeImportSnapshotTasksRequest(inCpy) req.SetContext(ctx) req.ApplyOptions(opts...) return req, nil }, } w.ApplyOptions(opts...) return w.WaitWithContext(ctx) } // Register is a function that imports a snapshot, waits for the snapshot to // fully import, tags the snapshot, cleans up the image in S3, and registers // an AMI in AWS. func (a *AWS) Register(name, bucket, key string, shareWith []string, rpmArch string) (*string, error) { rpmArchToEC2Arch := map[string]string{ "x86_64": "x86_64", "aarch64": "arm64", } ec2Arch, validArch := rpmArchToEC2Arch[rpmArch] if !validArch { return nil, fmt.Errorf("ec2 doesn't support the following arch: %s", rpmArch) } log.Printf("[AWS] 📥 Importing snapshot from image: %s/%s", bucket, key) snapshotDescription := fmt.Sprintf("Image Builder AWS Import of %s", name) importTaskOutput, err := a.ec2.ImportSnapshot( &ec2.ImportSnapshotInput{ Description: aws.String(snapshotDescription), DiskContainer: &ec2.SnapshotDiskContainer{ UserBucket: &ec2.UserBucket{ S3Bucket: aws.String(bucket), S3Key: aws.String(key), }, }, }, ) if err != nil { log.Printf("[AWS] error importing snapshot: %s", err) return nil, err } log.Printf("[AWS] 🚚 Waiting for snapshot to finish importing: %s", *importTaskOutput.ImportTaskId) err = WaitUntilImportSnapshotTaskCompleted( a.ec2, &ec2.DescribeImportSnapshotTasksInput{ ImportTaskIds: []*string{ importTaskOutput.ImportTaskId, }, }, ) if err != nil { return nil, err } // we no longer need the object in s3, let's just delete it log.Printf("[AWS] 🧹 Deleting image from S3: %s/%s", bucket, key) _, err = a.s3.DeleteObject(&s3.DeleteObjectInput{ Bucket: aws.String(bucket), Key: aws.String(key), }) if err != nil { return nil, err } importOutput, err := a.ec2.DescribeImportSnapshotTasks( &ec2.DescribeImportSnapshotTasksInput{ ImportTaskIds: []*string{ importTaskOutput.ImportTaskId, }, }, ) if err != nil { return nil, err } snapshotID := importOutput.ImportSnapshotTasks[0].SnapshotTaskDetail.SnapshotId if len(shareWith) > 0 { log.Printf("[AWS] 🎥 Sharing ec2 snapshot") var userIds []*string for _, v := range shareWith { userIds = append(userIds, &v) } _, err := a.ec2.ModifySnapshotAttribute( &ec2.ModifySnapshotAttributeInput{ Attribute: aws.String("createVolumePermission"), OperationType: aws.String("add"), SnapshotId: snapshotID, UserIds: userIds, }, ) if err != nil { return nil, err } log.Println("[AWS] 📨 Shared ec2 snapshot") } // Tag the snapshot with the image name. req, _ := a.ec2.CreateTagsRequest( &ec2.CreateTagsInput{ Resources: []*string{snapshotID}, Tags: []*ec2.Tag{ { Key: aws.String("Name"), Value: aws.String(name), }, }, }, ) err = req.Send() if err != nil { return nil, err } log.Printf("[AWS] 📋 Registering AMI from imported snapshot: %s", *snapshotID) registerOutput, err := a.ec2.RegisterImage( &ec2.RegisterImageInput{ Architecture: aws.String(ec2Arch), VirtualizationType: aws.String("hvm"), Name: aws.String(name), RootDeviceName: aws.String("/dev/sda1"), EnaSupport: aws.Bool(true), BlockDeviceMappings: []*ec2.BlockDeviceMapping{ { DeviceName: aws.String("/dev/sda1"), Ebs: &ec2.EbsBlockDevice{ SnapshotId: snapshotID, }, }, }, }, ) if err != nil { return nil, err } log.Printf("[AWS] 🎉 AMI registered: %s", *registerOutput.ImageId) // Tag the image with the image name. req, _ = a.ec2.CreateTagsRequest( &ec2.CreateTagsInput{ Resources: []*string{registerOutput.ImageId}, Tags: []*ec2.Tag{ { Key: aws.String("Name"), Value: aws.String(name), }, }, }, ) err = req.Send() if err != nil { return nil, err } if len(shareWith) > 0 { log.Println("[AWS] 💿 Sharing ec2 AMI") var launchPerms []*ec2.LaunchPermission for _, id := range shareWith { launchPerms = append(launchPerms, &ec2.LaunchPermission{ UserId: &id, }) } _, err := a.ec2.ModifyImageAttribute( &ec2.ModifyImageAttributeInput{ ImageId: registerOutput.ImageId, LaunchPermission: &ec2.LaunchPermissionModifications{ Add: launchPerms, }, }, ) if err != nil { return nil, err } log.Println("[AWS] 💿 Shared AMI") } return registerOutput.ImageId, nil } func (a *AWS) S3ObjectPresignedURL(bucket, objectKey string) (string, error) { log.Printf("[AWS] 📋 Generating Presigned URL for S3 object %s/%s", bucket, objectKey) req, _ := a.s3.GetObjectRequest(&s3.GetObjectInput{ Bucket: aws.String(bucket), Key: aws.String(objectKey), }) url, err := req.Presign(7 * 24 * time.Hour) // maximum allowed if err != nil { return "", err } log.Print("[AWS] 🎉 S3 Presigned URL ready") return url, nil }
/* * randmat: random number generation * * input: * nrows, ncols: the number of rows and columns * s: the seed * * output: * martix: a nrows x ncols integer matrix * */ package main import ( "flag" "fmt" "runtime" "bufio" "os" ) // #include <time.h> // #include <stdio.h> import "C" type ByteMatrix struct { Rows, Cols int array []byte } func NewByteMatrix(r, c int) *ByteMatrix { return &ByteMatrix{r, c, make([]byte, r*c)} } func (m *ByteMatrix) Row(i int) []byte { return m.array[i*m.Cols : (i+1)*m.Cols] } const ( LCG_A = 1664525 LCG_C = 1013904223 ) var ( is_bench = flag.Bool("is_bench", false, "") ) func randmat(nrows, ncols int, s uint32) *ByteMatrix { matrix := NewByteMatrix(nrows, ncols) work := make(chan int) go func() { for i := 0; i < nrows; i++ { work <- i } close(work) }() done := make(chan bool) NP := runtime.GOMAXPROCS(0) for i := 0; i < NP; i++ { go func() { for i := range work { seed := s + uint32(i) row := matrix.Row(i) for j := range row { seed = LCG_A*seed + LCG_C row[j] = byte(seed%100) % 100 } } done <- true }() } for i := 0; i < NP; i++ { <-done } return matrix } func main() { flag.Parse() var nrows, ncols int var seed uint32 fmt.Scan(&nrows) fmt.Scan(&ncols) fmt.Scan(&seed) var start, stop C.struct_timespec var accum C.double if( C.clock_gettime( C.CLOCK_MONOTONIC_RAW, &start) == -1 ) { C.perror( C.CString("clock gettime error 1") ); return } matrix := randmat(nrows, ncols, seed) if( C.clock_gettime( C.CLOCK_MONOTONIC_RAW, &stop) == -1 ) { C.perror( C.CString("clock gettime error 1") ); return } accum = C.double( C.long(stop.tv_sec) - C.long(start.tv_sec) ) + C.double(( C.long(stop.tv_nsec) - C.long(start.tv_nsec))) / C.double(1e9); file, err := os.OpenFile("./measurements.txt", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666) if err != nil { fmt.Println("File does not exists or cannot be created") os.Exit(1) } w := bufio.NewWriter(file) // Lang, Problem, rows, cols, thresh, winnow_nelts, jobs, time fmt.Fprintf(w, "Go ,Randmat,%5d,%5d, , ,%2d,%.9f,isBench:%t\n", nrows, ncols, runtime.GOMAXPROCS(0), accum, *is_bench ) w.Flush() file.Close() if !*is_bench { for i := 0; i < nrows; i++ { row := matrix.Row(i) for j := range row { fmt.Printf("%d ", row[j]) } fmt.Printf("\n") } fmt.Printf("\n") } }
package utils import ( "crypto/rand" "fmt" "io" "golang.org/x/crypto/bcrypt" ) // HashPassword - hashes given password string func HashPassword(input string) (string, error) { bytes, err := bcrypt.GenerateFromPassword([]byte(input), 15) return string(bytes), err } // CheckPasswordHash - Checks password has func CheckPasswordHash(password, hash string) bool { err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) return err == nil } // GenerateNewGUID - generates new GUID func GenerateNewGUID() (string, error) { guid := make([]byte, 16) n, err := io.ReadFull(rand.Reader, guid) if n != len(guid) || err != nil { return "AAAAAAAAAA", err } // variant bits; RFC section 4.1.1 guid[8] = guid[8]&^0xc0 | 0x80 // version 4 (pseudo-random); RFC section 4.1.3 guid[6] = guid[6]&^0xf0 | 0x40 return fmt.Sprintf("%x-%x-%x-%x-%x", guid[0:4], guid[4:6], guid[6:8], guid[8:10], guid[10:]), nil }
package day6 import ( "fmt" "github.com/kdeberk/advent-of-code/2019/internal/utils" "strings" ) type node struct { name string parent *node children []*node depth int } func makeNode(name string) *node { return &node{name, nil, []*node{}, 0} } func (self *node) addChild(child *node) { child.parent = self self.children = append(self.children, child) } func (self *node) setDepth(depth int) { self.depth = depth for _, child := range self.children { child.setDepth(depth + 1) } } type tree struct { nodes map[string]*node } func (self *tree) getNode(name string) *node { node, ok := self.nodes[name] if !ok { node = makeNode(name) self.nodes[name] = node } return node } func readTree(filename string) (tree, error) { a_tree := tree{map[string]*node{}} lines, err := utils.ReadStrings(filename, utils.IsNewline) if err != nil { return a_tree, err } for _, line := range lines { parts := strings.Split(line, ")") if 2 != len(parts) { return a_tree, fmt.Errorf("Misformatted line: %s", line) } parent := a_tree.getNode(parts[0]) parent.addChild(a_tree.getNode(parts[1])) } a_tree.getNode("COM").setDepth(0) return a_tree, nil }
package TF2RconWrapper import ( "github.com/stretchr/testify/assert" "testing" ) var logs []string = []string{ `"Sk1LL0<2><[U:1:198288660]><Unassigned>" joined team "Red"`, `"Sk1LL0<2><[U:1:198288660]><Red>" changed role to "scout"`, `"Sk1LL0<2><[U:1:198288660]><Red>" changed role to "soldier"`, `"Sk1LL0<2><[U:1:198288660]><Red>" say "hello gringos"`, `"Sk1LL0<2><[U:1:198288660]><Red>" say_team "ufo porno"`, `"Sk1LL0<2><[U:1:198288660]><Red>" changed role to "sniper"`, `"Sk1LL0<2><[U:1:198288660]><Red>" joined team "Blue"`, `"Sk1LL0<2><[U:1:198288660]><Blue>" changed role to "medic"`, `World triggered "Game_Over" reason "Reached Win Difference Limit"`, } func TestParse(t *testing.T) { for i := range logs { m := parse(logs[i]) switch i { // 0 = changed team case 0: assert.Equal(t, m.Type, PlayerChangedTeam) assert.Equal(t, m.Data.Team, "Unassigned") assert.Equal(t, m.Data.NewTeam, "Red") assert.Equal(t, m.Data.Username, "Sk1LL0") assert.Equal(t, m.Data.UserId, "2") assert.Equal(t, m.Data.SteamId, "[U:1:198288660]") // 1 = changed class case 1: assert.Equal(t, m.Type, PlayerChangedClass) assert.Equal(t, m.Data.Class, "scout") // 2 = changed class case 2: assert.Equal(t, m.Type, PlayerChangedClass) assert.Equal(t, m.Data.Class, "soldier") // 3 = global message case 3: assert.Equal(t, m.Type, PlayerGlobalMessage) assert.Equal(t, m.Data.Team, "Red") assert.Equal(t, m.Data.Text, "hello gringos") // 4 = team message case 4: assert.Equal(t, m.Type, PlayerTeamMessage) assert.Equal(t, m.Data.Text, "ufo porno") // 5 = changed class case 5: assert.Equal(t, m.Type, PlayerChangedClass) assert.Equal(t, m.Data.Class, "sniper") // 6 = changed team case 6: assert.Equal(t, m.Type, PlayerChangedTeam) assert.Equal(t, m.Data.Team, "Red") assert.Equal(t, m.Data.NewTeam, "Blue") // 7 = changed class case 7: assert.Equal(t, m.Type, PlayerChangedClass) assert.Equal(t, m.Data.Team, "Blue") assert.Equal(t, m.Data.Class, "medic") // 8 = game over case 8: assert.Equal(t, m.Type, WorldGameOver) } } }
package compiler import ( "os" "strings" "github.com/go-task/task/v2/internal/taskfile" ) // GetEnviron the all return all environment variables encapsulated on a // taskfile.Vars func GetEnviron() taskfile.Vars { var ( env = os.Environ() m = make(taskfile.Vars, len(env)) ) for _, e := range env { keyVal := strings.SplitN(e, "=", 2) key, val := keyVal[0], keyVal[1] m[key] = taskfile.Var{Static: val} } return m }
// Copyright © 2018 Inanc Gumus // Learn Go Programming Course // License: https://creativecommons.org/licenses/by-nc-sa/4.0/ // // For more tutorials : https://learngoprogramming.com // In-person training : https://www.linkedin.com/in/inancgumus/ // Follow me on twitter: https://twitter.com/inancgumus package main import "fmt" func main() { // When argument to len is a constant, len can be used // while initializing a constant // // Here, "Hello" is a constant. const max int = len("Hello") fmt.Println(max) }
/* # -*- coding: utf-8 -*- # @Author : joker # @Time : 2020-11-13 09:32 # @File : lt_978_Longest_Turbulent_Subarray.go # @Description : # @Attention : */ package slide_window import ( "fmt" "testing" ) func Test_maxTurbulenceSize(t *testing.T) { // A := []int{9, 4, 2, 10, 7, 8, 8, 1, 9} A := []int{9, 4, 2, 10, 7, 8, 8, 1, 9} size := maxTurbulenceSize(A) fmt.Println(size) }
package rc import ( "bytes" "encoding/json" "fmt" "io/ioutil" "net/http" "os" "strings" "github.com/ncw/rclone/cmd" "github.com/ncw/rclone/fs" "github.com/ncw/rclone/fs/fshttp" "github.com/ncw/rclone/fs/rc" "github.com/pkg/errors" "github.com/spf13/cobra" "github.com/spf13/pflag" ) var ( noOutput = false url = "http://localhost:5572/" ) func init() { cmd.Root.AddCommand(commandDefintion) commandDefintion.Flags().BoolVarP(&noOutput, "no-output", "", noOutput, "If set don't output the JSON result.") commandDefintion.Flags().StringVarP(&url, "url", "", url, "URL to connect to rclone remote control.") } var commandDefintion = &cobra.Command{ Use: "rc commands parameter", Short: `Run a command against a running rclone.`, Long: ` This runs a command against a running rclone. By default it will use that specified in the --rc-addr command. Arguments should be passed in as parameter=value. The result will be returned as a JSON object by default. Use "rclone rc" to see a list of all possible commands.`, Run: func(command *cobra.Command, args []string) { cmd.CheckArgs(0, 1E9, command, args) cmd.Run(false, false, command, func() error { if len(args) == 0 { return list() } return run(args) }) }, } // do a call from (path, in) to (out, err). // // if err is set, out may be a valid error return or it may be nil func doCall(path string, in rc.Params) (out rc.Params, err error) { // Do HTTP request client := fshttp.NewClient(fs.Config) url := url // set the user use --rc-addr as well as --url if rcAddrFlag := pflag.Lookup("rc-addr"); rcAddrFlag != nil && rcAddrFlag.Changed { url = rcAddrFlag.Value.String() if strings.HasPrefix(url, ":") { url = "localhost" + url } url = "http://" + url + "/" } if !strings.HasSuffix(url, "/") { url += "/" } url += path data, err := json.Marshal(in) if err != nil { return nil, errors.Wrap(err, "failed to encode JSON") } resp, err := client.Post(url, "application/json", bytes.NewBuffer(data)) if err != nil { return nil, errors.Wrap(err, "connection failed") } defer fs.CheckClose(resp.Body, &err) if resp.StatusCode != http.StatusOK { var body []byte body, err = ioutil.ReadAll(resp.Body) var bodyString string if err == nil { bodyString = string(body) } else { bodyString = err.Error() } bodyString = strings.TrimSpace(bodyString) return nil, errors.Errorf("Failed to read rc response: %s: %s", resp.Status, bodyString) } // Parse output out = make(rc.Params) err = json.NewDecoder(resp.Body).Decode(&out) if err != nil { return nil, errors.Wrap(err, "failed to decode JSON") } // Check we got 200 OK if resp.StatusCode != http.StatusOK { err = errors.Errorf("operation %q failed: %v", path, out["error"]) } return out, err } // Run the remote control command passed in func run(args []string) (err error) { path := strings.Trim(args[0], "/") // parse input in := make(rc.Params) for _, param := range args[1:] { equals := strings.IndexRune(param, '=') if equals < 0 { return errors.Errorf("No '=' found in parameter %q", param) } key, value := param[:equals], param[equals+1:] in[key] = value } // Do the call out, callErr := doCall(path, in) // Write the JSON blob to stdout if required if out != nil && !noOutput { err := rc.WriteJSON(os.Stdout, out) if err != nil { return errors.Wrap(err, "failed to output JSON") } } return callErr } // List the available commands to stdout func list() error { list, err := doCall("rc/list", nil) if err != nil { return errors.Wrap(err, "failed to list") } commands, ok := list["commands"].([]interface{}) if !ok { return errors.New("bad JSON") } for _, command := range commands { info, ok := command.(map[string]interface{}) if !ok { return errors.New("bad JSON") } fmt.Printf("### %s: %s\n\n", info["Path"], info["Title"]) fmt.Printf("%s\n\n", info["Help"]) } return nil }
/* * Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you 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 ( "fmt" "github.com/AlecAivazis/survey/v2" "github.com/mbndr/figlet4go" "github.com/spf13/cobra" "log" "net/url" ) var createSPCmd = &cobra.Command{ Use: "application", Short: "Create a service provider", Long: `This will help you to create the service providers`, Run: func(cmd *cobra.Command, args []string) { create() },} var qs = []*survey.Question{ { Name: "question", Prompt: &survey.Select{ Message: "Select the option to move on:", Options: []string{"Add application", "Get List", "Exit"}, Default: "Add application", }, }, } var types = []*survey.Question{ { Name: "type", Prompt: &survey.Select{ Message: "Select the configuration type:", Options: []string{"Basic application", "oauth"}, Default: "Basic application", }, }, } var details = []*survey.Question{ { Name: "spName", Prompt: &survey.Input{Message: "Enter service provider name:"}, Validate: survey.Required, Transform: survey.Title, }, { Name: "spDescription", Prompt: &survey.Input{Message: "Enter service provider description:"}, Validate: survey.Required, }, } var oauthDetails = []*survey.Question{ { Name: "oauthName", Prompt: &survey.Input{Message: "Enter Oauth application name:"}, Validate: survey.Required, Transform: survey.Title, }, { Name: "callbackURls", Prompt: &survey.Input{Message: "Enter callbackURLs(not mandatory):"}, }, } func init() { rootCmd.AddCommand(createSPCmd) } func create() { answers := struct { Selected string `survey:"question"` Name string `survey:"spName"` Description string `survey:"spDescription"` }{} answersOfType := struct { Selected string `survey:"type"` }{} answersOauth := struct { Name string `survey:"oauthName"` CallbackURLs string `survey:"callbackURls"` }{} SERVER, CLIENTID, CLIENTSECRET, TENANTDOMAIN = readSPConfig() if CLIENTID == "" { setSampleSP() SERVER, CLIENTID, CLIENTSECRET, TENANTDOMAIN = readSPConfig() setServerWithInit(SERVER) } else if readFile() == "" { setServer() if readFile() == "" { return } } else { ascii := figlet4go.NewAsciiRender() renderStr, _ := ascii.Render(appName) fmt.Print(renderStr) } err := survey.Ask(qs, &answers) if err == nil && answers.Selected == "Add application" { err := survey.Ask(types, &answersOfType) if err == nil && answersOfType.Selected == "Basic application" { err1 := survey.Ask(details, &answers) if err1 != nil { log.Fatalln(err1) return } createSPBasicApplication(answers.Name, answers.Description) } if err == nil && answersOfType.Selected == "oauth" { err1 := survey.Ask(oauthDetails, &answersOauth) if err1 != nil { log.Fatalln(err) return } if answersOauth.CallbackURLs == "" { grantTypes := []string{"password", "client_credentials", "refresh_token", "urn:ietf:params:oauth:grant-type:device_code", "iwa:ntlm", "urn:ietf:params:oauth:grant-type:jwt-bearer", "account_switch", "urn:ietf:params:oauth:grant-type:saml2-bearer", "urn:ietf:params:oauth:grant-type:uma-ticket"} createSPOauthApplication(answersOauth.Name, answersOauth.Name, answersOauth.CallbackURLs, grantTypes) } else { _, err := url.ParseRequestURI(answersOauth.CallbackURLs) if err != nil { log.Fatalln(err) } else { grantTypes := []string{"authorization_code", "implicit", "password", "client_credentials", "refresh_token", "urn:ietf:params:oauth:grant-type:device_code", "iwa:ntlm", "urn:ietf:params:oauth:grant-type:jwt-bearer", "account_switch", "urn:ietf:params:oauth:grant-type:saml2-bearer", "urn:ietf:params:oauth:grant-type:uma-ticket"} createSPOauthApplication(answersOauth.Name, answersOauth.Name, answersOauth.CallbackURLs, grantTypes) } } } } if err == nil && answers.Selected == "Get List" { getList() } }
package metric import ( "bytes" "encoding/binary" "fmt" "metric/win" "net" ) // 获取tcp连接表 func GetTcpTable() (tt *TcpTable, err error) { var ptb *win.MIB_TCPTABLE = &win.MIB_TCPTABLE{} var size uint32 if win.GetTcpTable(ptb, &size, 1) != win.ERROR_INSUFFICIENT_BUFFER { return tt, fmt.Errorf("call native GetTcpTable failed. return is not ERROR_INSUFFICIENT_BUFFER") } if win.GetTcpTable(ptb, &size, 1) != win.NO_ERROR { return tt, fmt.Errorf("call native GetTcpTable failed. return is not NO_ERROR") } var tr = TcpRow{} tt = &TcpTable{Table: make([]TcpRow, ptb.DwNumEntries)} for i := uint32(0); i < ptb.DwNumEntries; i++ { tr.RemoteAddr = addrDecode(ptb.Table[i].DwRemoteAddr).String() tr.LocalAddr = addrDecode(ptb.Table[i].DwLocalAddr).String() tr.RemotePort = portDecode(ptb.Table[i].DwRemotePort) tr.LocalPort = portDecode(ptb.Table[i].DwLocalPort) tt.Table[i] = tr } return tt, nil } // 将uint32格式的IP地址转换为nete.IP形式的IP地址 func addrDecode(addr uint32) net.IP { buf := bytes.NewBuffer([]byte{}) binary.Write(buf, binary.LittleEndian, addr) return net.IP(buf.Bytes()) } // 将uint32格式的端口转换为uint16格式的端口号 func portDecode(port uint32) uint16 { buf := bytes.NewBuffer([]byte{}) binary.Write(buf, binary.LittleEndian, uint16(port)) return binary.BigEndian.Uint16(buf.Bytes()) }
package graphql_test import ( "testing" "github.com/graphql-go/graphql" "github.com/graphql-go/graphql/gqlerrors" "github.com/graphql-go/graphql/testutil" ) func TestValidate_NoUnusedVariables_UsesAllVariables(t *testing.T) { testutil.ExpectPassesRule(t, graphql.NoUnusedVariablesRule, ` query ($a: String, $b: String, $c: String) { field(a: $a, b: $b, c: $c) } `) } func TestValidate_NoUnusedVariables_UsesAllVariablesDeeply(t *testing.T) { testutil.ExpectPassesRule(t, graphql.NoUnusedVariablesRule, ` query Foo($a: String, $b: String, $c: String) { field(a: $a) { field(b: $b) { field(c: $c) } } } `) } func TestValidate_NoUnusedVariables_UsesAllVariablesDeeplyInInlineFragments(t *testing.T) { testutil.ExpectPassesRule(t, graphql.NoUnusedVariablesRule, ` query Foo($a: String, $b: String, $c: String) { ... on Type { field(a: $a) { field(b: $b) { ... on Type { field(c: $c) } } } } } `) } func TestValidate_NoUnusedVariables_UsesAllVariablesInFragments(t *testing.T) { testutil.ExpectPassesRule(t, graphql.NoUnusedVariablesRule, ` query Foo($a: String, $b: String, $c: String) { ...FragA } fragment FragA on Type { field(a: $a) { ...FragB } } fragment FragB on Type { field(b: $b) { ...FragC } } fragment FragC on Type { field(c: $c) } `) } func TestValidate_NoUnusedVariables_VariableUsedByFragmentInMultipleOperations(t *testing.T) { testutil.ExpectPassesRule(t, graphql.NoUnusedVariablesRule, ` query Foo($a: String) { ...FragA } query Bar($b: String) { ...FragB } fragment FragA on Type { field(a: $a) } fragment FragB on Type { field(b: $b) } `) } func TestValidate_NoUnusedVariables_VariableUsedByRecursiveFragment(t *testing.T) { testutil.ExpectPassesRule(t, graphql.NoUnusedVariablesRule, ` query Foo($a: String) { ...FragA } fragment FragA on Type { field(a: $a) { ...FragA } } `) } func TestValidate_NoUnusedVariables_VariableNotUsed(t *testing.T) { testutil.ExpectFailsRule(t, graphql.NoUnusedVariablesRule, ` query ($a: String, $b: String, $c: String) { field(a: $a, b: $b) } `, []gqlerrors.FormattedError{ testutil.RuleError(`Variable "$c" is never used.`, 2, 38), }) } func TestValidate_NoUnusedVariables_MultipleVariablesNotUsed(t *testing.T) { testutil.ExpectFailsRule(t, graphql.NoUnusedVariablesRule, ` query Foo($a: String, $b: String, $c: String) { field(b: $b) } `, []gqlerrors.FormattedError{ testutil.RuleError(`Variable "$a" is never used in operation "Foo".`, 2, 17), testutil.RuleError(`Variable "$c" is never used in operation "Foo".`, 2, 41), }) } func TestValidate_NoUnusedVariables_VariableNotUsedInFragments(t *testing.T) { testutil.ExpectFailsRule(t, graphql.NoUnusedVariablesRule, ` query Foo($a: String, $b: String, $c: String) { ...FragA } fragment FragA on Type { field(a: $a) { ...FragB } } fragment FragB on Type { field(b: $b) { ...FragC } } fragment FragC on Type { field } `, []gqlerrors.FormattedError{ testutil.RuleError(`Variable "$c" is never used in operation "Foo".`, 2, 41), }) } func TestValidate_NoUnusedVariables_MultipleVariablesNotUsed2(t *testing.T) { testutil.ExpectFailsRule(t, graphql.NoUnusedVariablesRule, ` query Foo($a: String, $b: String, $c: String) { ...FragA } fragment FragA on Type { field { ...FragB } } fragment FragB on Type { field(b: $b) { ...FragC } } fragment FragC on Type { field } `, []gqlerrors.FormattedError{ testutil.RuleError(`Variable "$a" is never used in operation "Foo".`, 2, 17), testutil.RuleError(`Variable "$c" is never used in operation "Foo".`, 2, 41), }) } func TestValidate_NoUnusedVariables_VariableNotUsedByUnreferencedFragment(t *testing.T) { testutil.ExpectFailsRule(t, graphql.NoUnusedVariablesRule, ` query Foo($b: String) { ...FragA } fragment FragA on Type { field(a: $a) } fragment FragB on Type { field(b: $b) } `, []gqlerrors.FormattedError{ testutil.RuleError(`Variable "$b" is never used in operation "Foo".`, 2, 17), }) } func TestValidate_NoUnusedVariables_VariableNotUsedByFragmentUsedByOtherOperation(t *testing.T) { testutil.ExpectFailsRule(t, graphql.NoUnusedVariablesRule, ` query Foo($b: String) { ...FragA } query Bar($a: String) { ...FragB } fragment FragA on Type { field(a: $a) } fragment FragB on Type { field(b: $b) } `, []gqlerrors.FormattedError{ testutil.RuleError(`Variable "$b" is never used in operation "Foo".`, 2, 17), testutil.RuleError(`Variable "$a" is never used in operation "Bar".`, 5, 17), }) }
package cluster import ( "fmt" "github.com/KubeOperator/KubeOperator/pkg/util/ssh" "testing" "time" ) func TestGetClusterToken(t *testing.T) { client, err := ssh.New(&ssh.Config{ User: "root", Host: "172.16.10.184", Port: 22, Password: "Calong@2015", PrivateKey: nil, PassPhrase: nil, DialTimeOut: 5 * time.Second, Retry: 3, }) if err != nil { t.Error(err) } result, err := GetClusterToken(client) fmt.Println(result) }
package g2db import ( "fmt" "reflect" "strings" "github.com/pkg/errors" "xorm.io/xorm" "github.com/atcharles/gof/v2/g2util" ) type ( //MysqlQueryRowsParams ... MysqlQueryRowsParams struct { Page int `json:"page,omitempty"` PageCount int `json:"page_count,omitempty"` Conditions []string `json:"conditions,omitempty"` OrderBy string `json:"order_by,omitempty"` Asc bool `json:"asc,omitempty"` TimeColumn string `json:"time_column"` TimeBetween string `json:"time_between"` } //MysqlRows ... MysqlRows struct { Pages int `json:"pages,omitempty"` Data interface{} `json:"data,omitempty"` Count int64 `json:"count,omitempty"` } //ItfMysqlAfterQueryRow ... ItfMysqlAfterQueryRow interface { MysqlAfterQueryRow() } ) // GetBeanByTableName ... func (m *Mysql) GetBeanByTableName(tableStr string) (bean interface{}, err error) { m.mu.RLock() defer m.mu.RUnlock() for _, table := range m.tables { if tableName(table) == tableStr { bean = table return } } err = errors.Errorf("数据表%s不存在", tableStr) return } // QueryTableRows ...查询经过注册的表 func (m *Mysql) QueryTableRows(tableStr string, params *MysqlQueryRowsParams) (rows *MysqlRows, err error) { val, err := m.GetBeanByTableName(tableStr) if err != nil { return } return m.QueryRows(val, params) } // QueryRows ...分页查询,可以指定表名 func (m *Mysql) QueryRows(val interface{}, params *MysqlQueryRowsParams) (rows *MysqlRows, err error) { return NewQuery(m.Engine()).QueryRows(val, params) } // Query ... // new(Query).SetDb(*xorm.Engine).QueryRows(val, params) // new(Query).SetDb(*xorm.Engine).SetTable(string).QueryRows(val, params) type Query struct { db *xorm.Engine table string } // SetTable ... func (q *Query) SetTable(table string) *Query { q.table = table; return q } // QueryRows ... func (q *Query) QueryRows(val interface{}, params *MysqlQueryRowsParams) (rows *MysqlRows, err error) { db := q.db v1 := reflect.ValueOf(val) sl1 := reflect.MakeSlice(reflect.SliceOf(v1.Type()), 0, 0) sl := reflect.New(sl1.Type()) sl.Elem().Set(sl1) data := sl.Interface() if params.Page == 0 { params.Page = 1 } if params.PageCount == 0 { params.PageCount = 10 } const maxCount = 100 if params.PageCount > maxCount { params.PageCount = maxCount } if len(params.OrderBy) == 0 { params.OrderBy = "id" } if len(params.TimeColumn) == 0 { params.TimeColumn = "created" } sq := `SELECT * FROM {{.table}} WHERE ({{.condition}}) ` + `ORDER BY {{.orderBy}} {{.sort}} LIMIT {{.offsetX}},{{.pageCount}}` tpl := g2util.Map{ "orderBy": db.Quote(params.OrderBy), "sort": "DESC", "offsetX": params.PageCount * (params.Page - 1), "pageCount": params.PageCount, } if params.Asc { tpl["sort"] = "ASC" } tableStr := func() string { if len(q.table) == 0 { return tableName(val) } return q.table }() tpl["table"] = db.Quote(tableStr) condition1 := []string{"1=1"} condition1 = append(condition1, params.Conditions...) if len(params.TimeBetween) > 0 { ts := strings.Split(params.TimeBetween, ",") if len(ts) == 2 { condition1 = append( condition1, fmt.Sprintf("(`%s` BETWEEN '%s' AND '%s')", params.TimeColumn, ts[0], ts[1]), ) } } for i, s := range condition1 { condition1[i] = fmt.Sprintf("(%s)", s) } conditionStr := strings.Join(condition1, " AND ") tpl["condition"] = conditionStr sq = g2util.TextTemplateMustParse(sq, tpl) if err = db.SQL(sq).Find(data); err != nil { return } rows = &MysqlRows{Data: data} if sl.Elem().Len() == 0 { return } count, err := db.Table(tableStr).Where(conditionStr).Count() if err != nil { return } rows.Count = count rows.Pages = int(count) / params.PageCount if int(count)%params.PageCount > 0 { rows.Pages++ } ss1 := sl.Elem() for i := 0; i < ss1.Len(); i++ { switch vv := ss1.Index(i).Interface().(type) { case ItfMysqlAfterQueryRow: vv.MysqlAfterQueryRow() } } return } // NewQuery ... func NewQuery(engine *xorm.Engine) *Query { return &Query{db: engine} }
package main import ( "fmt" "math/rand" ) func main() { arr := rand.Perm(11) fmt.Println(arr) arr = mergeSort(arr) fmt.Println(arr) } func mergeSort(arr []int) []int { if len(arr) < 2 { return arr } middle := len(arr) / 2 left, right := arr[:middle], arr[middle:] return merge(mergeSort(left), mergeSort(right)) } func merge(left, right []int) []int { result := make([]int, 0, len(left)+len(right)) for len(left) != 0 && len(right) != 0 { if left[0] <= right[0] { result = append(result, left[0]) left = left[1:] } else { result = append(result, right[0]) right = right[1:] } } result = append(result, left...) result = append(result, right...) return result }
package main import ( "fmt" "strconv" "strings" ) func asInt(txt string) int { if val, err := strconv.Atoi(txt); err == nil { return val } else { panic("bad input, expected number, got : " + txt) } } func processLine(line string, currentTotal int) int { line = strings.TrimSpace(line) if line != "" { if strings.HasPrefix(line, "+") { line = line[1:len(line)] } val := asInt(line) currentTotal += val } return currentTotal } func main() { total := 0 for _, line := range strings.Split(testdata(), "\n") { total = processLine(line, total) } fmt.Println("Part 1 Result ", total) main2() } func testdata() string { return ` +1 +1 -1 ` }
package advent06 import ( "strings" ) type Body struct { Id string Orbiters []*Body Orbiting *Body } func ParseBodyTree(input string) (*Body, map[string]*Body) { bodies := make(map[string]*Body) for _, line := range strings.Split(input, "\n") { parts := strings.Split(line, ")") orbited, orbiter := parts[0], parts[1] orbitedBody := bodies[orbited] if orbitedBody == nil { orbitedBody = &Body{ Id: orbited, } bodies[orbited] = orbitedBody } orbiterBody := bodies[orbiter] if orbiterBody == nil { orbiterBody = &Body{ Id: orbiter, } bodies[orbiter] = orbiterBody } orbitedBody.Orbiters = append(orbitedBody.Orbiters, orbiterBody) // Install upward pointer. orbiterBody.Orbiting = orbitedBody } rootBody, ok := bodies["COM"] if !ok { panic("COM (root) not found.") } return rootBody, bodies } var Input = `797)67Y W32)48L J31)N9K QQ3)NVL MP6)JBY 8T3)H27 DRK)THF BSN)7MD Z2G)VRX CVV)XDC WVW)SV6 D3H)QMG 9BM)NTH 4T7)FQS F58)D1Q CR7)B7L 4W8)T9Z 5SB)5JB DRJ)YQD 76X)X1Z WC9)LNG 52C)W7J 9ZS)KM7 3RW)C8R 7RQ)TJW HVN)ZNQ SQK)CBT GWC)N76 KBQ)W44 QD5)RVQ SQF)N3K RZ1)B2R TB5)34W J56)CQD 34Y)HLX DTM)TD4 2RF)SQV GJT)TFD CNK)88B PJD)GD8 4V8)FQN HKH)6RS 7T4)2JT DBM)DMQ 59X)137 HK7)B62 D34)K7Z RR2)M74 Q13)FC5 1F1)8XJ K1L)QZ9 T73)4VT Z7S)59X 1MQ)GB6 BJT)4BZ WW8)DT2 JYL)6SH R2K)WC9 21H)4ZD Z7Z)QWZ F8N)LRZ QZ9)9TD 3DP)VDT GZK)ZGF G3P)KLZ 7ZM)G3P 3VX)P4H 7T4)LNV VVV)Q99 BYX)87K 4C1)9XS SB3)4SV FYV)JQ4 HQ4)ZMR K7Z)LKT TQM)BBH 9V5)PJD 7VB)H6L 66X)FDY NT9)17R K9Z)T26 1BX)VRN TJD)5ST QWZ)5CT MD6)GJT TT1)W3Y B2R)444 MB8)NFN FB1)4T3 V3Y)DJ7 2GQ)265 SLV)G3B THF)DC1 HRR)LV1 QZ7)ZR5 VGS)ZCG CRY)3L3 3N2)CZ4 Y1B)3WF YK2)W5C X15)8ZW 92C)3PV 7Z8)Y4B PWF)NX2 GPR)QVR TDL)TRM W4X)8TH 23H)6KK 4X2)TXV HQ9)52C LRG)RWM 38N)YVB W7F)BSM 3VC)FQC PS7)Z7Z 2YX)QSG 9PB)4KF VRX)K9Z TRM)R2K WYB)NRD HJ2)5LM ZRJ)WWL 7TW)WZR CBX)7S2 V4N)FSN 17B)88D F91)LWV L54)9G4 592)YC1 J24)9KW GNP)Y7T KDP)22T ZNQ)QFZ 8NW)MKC VSJ)NTD 137)VQS YB3)MP6 38W)DLK CJJ)683 59N)GHZ W3Y)P9Y 733)V2Q WX6)4GM RRP)HG8 L6L)YZZ QRW)YZX 1FD)RMT HSJ)5V9 RVQ)1KY 9K7)72H V6S)75V NB1)SDT J5N)4R6 QD7)1SR J6W)3FL 2GQ)FQM J5N)2K9 2B4)R23 4L5)QXX 7J4)42R 6X7)H2X 8D1)LH7 592)J4Y 6CM)4GW R6V)KSD FDL)NKS P4H)8RZ 46M)L1N M64)M4K 6K3)KZ9 FH8)1SS DJ7)BMS MG1)RQ9 ZRH)5G1 TMT)VQG 11V)W7N ZM5)QHZ DSL)8GB YK5)38P C1Y)YYJ H61)8N2 T7W)VVJ THR)M7F XXH)3H3 TVX)595 B2B)KBF 76Z)DGL 9PR)X23 ST7)G8Q 1FP)FH8 Q5F)7V2 XKP)2VC 47G)1ZG QXX)8XD MNG)KNF RF3)XD8 K4F)PLX 66D)LXG TQW)5SP SBR)ZFT NMH)8W7 N79)YBM BK8)JY9 NKS)H8K LQ5)SNS TVR)N6T QXP)M92 YMD)HM8 T84)25S Q6K)M3K R23)MZM CTB)B9Z DT2)718 9ZD)GXG KKV)N5K GBK)TKG TRG)GMW KFY)PLY LSP)RG9 Z31)MBP LXF)LFF 3JC)MS6 CRY)6ZK 67H)Z6Y B9Z)674 TWJ)DW2 1PR)4WW X1J)QZR 128)FLG GTT)75S 67Y)HNK H2L)ZRX 9V6)RF3 GRX)TDC WJR)68N 129)QJ4 FY1)PWF F5D)RQM S7K)PVL 88B)C23 YV9)136 5C8)X6V LDQ)1FD N55)WYB WZB)ZT8 SYH)QVB FWZ)SFX ZVJ)VXP L5V)J31 8ZW)4HG 49B)J24 6LC)Z98 G83)4V8 BGX)J9B 6XF)MQJ 54P)BTC 83Z)KZP BZZ)J9P RL5)QXQ YMQ)HH4 3XQ)64P 3BG)SBJ X7P)N8Y 3HN)L4S T1P)H61 ZJR)ZZR 1SH)JY7 KTB)LYF ZLF)BXG G3B)BRS 8JV)46M KDX)TP4 DPC)T8P VRQ)G56 2JZ)M64 YY2)1J2 VSJ)G7W SJ3)L68 19W)SMN KJX)GNP 7S3)RP1 VCS)MKK 8C6)7TR NY3)2LY 9N2)GVQ 9Y1)K9W PLX)V6S 38P)QNP V2D)J4Q TGL)NMG 2N2)NXX ZBW)G5C 88Y)QTV NPD)B9Y NFR)HHP 9Z9)Y49 NTH)LG9 RG9)HHS Y3P)D7W D38)4JL MF5)XGZ 4BB)DJJ 1XF)BZ4 F4Q)MHQ 7QN)FPZ 98T)DXP MLJ)DMR ZZC)7P2 5G1)7T4 J9B)VR4 W7K)1LP 8Z2)4K2 N1N)DS1 T73)TQW RQV)HCS T8P)6XS CNK)9WG 3RP)43B S2K)Z2G Z3H)P8G BZ4)QVP W7J)BN5 ZNJ)91T 6V7)CLD 6SH)6L9 XLQ)YBC BWN)6RL DRK)NBG 5ST)LR7 BPM)DNV 3H7)WYV WNF)BS9 FY1)6K9 3T2)3P4 B45)S1Q BKX)9ZD Y7T)9PR BRS)92N QLQ)75L XMQ)XTF N8Y)LSJ 4Q1)2MG NT9)NRL 7NT)F18 NRD)CFJ MDW)QXC QMG)LCN LSJ)L24 44J)V5Y 186)18R 91T)RM1 P4B)XVT JN4)128 JXZ)6PZ Q36)3RP 6K1)T2C 3S8)3VX 42R)QSD 3WF)66X LB2)XXH G3Y)SB3 44G)J99 HPK)2X5 7NH)HGJ 2W6)HTC HM8)FS4 XFD)9FK 643)L1R 3SQ)VB6 8BQ)N5L 2X5)J3R 1ZS)8LF 21Z)SLK YL7)FQH RKK)DMZ TNY)F96 Y2F)FRV MN7)BZZ 38X)KWN 75F)8WP ZR5)N7W F65)2VB 5PT)84N F9Y)HRR SVL)RXH RB6)NFR QTV)8CV 58Z)BWN FQN)BK8 WXC)MLY 683)HF6 T5X)6X6 BC5)WZB J2H)SQF DBM)LJQ FQS)SWH BFC)SLV 45B)7F8 Z12)6DS DP1)3T2 SLK)BBN 34Q)6V7 X66)DCJ V1V)X6C MR9)Z9T PMF)VP9 VCL)GNN B7L)KQ2 95C)F58 2RF)YJJ KNF)5X4 GJT)YZJ N9K)XTN T84)HZW TJN)6QJ TB5)Z7W YKV)YMQ W6T)1CV 1G3)5ZB LXG)3MK YJN)TTD 2Z7)KJN HHS)KKV KQ2)D3W M32)3SK 528)49L CVH)LB6 QSY)C6J VQS)KFY VPJ)95Q 2MG)GCK B2N)9QV 6N5)5FX F25)QJB 92Z)7QN 7XN)G62 WQ8)61N X8F)HG1 6Z4)3YQ MHQ)SAN XR9)5XJ 891)H43 VTD)1BJ 48L)MV7 W7W)BQT S9W)42J 7P2)ZV9 TW7)DXK CBG)2JK 7H8)KRG GDW)W4X G8X)2NW J99)Y5T VP9)83G D17)DKJ 1YF)W9J RSH)T43 4SV)6V6 M7D)QRQ 3WC)CJJ 45R)45B WFN)21H 4HG)8C6 NFN)BC5 XWF)BWG NHR)ST7 H83)NXB 3SK)7GB ZKW)D34 VDT)1SH 33V)N7F M8Z)4W8 XPD)WXC FRY)Z2V JB4)WR2 YPF)8T3 C8R)LRK V8L)WQ1 28R)Q7Y C52)Z18 CBY)GLF PXR)1F1 4XM)CFG J8G)V11 RVN)9V6 FZQ)B4V 775)3HN 1B2)X42 VD7)6GY 5WS)91M JJ2)3RW 3RG)8PX H4W)KHD B4Z)J56 8XP)ZHJ FZ4)6DZ 3QM)1XJ KQD)WDC BNV)87P GHZ)B2J J4Y)PXR BMM)LVJ 4JK)WZN TTD)KNL TW2)9JZ 6KK)DPC RZV)FK8 3DR)VSR PDP)76Z N7H)X7P J4L)7VB 2HT)DSL MV7)ZL3 Q7Y)FHP 7BM)2HT 4KF)FX7 B62)DHN FJ4)775 Z1V)XFQ N6T)7MV 136)F4M FBW)FGV W5G)Q7R 2G5)21B F76)LLY VCX)WJB BN5)B2N ZVF)9HQ BMJ)D17 1Q1)Y6J 6TV)MR9 9FQ)1MQ FC4)VCT V2C)YDS 8N2)T7W N5K)RY7 YPH)WGN RPY)TVY 6BQ)JJF 1SZ)KDP 1WL)DQW ZXR)BT3 MS6)JN4 4ZD)DBM 3RL)BM4 4DK)SVL YZ4)XR1 5R1)FMZ 8W7)JS1 KWN)GZK SR5)L9J JX6)X5V YBC)3S8 H48)BTY FL4)6WC GB6)285 64P)B4Z HCS)LK1 Q5F)R6V JDC)HKH PWR)916 RDW)TRJ V11)9L8 HXY)9VS RP1)CZD B9Y)891 P1G)FRZ QTV)B92 VB6)LYJ 3FL)7PW QLM)L54 LYQ)6LC Y5Q)MD6 KQ2)KJX GQG)1K8 SY7)WK9 77W)K1H 65Z)RFV H54)4P4 95Q)KTB VMB)DZS F3C)1N5 T26)7WW MSL)CWB QF5)6LN TWH)MGK 73Z)7KR VPP)LR8 129)CBX G8Q)L5V 9V7)RLB B2X)YPR T2D)M3M TT1)4QD 89C)JCX T7S)7QJ 6WC)SXQ Z3H)YPM MBP)7Z8 D3W)G83 QXX)74K SSB)V2D QVM)ZBL WZ1)Z6G D8J)GQG 9CF)F1C YDP)TWH FZ9)T3M ZTQ)V9X RX7)7F1 L3H)6NF BSM)TBV Z2V)D6G YS7)W32 LWV)7ZB PSP)YJR 49C)DWM 88D)3SZ LX9)G2Z 46D)GKR Z7W)1PR PWK)NY3 WDC)Z1V ZGF)PBN W28)HX3 5WQ)49B DYK)B5C 4R6)HK3 HZ2)N7H MN8)G4Y SJW)B2X 4M5)6QW YVC)PDW D1Q)C97 3SZ)7FW N6M)MF5 P53)XWC G46)RDW F6H)G9N XTF)BNV 6LC)K8B 2XV)813 7TR)J26 HC4)K38 9QV)VG8 F7Y)58Z N7W)V4N YZX)35W VCJ)1SN R85)1FP WHT)681 QCJ)RHP 2T5)ZTX VXP)XKP DVZ)2VX RDF)6FN DLR)RXK M66)F8N BQD)TW1 9L8)2BL 4T5)M36 8FJ)3PK MLF)7TW LR8)VZJ TMH)P2Z 8TH)LFP FB6)66D 3P2)4T5 BGZ)K4F 75V)F4Q TP4)8K6 4JL)KGH N5L)LFC F5D)WN4 RMT)T5C 1JB)XSJ MDB)WDX Y4B)765 1BY)MDW KYQ)48R KDD)6K3 YZ2)517 DC1)V5V JS1)6C9 FVR)3L7 CCQ)HQ9 LB6)JPM SWH)W28 WVM)K8N L7T)GPF 4X5)98T J1V)97M XHZ)FZQ J2L)CQ1 Z9T)W7F 3XQ)F25 XYS)M66 PFM)92C 144)F91 7ZB)PFM GPK)HXY BBN)MLJ 1KY)3QM 7FW)8BQ NP8)N2C CLY)QLQ HN5)VD7 1CV)H7D QCJ)TDZ G9N)HLN WYK)8H7 NRL)QXS XMF)WHQ SQV)2G5 YQM)VZX NMX)SR5 T4P)6VG 3SQ)S47 1BJ)Q36 QXS)51X HX3)KGJ 28V)GGC 2VC)6BL 4Q8)RVX CKW)GTT JX4)XCB NDH)Z8W HJ2)S2K S6Z)NMX N76)6TV RLD)Q8V R1Q)K7V FRV)RQK FJF)RLS KBF)SWF VJP)Y2F LW6)PMF 7MD)67H 456)S3D DW4)23D KVT)CVH NGC)1YF FX7)JX4 674)HBV 77G)7H8 MZ6)528 NX2)WGD TZR)CLZ YY7)4TQ K8B)GR9 S1Z)WF2 H5F)CKS W3R)J1V DTH)28R 9SK)7NH Q8V)X9B WJB)4FK 5SP)VJP 3ZL)8Z2 C6J)H85 YR7)4JK YS7)RVN BPM)H83 Q1Y)ZWH 4JM)561 MVM)6X7 T6Q)TW2 TPT)47G QVB)144 VSR)H48 GPS)FJF RFB)T4B VP7)3C9 2D8)FZ4 DWM)Y61 YJN)C52 1JB)ZG5 2K9)J7F 3MK)4XM YB3)PS7 COM)WV2 PDW)T1P 4YP)Q13 BTC)ZBW 9FS)37V 87P)XP2 7F1)RTN HKR)ZKW NHL)2XV PP4)CBG SDT)9CF HLN)GBK Y21)GPS H42)FJ4 FFZ)DDD SF7)YZ2 LP4)VSK FK8)W5G RFF)2FM 517)FDL 9FK)TW7 83H)S1M S4T)D8G 9TZ)89C G7W)VMB 4TQ)V7H JGP)Z95 V9X)VCS 8P7)DN2 WKZ)95C L9J)Z8M M36)FHD BBH)T3G XHZ)DP1 VZJ)39J FVR)YV9 Z95)XK9 D5Y)HTZ 8JH)ZXS B9D)VHJ YQD)XPD 9Z8)ZRT 285)X66 F94)D5Y C23)G3T 7SR)PWR LK1)K79 X42)8JV 3K2)LSP DHH)QF5 B92)H2L 7QJ)MPR FYH)BYX QCT)PFC VQG)PQ8 KNL)4SC QJB)YOU YKH)YY2 S1M)T92 6PW)11V HMT)CQY FHD)MTV Z6G)PVR 4Q1)6N5 N3M)38W VCT)CCQ 9KW)BMF QSG)4C1 J7T)GST FVN)TY8 X6C)4YN KRG)Q1Y CDD)7FS KDM)K1L NXB)QR4 XFQ)FZN 1T4)KYQ QVR)34Q W6S)TSK XLD)YKH 75R)TH8 T9Z)5NG C97)YJF PSZ)33Z GNN)R49 36J)N3H MYL)N1Z WPP)RHG 2VX)T6Q XP2)DG9 S21)Z1Q NMG)YDV SLV)BGZ 931)KQD 1DB)XGB SXQ)WCX K59)XBB TXV)ZVF DG9)Y3N H27)3ZZ XY8)ZZC Q7R)V8L W9J)WFN 8H7)J1X QJ4)DXJ GST)Q6K YDS)JXP GMW)83M TFD)P3N XTN)PKR 9HQ)5H6 BTB)685 3PN)D3H 6NT)F3C JXP)77W D8G)XHY QZ9)L2J 75L)SQK XWC)8YX L1N)GS2 JQ8)31Y TZQ)FVK DN2)YPH DW2)8NW RRQ)2T5 S81)DT5 S3X)V3Y XBB)FVR BFV)9DQ 9PR)Z3Z 92N)PLM B5C)NZR 3C9)LJ5 CQ1)HPK LR7)BGX 37V)D61 LRK)SP9 JY1)HQ4 RQM)WKZ 8X9)TJQ DS4)KWB LG9)JXZ HG8)MN8 KGJ)BYK 2JK)FMR WB1)GB9 WGD)TT1 Z3Z)RTL CDQ)6PW 8V8)2HD CCC)W7K YMQ)1WL GRY)WB1 4QK)DS4 FQH)SSB Z8W)648 GPD)Q5F ZBL)LCK 6RL)ZTM 7MV)6Z4 QSY)B9D N55)SVN G62)1B2 91R)Q1L G3P)GX2 PVL)1YW J9B)JJ2 TNS)PHY MGK)XZG RFV)3XQ 1XJ)23H G3T)Z5H 3RK)T1W T92)MXC XDC)HG6 WJQ)PRY XCB)D8Z K4R)K32 XYS)46D RK4)931 7FS)442 RQ9)YV4 KFV)RDF YC1)2B4 CBT)WHT JGZ)RTB C19)HYY RM1)PDP SFX)RK4 V5V)JYL RXK)T57 17R)3DR CQL)JK6 SP9)WVM ZG5)T7N QD7)YL7 ZFT)3RG PLM)SH8 RP6)VPP 12T)K4R G9F)KFV MGG)72P 85L)DPB GWP)L6L NHD)WYK XK8)9ND T5X)ZXY 6QJ)8X9 4MY)RP6 WN4)W9L 7CW)JH8 1JN)R7V 7KR)Q1G YHT)5WR GLP)FHT 59X)TLM 8LS)RKB 4MY)LKV NQW)VPJ J7F)R1Q WWL)77G LH7)YVC LR2)SVZ 826)2Z7 C8R)HJ2 8WP)GFJ X23)FB6 RM1)76X 1Z6)BMJ 1FR)51P LCK)VFT ZL3)75R KWB)L7T 6ZW)826 NZR)3K2 FQC)VHL YPM)YPJ 2FM)CNL 4TQ)HTP WGD)36J PBN)9FQ YVC)C2P S49)YJN QLX)SZC Z8W)BFC 3ZZ)8D1 WJV)JDP Z7W)QPK VZL)9VZ KLZ)K5Q SWS)TPT R68)VFM SXM)J4L L71)BTB 8GB)6D5 9WG)P6P J52)SYH D6G)T25 TBV)F9Y R3Y)NHL 5XF)S84 VTZ)Z31 HZW)XMT DGL)W6S 7TN)QJN 2JT)WJQ XSJ)9XN YG4)X15 JY7)DTM B9Z)MGG YJJ)Y8G B4V)R6F TFF)TDL TNS)FYH FDY)CCM HG6)H2H N5L)Z2N FWZ)V1Z CFG)GYM 23D)BJT BGD)CLY GXG)9FS ZWH)T73 J24)D4X 88N)BGJ LH7)K5Y 3MC)7S3 TJW)Z7S ZK7)695 1DM)19W 51P)DVX N1Z)1SZ JPM)3N2 6D5)M32 VVJ)KDM FHP)19S WCX)VZL 4FK)5XF DZQ)SWS QRQ)J52 RHP)ZHT 5RR)92Z 3P4)D5N 1XJ)38N YFB)C19 1MT)S6T 8K5)QD8 W86)NGC ZV9)8FJ GYM)GDP 7LS)HMT LCN)S7K K32)7RQ NFR)S6Z Q6K)CNK LYF)RRP 8XJ)R6G N1Y)DZQ PQ8)H78 HYY)J2H 8MB)5R1 YDV)4GG 8YX)V62 84V)46L LNV)KVC 6X6)TMH BPL)33V 6V6)YMM JZJ)QWP 4T3)VSJ DNH)JX6 ZFT)VCX KSD)YMD HYR)F64 GLF)7Q6 FPT)84V R6G)YK5 NNT)H4W TJD)WKD RWZ)VMM NLW)85L 4YN)SQR 8N2)9ZS N3K)YHT 2S1)SYL CCM)5MS GVQ)HC4 VM5)W3Q WQ1)FWZ RQK)GZM HNK)8DX D6J)GRY TZQ)RZV WHQ)SVY WVM)3DP Z7Z)PKM C2K)N1Y Z2N)9HB CRZ)4YM H78)MB8 8RH)8LW NBG)2BG XSW)TMT 561)LRG 1N5)4M5 FLW)YBZ 6RP)3QH M92)R58 CZ7)RDL FGV)ZPV RXF)CDQ 9XS)W7W 9VZ)4X2 VRX)WPP LYJ)VXH 681)YSC PFC)5CQ 7G7)X8F T57)FY1 Z8Z)BKX Z5P)YDP CQD)T1D 8HF)BSN YZJ)HVJ KRL)N55 4KR)4DK P2D)KVT RLC)YPF GX2)4JM V2Q)7F5 FQM)L2G SGD)WC5 HTC)SJG F1C)GDW WDX)G21 HBV)CVV 7F5)1Z6 LNK)HFD JB4)DFP 7S2)85B S1Z)HKR 2LY)LX9 T2C)DGK HLX)Z6L 4FM)NDH TRJ)TQM 49L)JY1 MPR)3T6 CWM)9SK 52C)9BX JBY)DVW V9C)DLR ZHT)86L MBH)NG2 7SR)G4D 35M)MYL NTD)QCT 2TX)1P3 8RZ)8VK WYP)N2S 7Z8)2RF SJG)29X 7WW)GDT VRN)QZ7 7LG)YK2 765)XLD P3N)TRG GCK)RSH TLM)GPK M79)4FX XGB)RL5 RXH)PKH YHB)LR2 265)1G3 MCG)NHR 3PV)BPM LM3)TFF Y49)1BX GB9)W1Q GKR)45R 2LF)CHQ 595)X41 W2G)7CW YB6)83Z 8LF)2W6 GJG)H42 PKR)3Z6 FLL)G7S WZS)ZFJ GB4)88N 8BK)CQM 9VS)W2G 5CT)YYD G4Y)N79 KJN)Y1T RY7)LBS K16)FLL YPF)LW6 SBJ)CRY 4DZ)186 4GG)5WQ KDV)4DZ Q1L)H54 R9Z)733 YPJ)GLT LNP)WVW XPD)21Z 9V2)HK7 4WW)37W 8K6)FBW R3Y)LM3 5M2)VM5 ZNJ)DVZ DVH)1NW GLT)HM1 SLK)PWK 84N)6K1 GS2)88Y K1H)GWP 4GW)ZRJ DVX)PZG VSF)5GL WBS)4DV 8XD)S49 V6J)4T7 75S)YKR GZM)BGD NKS)LKD 29X)LYQ JY9)2YX HBY)73Z BMF)LP4 T4B)KC2 87K)5M2 QZR)FLW GR9)KRL TXB)6NT 4FK)4MY B31)2LX TG1)4YP BQT)LNK TW1)RB6 3L7)T4P Z8Z)N3M 6TF)CR7 LFC)R33 37W)1FL CQY)J5N S4G)VTD ZT8)RZ1 5CQ)1FR BXG)FB1 9G4)BPL ZCG)F65 ZZR)2NC WZR)59N 6C9)V2C ZFJ)P1G CWB)KYN SY4)R85 DLK)9V2 2LX)VGN 5JB)GPR QHZ)9K7 D8Z)2LF 395)NB1 1FL)FBF 5MS)4XD HF6)49C JL7)YDQ 33Z)TG1 CXL)X8Y KYM)8XP RTB)54P LZ3)WJR 6DZ)969 FC5)XH7 DKJ)MCG QCR)VCJ W32)QXP 2XS)7LG Z6G)KDX H43)1SJ R7V)G7M YV4)8V8 D4X)1Q1 QSD)3KQ SFX)M6F DZ2)4DY 6K9)1DB CZD)2TX 3Z6)RRQ 72H)3H7 7BM)QRW P1G)NPF 85B)71W FRV)MMC 21B)5RR CSL)VCL XGZ)CDD 2B4)V9C QD5)T2M VMM)456 G56)S1Z NR6)C1N NXX)HMR H2H)XSW D7W)GPD JBY)ZNJ WKD)KDV 7PN)MD2 GDT)G6Q LV1)7XN 3KQ)RHW SWF)XLQ YDS)FL4 45R)Z8Z K4F)K59 HLJ)QD5 11H)MX8 MKC)VH3 G21)NT9 QXQ)L6Q VJ2)GFS HWJ)P4B B33)3P2 W28)2QR C1N)8LS 9KW)PSZ 74K)6ZT B23)WZ6 PPG)GJG PKM)4QK BS9)T7S F96)39P 444)RM5 T6Q)BWD S7K)M7D YYD)M79 D1P)116 4DV)J6W J7F)FRY SVY)TZQ 8PX)1ZS QFZ)NKW FD8)YB6 CLY)X6W 1YW)RFB 648)3MC 7D7)8TJ DT5)B33 T3M)5C8 31Y)FYV T43)75F H46)RFF 3BR)J8G 7S7)WBS G9F)C39 2QR)12T MKK)7LS D1P)RX1 X8Y)CS3 7PN)CRZ QMG)XNK YMD)3JC YSC)S21 DKZ)VWQ C1Y)G9Y DS1)Z4P T2M)9BM 38X)XMF MZM)DZ2 DXK)YQQ HGJ)YZ4 VCL)7BM ZPV)SN4 7J9)6XF QWP)RKK TSK)CQL BMS)TVX NPF)VJ2 KC2)NP8 MX8)YQM TH8)RLD KM7)F76 ZRT)XJR VWQ)V6J MKC)SY7 WGN)HLJ CXL)4Q8 1LP)8RH MQJ)KD7 7R8)R9Z 3H3)JL7 Y8G)LNP 4VT)P51 2NC)MLF 12H)HVN HVJ)MN7 SZC)7J4 5X4)D1P 29N)NMH 8LW)L71 YYJ)G46 LDL)CQ3 KHG)6MS RR2)83H 35D)38X SV6)XMQ KHD)MSL FGB)XFD ZS2)LXF DMQ)FZ9 MMC)FGB JW7)34Y WGN)VRQ LRZ)TB5 6NF)4FV DMR)9N2 916)SY4 83G)WJV 65M)12H 9HB)WSL L1R)5SB G9Y)1BT J26)91R WR2)H46 2RC)K16 QJN)VVV 4QD)G3Y XBV)35M QPK)RR2 S72)T84 Q2B)5PT 39J)MBH VFM)QSY G2Z)KDD Y94)ZS2 MTV)NPB R49)B31 RVX)TZR MD2)V1V 9TD)MDB WYV)YFB FRZ)C2K DPB)CTJ 5JB)M8Z 4DY)WQ8 KGH)WZS 35W)3RK 1SN)PSP VGN)5WS BR8)8JH N2Z)ZXR TJY)29N 8JN)S81 4FV)3Y3 QFZ)F7Y H7D)FFZ TVY)BMM 8VK)395 N3H)X1J 6RS)HQH 42J)FCX 6TF)R3Y 4K2)7R8 BGJ)2JZ 7F8)G92 BMS)6CM HTZ)ZM5 HQH)8P7 MXC)7LR M3K)YKV 54P)TJD FS4)28V 7PW)WNF HMR)SGC V5V)HBY RM5)Z12 KZP)KCV 4P4)VWV WZR)XYS RNC)9Z8 QR4)JQ8 WSL)7S7 S81)DHH NGC)7SR 6L9)8MB DNH)44J PVR)124 XZG)4X5 M6F)CB8 QJB)CZ7 DQW)XBV PKH)RX7 GFS)7J9 W7N)DVH 96G)DQC BWG)W6T 2BG)129 HHP)SJW FGB)SBR X6W)XHZ 5SB)MZ6 L5G)65M WC5)1MT 3T6)CTB YJF)JGZ 124)LB2 JDP)592 WV2)4D6 T7N)Y94 1SJ)ZTQ CKS)KHG 1SR)4L5 6N5)3BR 22T)BQD NBG)CSL 1ZG)DYK P8G)DRK LKD)RPY 7S3)9PB ZTM)RNC 3QH)Y21 VXH)LDQ NVL)QD7 TDC)TM4 W5C)YHB 19S)MS9 MNM)SJ3 8MT)XY8 6J1)GWC T5C)KBQ DC1)MVM QXD)N8B LKT)F5D HM1)TNY DQC)S9W RTL)QGK J1T)FPT CZ7)2N2 674)FC4 FMR)NLW TKG)1JN 1P3)GLP HK3)VTZ RHW)PG9 LJQ)7B2 5ZB)7ZM LFP)PQW TY8)YS7 4BZ)QLX 9BX)TNS S84)3PN GGC)S4T L5G)WX6 25S)JZJ WK9)L5G LBS)9V5 K7V)8MT 7Q6)G8X 4GN)HXM VH3)XK8 N8B)882 83M)YG4 P51)YR7 CS3)YY7 SVZ)N1N X5V)G9F G7M)GRX 39P)16T YBM)JDC WDC)8K5 HLN)W9F QVP)XR9 442)VSF YJR)LZ3 86L)6TF P2Z)LDL PQW)PPG CB8)1JB W9F)CHH VSK)RG1 SXM)QCR 969)WYR 6VG)F69 MLY)3VC RDL)ZRH X1Z)TWJ 1BT)RXF 4FX)T2D L2J)LB5 VHJ)MNM Y3N)3BG GD8)4KR 8TJ)C79 CFJ)QVM 4YM)SXM 71W)2S1 16T)NR6 D5N)PC7 S47)2RW 2Q3)QQ3 6FN)9Y1 PZG)6B3 XD8)2D8 C39)TJN WYR)HWJ HG1)RLC CQM)7G7 WF2)NPD VWV)643 JLZ)B2B Z5H)BFV LX9)1T4 CBG)3ZL 9HQ)8JN F18)Q7J F4M)W86 Q7J)YHM 6BQ)4FM 8CV)ZN4 YPR)NW2 VFT)FDW DFP)JT7 Y6J)ZK7 C2P)CBY 3Y3)TVR 97M)JLZ RG1)YB3 1J2)DLX V7H)D6J 6B3)8BK NW2)F94 PLY)D38 J3R)WYP 4GM)9TZ D34)44G QXC)B23 L68)797 HH4)1XF N2S)ZJR JJF)CXL L24)Z5P YHM)JB4 5FX)DW4 5WR)KYM 1SS)QCJ 9V5)RWZ ZXY)FD8 VHL)6JG RTN)Y5Q JGP)H5F 2T5)7NT LLY)TWZ SYL)HSJ BK8)3NR VG8)D8J Z18)T5X G7S)N6M 9JZ)BR8 BM4)8HF DXP)7D7 PG9)3SQ P9Y)J7T 47G)TGL 9BX)JGP HXM)7TN JQ4)LQ5 6MS)VP7 2BL)3WC T1W)WW8 YDQ)NQW 1FL)Z3H JCX)WHG 6ZK)L3H DZS)TXB Z4P)6BQ Y5T)9V7 5WQ)HN5 DGK)C1Y FSN)ZLF 72P)DNH 19S)K14 QPK)FRL 6QW)VGS 5V9)2C7 BYK)RQV 1JN)XWF 34W)6RP QFS)SF7 Y61)CKW R33)NNT MS9)4Q1 M74)FVN RX1)S4G 116)4BB YQQ)MC2 ZN4)1BY RLS)BBC B2J)11H P6P)F6H KD7)R9K FCV)ZVJ ZTX)HZ2 VMM)SGD 5H6)Q2B L1R)9Z9 H83)FCV F91)B45 L4S)PP4 2VB)R69 YB6)4GN 5ST)1DM 3L3)J2L ZRX)2RC 5GL)S3X 7LR)N2Z 3RL)P2D ZHJ)TJY DCJ)2XS PHY)96G MDB)QFS SH8)LZ7 VSF)CCC XMT)35D YKR)GB4 X41)Y3P MN8)2Q3 LNG)NHD K8N)DTH H2X)J1T 5LM)Y1B JT7)6J1 VR4)P53 813)JW7 CNL)QXD PRY)MG1 S3D)R68 JGZ)PXX 1NW)S72 FYH)3RL 48R)CWM 2RW)6ZW 6DS)MNG FD8)238 FZN)HYR NHL)THR Z98)65Z TRM)QLM K38)W3R 4D6)WZ1 BWD)2GQ FRL)DKZ WZ6)HC9 BBN)7PN DJJ)DRJ 3YQ)17B KCV)YTH`
package multipart import ( "io" "os" ) type File struct { name string io.ReadCloser } func (f *File) FileName() string { return f.name } func (f *File) Close() error { return f.ReadCloser.Close() } type IOFile struct { name string *os.File } func (f *IOFile) Close() error { var err error err = f.File.Close() err = os.Remove(f.name) return err } type BufferFile struct { io.Reader } func (b *BufferFile) Close() error { return nil }
package models import ( "fmt" mapStructure "github.com/mitchellh/mapstructure" uuid "github.com/nu7hatch/gouuid" apiResponse "github.com/alexhornbake/go-crud-api/lib/api_response" sql "github.com/alexhornbake/go-crud-api/lib/datastore" log "github.com/alexhornbake/go-crud-api/lib/logging" ) type Post struct { UserId string `json:"-"` Id string `json:"id"` Description string `json:"description"` ImageUrl string `json:"image_url"` changes []string } func NewPost(userId string, values *map[string]interface{}) *Post { newPost := Post{} newPost.ApplyChanges(values) newPost.UserId = userId return &newPost } func (post *Post) ApplyChanges(values *map[string]interface{}) { var md mapStructure.Metadata config := &mapStructure.DecoderConfig{ Metadata: &md, Result: post, } decoder, err := mapStructure.NewDecoder(config) if err != nil { panic(err) } err1 := decoder.Decode(values) if err1 != nil { panic(err1) } post.changes = md.Keys } func FindPost(userId string, id string) (*Post, *apiResponse.ErrorResponse) { var description string rows, err := sql.DB.Query("SELECT description FROM `posts` WHERE user_id=? AND id=?", userId, id) if err != nil { return nil, apiResponse.InternalServerError(err) } defer rows.Close() if !rows.Next() { return nil, apiResponse.NotFound("Post %s not found.", id) } err = rows.Scan(&description) if err != nil { return nil, apiResponse.InternalServerError(err) } err = rows.Err() if err != nil { return nil, apiResponse.InternalServerError(err) } foundPost := Post{ UserId: userId, Id: id, Description: description, } foundPost.buildImageUrl() return &foundPost, nil } func FindAllPosts(userId string) (*[]Post, *apiResponse.ErrorResponse) { var id, description string rows, err := sql.DB.Query("SELECT id, description FROM `posts` WHERE user_id=?", userId) if err != nil { return nil, apiResponse.InternalServerError(err) } defer rows.Close() if !rows.Next() { return nil, apiResponse.NotFound("No Posts found for user %s.", userId) } var foundPosts = []Post{} for rows.Next() { err = rows.Scan(&id, &description) if err != nil { return nil, apiResponse.InternalServerError(err) } foundPost := Post{ UserId: userId, Id: id, Description: description, } foundPost.buildImageUrl() foundPosts = append(foundPosts, foundPost) } err = rows.Err() if err != nil { return nil, apiResponse.InternalServerError(err) } return &foundPosts, nil } func (post *Post) Save() (*Post, *apiResponse.ErrorResponse) { if post.changes == nil || len(post.changes) == 0 { log.Warning("Called post.Save() without any changes to commit.") return post, nil } stmt, sqlErr := sql.DB.Prepare("UPDATE posts SET description=? WHERE user_id=? AND id=?") if sqlErr != nil { return nil, apiResponse.InternalServerError(sqlErr) } defer stmt.Close() _, sqlErr = stmt.Exec(post.Description, post.UserId, post.Id) if sqlErr != nil { return nil, apiResponse.InternalServerError(sqlErr) } return post, nil } func (post *Post) Delete() (*Post, *apiResponse.ErrorResponse) { stmt, sqlErr := sql.DB.Prepare("DELETE FROM posts WHERE user_id=? AND id=?") if sqlErr != nil { return nil, apiResponse.InternalServerError(sqlErr) } defer stmt.Close() _, sqlErr = stmt.Exec(post.UserId, post.Id) if sqlErr != nil { return nil, apiResponse.InternalServerError(sqlErr) } return post, nil } func (post *Post) InitialSave() (*Post, *apiResponse.ErrorResponse) { id, err := uuid.NewV4() if err != nil { panic(err) } post.Id = id.String() stmt, sqlErr := sql.DB.Prepare("INSERT INTO posts(user_id, id, description) VALUES(?,?,?)") if sqlErr != nil { return nil, apiResponse.InternalServerError(sqlErr) } defer stmt.Close() _, sqlErr = stmt.Exec(post.UserId, post.Id, post.Description) if sqlErr != nil { return nil, apiResponse.InternalServerError(sqlErr) } return post, nil } func (post *Post) buildImageUrl() { post.ImageUrl = fmt.Sprintf("//image.example.com/users/%s/posts/%s.jpg", post.UserId, post.Id) }
package dao import ( "coffeebeans-people-backend/models" "context" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" ) type KafkaService struct { conn string } func (k KafkaService) CreateUser(ctx context.Context, user models.User) error { return nil } func (service *Service) CreateUser(ctx context.Context, user models.User) error { c := service.MongoConn.Collection("users") model := mongo.IndexModel{ Keys: bson.M{ "employee_id": user.EmployeeId, }, Options: options.Index().SetUnique(true), } c.Indexes().CreateOne(ctx, model) _, err := c.InsertOne(ctx, user) if err != nil { return err } return nil } func (service *Service) GetUserByEmployeeId(ctx context.Context, employeeId int64) (models.User, error) { user := models.User{} collection := service.MongoConn.Collection("users") doc := collection.FindOne(ctx, bson.M{"employee_id": employeeId}) err := doc.Decode(&user) if err != nil { return user, err } return user, nil } func (service *Service) GetUserByCredentials(ctx context.Context, email string, password string) (models.User, error) { user := models.User{} collection := service.MongoConn.Collection("users") doc := collection.FindOne(ctx, bson.M{"email": email, "password": password}) err := doc.Decode(&user) if err != nil { return user, err } return user, nil } func (service *Service) GetAllUsers(ctx context.Context, params map[string]interface{}) ([]models.User, error) { users := make([]models.User, 0) collection := service.MongoConn.Collection("users") filter := bson.M{} if params != nil { if param, ok := params["skill"]; ok { filter["skill"] = param } else if param, ok := params["id"]; ok { filter["employee_id"] = param } } cur, err := collection.Find(ctx, filter) if err != nil { return users, err } defer cur.Close(ctx) for cur.Next(context.Background()) { user := models.User{} err := cur.Decode(&user) if err != nil { return users, err } users = append(users, user) } if err := cur.Err(); err != nil { return users, err } return users, nil }
// Package route53 implements a DNS provider for solving the DNS-01 challenge // using AWS Route 53 DNS. package aws import ( "fmt" "log" "math/rand" "os" "strings" "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/client" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/credentials/stscreds" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/route53" "github.com/xenolf/lego/acme" dp "gomodules.xyz/dns/provider" ) const ( maxRetries = 5 ttl = 300 ) // DNSProvider implements the acme.ChallengeProvider interface type DNSProvider struct { client *route53.Route53 hostedZoneID string } var _ dp.Provider = &DNSProvider{} // customRetryer implements the client.Retryer interface by composing the // DefaultRetryer. It controls the logic for retrying recoverable request // errors (e.g. when rate limits are exceeded). type customRetryer struct { client.DefaultRetryer } // RetryRules overwrites the DefaultRetryer's method. // It uses a basic exponential backoff algorithm that returns an initial // delay of ~400ms with an upper limit of ~30 seconds which should prevent // causing a high number of consecutive throttling errors. // For reference: Route 53 enforces an account-wide(!) 5req/s query limit. func (d customRetryer) RetryRules(r *request.Request) time.Duration { retryCount := r.RetryCount if retryCount > 7 { retryCount = 7 } delay := (1 << uint(retryCount)) * (rand.Intn(50) + 200) return time.Duration(delay) * time.Millisecond } type Options struct { AccessKeyId string `json:"access_key_id" envconfig:"AWS_ACCESS_KEY_ID" form:"aws_access_key_id"` SecretAccessKey string `json:"secret_access_key" envconfig:"AWS_SECRET_ACCESS_KEY" form:"aws_secret_access_key"` HostedZoneID string `json:"hosted_zone_id" envconfig:"AWS_HOSTED_ZONE_ID" form:"aws_hosted_zone_id"` } // NewDNSProvider returns a DNSProvider instance configured for the AWS // Route 53 service. // // AWS Credentials are automatically detected in the following locations // and prioritized in the following order: // 1. Environment variables: AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, // AWS_REGION, [AWS_SESSION_TOKEN] // 2. Shared credentials file (defaults to ~/.aws/credentials) // 3. Amazon EC2 IAM role // // See also: https://github.com/aws/aws-sdk-go/wiki/configuring-sdk func Default() (*DNSProvider, error) { hostedZoneID := os.Getenv("AWS_HOSTED_ZONE_ID") r := customRetryer{} r.NumMaxRetries = maxRetries config := request.WithRetryer(aws.NewConfig(), r) s, err := session.NewSessionWithOptions(session.Options{ Config: *config, // Support MFA when authing using assumed roles. SharedConfigState: session.SharedConfigEnable, AssumeRoleTokenProvider: stscreds.StdinTokenProvider, }) if err != nil { return nil, err } return &DNSProvider{client: route53.New(s), hostedZoneID: hostedZoneID}, nil } func New(opt Options) (*DNSProvider, error) { r := customRetryer{} r.NumMaxRetries = maxRetries config := &aws.Config{ Credentials: credentials.NewStaticCredentials(opt.AccessKeyId, opt.SecretAccessKey, ""), Retryer: r, Region: aws.String("us-east-1"), } s, err := session.NewSessionWithOptions(session.Options{ Config: *config, // Support MFA when authing using assumed roles. SharedConfigState: session.SharedConfigEnable, AssumeRoleTokenProvider: stscreds.StdinTokenProvider, }) if err != nil { return nil, err } return &DNSProvider{client: route53.New(s), hostedZoneID: opt.HostedZoneID}, nil } func (r *DNSProvider) EnsureARecord(domain string, ip string) error { fqdn := acme.ToFqdn(domain) hostedZoneID, err := r.getHostedZoneID(fqdn) if err != nil { return fmt.Errorf("Failed to determine Route 53 hosted zone ID: %v", err) } resp, err := r.client.ListResourceRecordSets(&route53.ListResourceRecordSetsInput{ HostedZoneId: aws.String(hostedZoneID), StartRecordName: aws.String(fqdn), StartRecordType: aws.String(route53.RRTypeA), }) if err != nil { return err } if len(resp.ResourceRecordSets) > 0 && *resp.ResourceRecordSets[0].Name == fqdn && *resp.ResourceRecordSets[0].Type == route53.RRTypeA && contains(resp.ResourceRecordSets[0].ResourceRecords, ip) { log.Println("DNS is already configured. No DNS related change is necessary.") return nil } reqParams := &route53.ChangeResourceRecordSetsInput{ HostedZoneId: aws.String(hostedZoneID), ChangeBatch: &route53.ChangeBatch{ Comment: aws.String("Managed by appscode/go-dns"), Changes: []*route53.Change{ { Action: aws.String(route53.ChangeActionUpsert), ResourceRecordSet: &route53.ResourceRecordSet{ Name: aws.String(fqdn), Type: aws.String(route53.RRTypeA), TTL: aws.Int64(ttl), ResourceRecords: []*route53.ResourceRecord{ { Value: aws.String(ip), }, }, }, }, }, }, } if len(resp.ResourceRecordSets) > 0 && *resp.ResourceRecordSets[0].Name == fqdn && *resp.ResourceRecordSets[0].Type == route53.RRTypeA { // append existing values reqParams.ChangeBatch.Changes[0].ResourceRecordSet.ResourceRecords = append( reqParams.ChangeBatch.Changes[0].ResourceRecordSet.ResourceRecords, resp.ResourceRecordSets[0].ResourceRecords...) } _, err = r.client.ChangeResourceRecordSets(reqParams) return err } func (r *DNSProvider) DeleteARecords(domain string) error { fqdn := acme.ToFqdn(domain) hostedZoneID, err := r.getHostedZoneID(fqdn) if err != nil { return fmt.Errorf("Failed to determine Route 53 hosted zone ID: %v", err) } resp, err := r.client.ListResourceRecordSets(&route53.ListResourceRecordSetsInput{ HostedZoneId: aws.String(hostedZoneID), StartRecordName: aws.String(fqdn), StartRecordType: aws.String(route53.RRTypeA), }) if err != nil { return err } if len(resp.ResourceRecordSets) > 0 && *resp.ResourceRecordSets[0].Name == fqdn && *resp.ResourceRecordSets[0].Type == route53.RRTypeA { reqParams := &route53.ChangeResourceRecordSetsInput{ HostedZoneId: aws.String(hostedZoneID), ChangeBatch: &route53.ChangeBatch{ Comment: aws.String("Managed by appscode/go-dns"), Changes: []*route53.Change{ { Action: aws.String(route53.ChangeActionDelete), ResourceRecordSet: resp.ResourceRecordSets[0], }, }, }, } _, err = r.client.ChangeResourceRecordSets(reqParams) return err } log.Println("No A record found. No DNS related change is necessary.") return nil } func (r *DNSProvider) DeleteARecord(domain string, ip string) error { fqdn := acme.ToFqdn(domain) hostedZoneID, err := r.getHostedZoneID(fqdn) if err != nil { return fmt.Errorf("Failed to determine Route 53 hosted zone ID: %v", err) } resp, err := r.client.ListResourceRecordSets(&route53.ListResourceRecordSetsInput{ HostedZoneId: aws.String(hostedZoneID), StartRecordName: aws.String(fqdn), StartRecordType: aws.String(route53.RRTypeA), }) if err != nil { return err } if len(resp.ResourceRecordSets) > 0 && *resp.ResourceRecordSets[0].Name == fqdn && *resp.ResourceRecordSets[0].Type == route53.RRTypeA && contains(resp.ResourceRecordSets[0].ResourceRecords, ip) { reqParams := &route53.ChangeResourceRecordSetsInput{ HostedZoneId: aws.String(hostedZoneID), ChangeBatch: &route53.ChangeBatch{ Comment: aws.String("Managed by appscode/go-dns"), }, } updatedRecords := make([]*route53.ResourceRecord, 0) for _, r := range resp.ResourceRecordSets[0].ResourceRecords { if *r.Value != ip { updatedRecords = append(updatedRecords, r) } } if len(updatedRecords) == 0 { // delete recordset reqParams.ChangeBatch.Changes = []*route53.Change{ { Action: aws.String(route53.ChangeActionDelete), ResourceRecordSet: resp.ResourceRecordSets[0], }, } } else { // update recordset resp.ResourceRecordSets[0].ResourceRecords = updatedRecords reqParams.ChangeBatch.Changes = []*route53.Change{ { Action: aws.String(route53.ChangeActionUpsert), ResourceRecordSet: resp.ResourceRecordSets[0], }, } } _, err = r.client.ChangeResourceRecordSets(reqParams) return err } log.Println("No A record found. No DNS related change is necessary.") return nil } func (r *DNSProvider) getHostedZoneID(fqdn string) (string, error) { if r.hostedZoneID != "" { return r.hostedZoneID, nil } authZone, err := acme.FindZoneByFqdn(fqdn, acme.RecursiveNameservers) if err != nil { return "", err } // .DNSName should not have a trailing dot reqParams := &route53.ListHostedZonesByNameInput{ DNSName: aws.String(acme.UnFqdn(authZone)), } resp, err := r.client.ListHostedZonesByName(reqParams) if err != nil { return "", err } var hostedZoneID string for _, hostedZone := range resp.HostedZones { // .Name has a trailing dot if !*hostedZone.Config.PrivateZone && *hostedZone.Name == authZone { hostedZoneID = *hostedZone.Id break } } if len(hostedZoneID) == 0 { return "", fmt.Errorf("Zone %s not found in Route 53 for domain %s", authZone, fqdn) } if strings.HasPrefix(hostedZoneID, "/hostedzone/") { hostedZoneID = strings.TrimPrefix(hostedZoneID, "/hostedzone/") } return hostedZoneID, nil } func contains(records []*route53.ResourceRecord, s string) bool { for _, record := range records { if *record.Value == s { return true } } return false }
package main import ( "encoding/json" "fmt" "io/ioutil" "net/http" "os" "regexp" "time" "github.com/confluentinc/confluent-kafka-go/kafka" ) var newsSummary map[string][]StdNews var newsContent map[string][][]string //WangYiNewsRaw contains a raw material form API type WangYiNewsRaw map[string][]struct { LiveInfo interface{} `json:"liveInfo"` Docid string `json:"docid"` Source string `json:"source"` Title string `json:"title"` Priority int `json:"priority"` HasImg int `json:"hasImg"` URL string `json:"url"` CommentCount int `json:"commentCount"` Imgsrc3Gtype string `json:"imgsrc3gtype"` Stitle string `json:"stitle"` Digest string `json:"digest"` Imgsrc string `json:"imgsrc"` Ptime string `json:"ptime"` Imgextra []struct { Imgsrc string `json:"imgsrc"` } `json:"imgextra,omitempty"` } //StdNews object is in standard format type StdNews struct { Timestamp string `json:"timestamp` Source string `json:"source"` Title string `json:"title"` Body string `json:"body"` PicURL string `json:"picurl` URL string `json:"url"` Types []string `json:"types"` Keywords []string `json:keywords"` } //WYToStd changes raw news to standard format func WYToStd(news WangYiNewsRaw) { var key string for k := range news { key = k } for _, each := range news[key] { var item StdNews item.Timestamp = time.Now().Format("2006-01-02 15:04:05") item.Source = each.Source item.Title = each.Title item.Body = each.Digest item.URL = each.URL item.PicURL = each.Imgsrc newsSummary["WYNews"] = append(newsSummary["WYNews"], item) } } func checkError(msg string, err error) { if err != nil { fmt.Println(msg, err) os.Exit(1) } } //GetWangYiNews set-up in [wyNewsSummary] and [wyNewsContent] func GetWangYiNews() { //网易新闻API接口{“游戏”,“教育”,“新闻”,“娱乐”,“体育”,“财经”,“军事”,“科技”,“手机”,“数码”,“时尚”,“健康”,“旅游”} urls := []string{"https://3g.163.com/touch/reconstruct/article/list/BAI6RHDKwangning/0-10.html", "https://3g.163.com/touch/reconstruct/article/list/BA8FF5PRwangning/0-10.html", "https://3g.163.com/touch/reconstruct/article/list/BBM54PGAwangning/0-10.html", "https://3g.163.com/touch/reconstruct/article/list/BA10TA81wangning/0-10.html", "https://3g.163.com/touch/reconstruct/article/list/BA8E6OEOwangning/0-10.html", "https://3g.163.com/touch/reconstruct/article/list/BA8EE5GMwangning/0-10.html", "https://3g.163.com/touch/reconstruct/article/list/BAI67OGGwangning/0-10.html", "https://3g.163.com/touch/reconstruct/article/list/BA8D4A3Rwangning/0-10.html", "https://3g.163.com/touch/reconstruct/article/list/BAI6I0O5wangning/0-10.html", "https://3g.163.com/touch/reconstruct/article/list/BAI6JOD9wangning/0-10.html", "https://3g.163.com/touch/reconstruct/article/list/BA8F6ICNwangning/0-10.html", "https://3g.163.com/touch/reconstruct/article/list/BDC4QSV3wangning/0-10.html", "https://3g.163.com/touch/reconstruct/article/list/BEO4GINLwangning/0-10.html"} for _, url := range urls { resp, err := http.Get(url) //接口接入、get返回示例 checkError("Failed to fetch news", err) body, err := ioutil.ReadAll(resp.Body) //转成可读形式(json) resp.Body.Close() //断开连接 bodyStr := string(body) bodyCut := bodyStr[9 : len(bodyStr)-1] bodyJSON := []byte(bodyCut) checkError("Failed to read news", err) /////格式转换///// var wangyiNews WangYiNewsRaw //创造object err = json.Unmarshal([]byte(bodyJSON), &wangyiNews) //json转换到go checkError("Failed to unmarshal json", err) WYToStd(wangyiNews) //转换到标准格式 } /////正文爬取///// GetNewsContent(newsSummary["WYNews"], 2) } func WangYiTest() { url := "https://3g.163.com/touch/reconstruct/article/list/BAI6RHDKwangning/0-10.html" resp, err := http.Get(url) //接口接入、get返回示例 checkError("Failed to fetch news", err) body, err := ioutil.ReadAll(resp.Body) //转成可读形式(json) resp.Body.Close() //断开连接 bodyStr := string(body) bodyCut := bodyStr[9 : len(bodyStr)-1] bodyJSON := []byte(bodyCut) checkError("Failed to read news", err) /////格式转换///// var wangyiNews WangYiNewsRaw //创造object err = json.Unmarshal([]byte(bodyJSON), &wangyiNews) //json转换到go checkError("Failed to unmarshal json", err) WYToStd(wangyiNews) //转换到标准格式 GetNewsContent(newsSummary["WYNews"], 2) } //GetNewsContent extracts all the chinese content in string form func GetNewsContent(news []StdNews, id int) { chineseRegExp := regexp.MustCompile("[\\p{Han}]+") //正则匹配中文格式 for _, each := range news { url := each.URL resp, err := http.Get(url) //access news article through url if err == nil { body, _ := ioutil.ReadAll(resp.Body) //get html body resp.Body.Close() chineseContent := chineseRegExp.FindAllString(string(body), -1) //find all the chinese content if id == 1 { newsContent["ZHNews"] = append(newsContent["ZHNews"], chineseContent) WriteToFile(each, chineseContent) //write news info and content into file } else if id == 2 { newsContent["WYNews"] = append(newsContent["WYNews"], chineseContent) WriteToFile(each, chineseContent) //write news info and content into file } else { newsContent["WYNews"] = append(newsContent["WYNews"], []string{each.Body}) WriteToFile(each, []string{each.Body}) //write news info and content into file } } } } //WriteToFile stores data from API into "newsData.txt" func WriteToFile(news StdNews, content []string) { f, _ := os.OpenFile("newsData.txt", os.O_WRONLY|os.O_APPEND, 0600) data, err := json.Marshal(news) checkError("Failed to marshal news", err) f.Write(data) //write marshaled news info in json format f.WriteString("\n") for _, s := range content { f.WriteString(s) } f.WriteString("\n\n") f.Close() } ///kafka数据发送与接收///// //DeliverMsgToKafka sends message to brokers with distinct topics func DeliverMsgToKafka(topic string) []string { //access data stored in [newsContent] //data := newsContent[topic] msgs := []string{} data := [][]string{[]string{topic}} //initiate a new producer producer, err := kafka.NewProducer(&kafka.ConfigMap{"bootstrap.servers": "127.0.0.1:9092"}) //check for successful creation of producer before proceeding checkError("Failed to create producer: %s\n", err) /////WRITES MESSAGE///// //produce message for _, news := range data { producer.Produce(&kafka.Message{ TopicPartition: kafka.TopicPartition{Topic: &topic, Partition: kafka.PartitionAny}, Value: []byte(news[0]), }, nil) } //prints out message fmt.Println("Produced message, waiting for delivery response.") /////CHECK MESSAGE DELIVERY///// //check delivery reponse with another goroutine go func() { //event used to listen for the result of send for e := range producer.Events() { switch ev := e.(type) { case *kafka.Message: if ev.TopicPartition.Error != nil { fmt.Printf("Delivery failed: %v\n", ev.TopicPartition.Error) } else { msg := "Delivery message to topic " + topic + string(ev.TopicPartition.Partition) + " at offset " + string(ev.TopicPartition.Offset) + "\n" msgs = append(msgs, msg) } } } }() //wait for message deliveries before shutting down producer.Flush(15 * 1000) return msgs } func connect(w http.ResponseWriter, r *http.Request) { r.ParseForm() newsSummary = make(map[string][]StdNews) //initiate [newsSummary] newsContent = make(map[string][][]string) //initiate [newsContent] //crawl news //GetWangYiNews() WangYiTest() //produce msg to kafka msgs := DeliverMsgToKafka("WYNews") for _, msg := range msgs { fmt.Fprintf(w, msg) } } func main() { http.HandleFunc("/crawlnews", connect) err := http.ListenAndServe(":9090", nil) checkError("Failed to connect to server", err) }
package Problem0313 // 解题思路可以参考 264 题 func nthSuperUglyNumber(n int, primes []int) int { if n == 1 { return 1 } pos := make([]int, len(primes)) candidates := make([]int, len(primes)) copy(candidates, primes) res := make([]int, n) res[0] = 1 for i := 1; i < n; i++ { res[i] = min(candidates) for j := 0; j < len(primes); j++ { if res[i] == candidates[j] { pos[j]++ candidates[j] = res[pos[j]] * primes[j] } } } return res[n-1] } func min(candidates []int) int { min := candidates[0] for i := 1; i < len(candidates); i++ { if min > candidates[i] { min = candidates[i] } } return min }
package 一维子串问题 /* 给定一个未经排序的整数数组,找到最长且连续的的递增序列。 */ // 原始dp (空间没有优化) // dp[i] 表示: 以nums[i]结尾的最长连续递增序列长度 // 状态转移方程: // 初始 : dp[i] = 1。 // i > 0 && nums[i] > nums[i-1]: dp[i] = dp[i-1] + 1 func findLengthOfLCIS(nums []int) int { dp := make([]int, len(nums)+1) maxLength := 0 for i := 0; i < len(nums); i++ { if i > 0 && nums[i] > nums[i-1] { dp[i] = dp[i-1] + 1 } else { dp[i] = 1 } maxLength = max(maxLength, dp[i]) } return maxLength } // 滚动优化,将空间复杂度优化为O(1),上面的空间复杂度是O(n) func findLengthOfLCIS(nums []int) int { maxLength := 0 dp := 0 for i := 0; i < len(nums); i++ { if i > 0 && nums[i] > nums[i-1] { dp = dp + 1 } else { dp = 1 } maxLength = max(maxLength, dp) } return maxLength } func max(a, b int) int { if a > b { return a } return b } /* 题目链接: https://leetcode-cn.com/problems/longest-continuous-increasing-subsequence/ 最长连续递增序列 */ /* 总结 1. 对于这个题,官方还有类似滑动窗口的解法。 */
package routers import ( "encoding/json" "net/http" "github.com/rodzy/flash/db" "github.com/rodzy/flash/models" ) //Register func to create an user in our MongoDB func Register(w http.ResponseWriter,r *http.Request) { var t models.User //Streaming the json file err:=json.NewDecoder(r.Body).Decode(&t) if err != nil { http.Error(w,"Error on streaming data"+err.Error(),400) return } if len(t.Email)==0 { http.Error(w,"Email required",400) return } if len(t.Password)< 8 { http.Error(w,"Password must be 8 caracters",400) return } //Finding the user in DB _,userfound,_:= db.UserFound(t.Email) if userfound==true { http.Error(w,"User is already registered",400) return } //Registering user _,status,err:=db.InsertUser(t) if err != nil { http.Error(w,"Error trying to register the user",400) return } if status==false { http.Error(w,"Couldn't register the user",400) return } w.WriteHeader(http.StatusCreated) }
package service import ( "github.com/Tanibox/tania-core/src/growth/domain" "github.com/Tanibox/tania-core/src/growth/query" "github.com/Tanibox/tania-core/src/growth/storage" "github.com/gofrs/uuid" ) type CropServiceInMemory struct { MaterialReadQuery query.MaterialReadQuery CropReadQuery query.CropReadQuery AreaReadQuery query.AreaReadQuery } func (s CropServiceInMemory) FindMaterialByID(uid uuid.UUID) domain.ServiceResult { result := <-s.MaterialReadQuery.FindByID(uid) if result.Error != nil { return domain.ServiceResult{ Error: result.Error, } } inv, ok := result.Result.(query.CropMaterialQueryResult) if !ok { return domain.ServiceResult{ Error: domain.CropError{Code: domain.CropMaterialErrorInvalidMaterial}, } } if inv == (query.CropMaterialQueryResult{}) { return domain.ServiceResult{ Error: domain.CropError{Code: domain.CropMaterialErrorNotFound}, } } return domain.ServiceResult{ Result: inv, } } func (s CropServiceInMemory) FindByBatchID(batchID string) domain.ServiceResult { resultQuery := <-s.CropReadQuery.FindByBatchID(batchID) if resultQuery.Error != nil { return domain.ServiceResult{ Error: resultQuery.Error, } } cropFound, ok := resultQuery.Result.(storage.CropRead) if !ok { return domain.ServiceResult{ Error: domain.CropError{Code: domain.CropErrorInvalidBatchID}, } } if cropFound.UID != (uuid.UUID{}) { return domain.ServiceResult{ Error: domain.CropError{Code: domain.CropErrorBatchIDAlreadyCreated}, } } return domain.ServiceResult{ Result: cropFound, } } func (s CropServiceInMemory) FindAreaByID(uid uuid.UUID) domain.ServiceResult { result := <-s.AreaReadQuery.FindByID(uid) if result.Error != nil { return domain.ServiceResult{ Error: result.Error, } } area, ok := result.Result.(query.CropAreaQueryResult) if !ok { return domain.ServiceResult{ Error: domain.CropError{Code: domain.CropMoveToAreaErrorInvalidSourceArea}, } } if area == (query.CropAreaQueryResult{}) { return domain.ServiceResult{ Error: domain.CropError{Code: domain.CropMoveToAreaErrorSourceAreaNotFound}, } } return domain.ServiceResult{ Result: area, } }
package shader import ( "fmt" "image" _ "image/jpeg" _ "image/png" "io/ioutil" "os" "strings" wrapper "github.com/akosgarai/opengl_playground/pkg/glwrapper" ) func textureMap(index int) uint32 { switch index { case 0: return wrapper.TEXTURE0 case 1: return wrapper.TEXTURE1 case 2: return wrapper.TEXTURE2 } return 0 } // LoadShaderFromFile takes a filepath string arguments. // It loads the file and returns it as a '\x00' terminated string. // It returns an error also. func LoadShaderFromFile(path string) (string, error) { shaderCode, err := ioutil.ReadFile(path) if err != nil { return "", err } result := string(shaderCode) + "\x00" return result, nil } // LoadImageFromFile takes a filepath string argument. // It loads the file, decodes it as PNG or jpg, and returns the image and error func loadImageFromFile(path string) (image.Image, error) { imgFile, err := os.Open(path) if err != nil { return nil, err } defer imgFile.Close() img, _, err := image.Decode(imgFile) return img, err } func CompileShader(source string, shaderType uint32) (uint32, error) { shader := wrapper.CreateShader(shaderType) csources, free := wrapper.Strs(source) wrapper.ShaderSource(shader, 1, csources, nil) free() wrapper.CompileShader(shader) var status int32 wrapper.GetShaderiv(shader, wrapper.COMPILE_STATUS, &status) if status == wrapper.FALSE { var logLength int32 wrapper.GetShaderiv(shader, wrapper.INFO_LOG_LENGTH, &logLength) log := strings.Repeat("\x00", int(logLength+1)) wrapper.GetShaderInfoLog(shader, logLength, nil, wrapper.Str(log)) return 0, fmt.Errorf("failed to compile %v: %v", source, log) } return shader, nil }
package k8s import ( appmesh "github.com/aws/aws-app-mesh-controller-for-k8s/apis/appmesh/v1beta2" "github.com/stretchr/testify/assert" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" "testing" ) func TestNamespacedName(t *testing.T) { tests := []struct { name string obj metav1.Object want types.NamespacedName }{ { name: "cluster-scoped object", obj: &appmesh.Mesh{ ObjectMeta: metav1.ObjectMeta{ Name: "global", }, }, want: types.NamespacedName{ Namespace: "", Name: "global", }, }, { name: "namespace-scoped object", obj: &appmesh.VirtualNode{ ObjectMeta: metav1.ObjectMeta{ Namespace: "namespace", Name: "my-node", }, }, want: types.NamespacedName{ Namespace: "namespace", Name: "my-node", }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got := NamespacedName(tt.obj) assert.Equal(t, tt.want, got) }) } }
/* Copyright 2021. The KubeVela 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 traitdefinition import ( "context" "fmt" "time" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" v1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/reconcile" "github.com/oam-dev/kubevela/apis/core.oam.dev/common" "github.com/oam-dev/kubevela/apis/core.oam.dev/v1beta1" "github.com/oam-dev/kubevela/pkg/oam" "github.com/oam-dev/kubevela/pkg/oam/testutil" "github.com/oam-dev/kubevela/pkg/oam/util" ) var _ = Describe("Test DefinitionRevision created by TraitDefinition", func() { ctx := context.Background() namespace := "test-revision" var ns v1.Namespace BeforeEach(func() { ns = v1.Namespace{ ObjectMeta: metav1.ObjectMeta{ Name: namespace, }, } Expect(k8sClient.Create(ctx, &ns)).Should(SatisfyAny(BeNil(), &util.AlreadyExistMatcher{})) }) Context("Test TraitDefinition", func() { It("Test update TraitDefinition", func() { tdName := "test-update-traitdef" req := reconcile.Request{NamespacedName: client.ObjectKey{Name: tdName, Namespace: namespace}} td1 := tdWithNoTemplate.DeepCopy() td1.Name = tdName td1.Spec.Schematic.CUE.Template = fmt.Sprintf(tdTemplate, "test-v1") By("create traitDefinition") Expect(k8sClient.Create(ctx, td1)).Should(SatisfyAll(BeNil())) testutil.ReconcileRetry(&r, req) By("check whether definitionRevision is created") tdRevName1 := fmt.Sprintf("%s-v1", tdName) var tdRev1 v1beta1.DefinitionRevision Eventually(func() error { err := k8sClient.Get(ctx, client.ObjectKey{Namespace: namespace, Name: tdRevName1}, &tdRev1) return err }, 10*time.Second, time.Second).Should(BeNil()) By("update traitDefinition") td := new(v1beta1.TraitDefinition) Eventually(func() error { err := k8sClient.Get(ctx, client.ObjectKey{Namespace: namespace, Name: tdName}, td) if err != nil { return err } td.Spec.Schematic.CUE.Template = fmt.Sprintf(tdTemplate, "test-v2") return k8sClient.Update(ctx, td) }, 10*time.Second, time.Second).Should(BeNil()) testutil.ReconcileRetry(&r, req) By("check whether a new definitionRevision is created") tdRevName2 := fmt.Sprintf("%s-v2", tdName) var tdRev2 v1beta1.DefinitionRevision Eventually(func() error { return k8sClient.Get(ctx, client.ObjectKey{Namespace: namespace, Name: tdRevName2}, &tdRev2) }, 10*time.Second, time.Second).Should(BeNil()) }) It("Test only update TraitDefinition Labels, Shouldn't create new revision", func() { td := tdWithNoTemplate.DeepCopy() tdName := "test-td" td.Name = tdName defKey := client.ObjectKey{Namespace: namespace, Name: tdName} req := reconcile.Request{NamespacedName: defKey} td.Spec.Schematic.CUE.Template = fmt.Sprintf(tdTemplate, "test") Expect(k8sClient.Create(ctx, td)).Should(BeNil()) testutil.ReconcileRetry(&r, req) By("Check revision create by TraitDefinition") defRevName := fmt.Sprintf("%s-v1", tdName) revKey := client.ObjectKey{Namespace: namespace, Name: defRevName} var defRev v1beta1.DefinitionRevision Eventually(func() error { return k8sClient.Get(ctx, revKey, &defRev) }, 10*time.Second, time.Second).Should(BeNil()) By("Only update TraitDefinition Labels") var checkRev v1beta1.TraitDefinition Eventually(func() error { err := k8sClient.Get(ctx, defKey, &checkRev) if err != nil { return err } checkRev.SetLabels(map[string]string{ "test-label": "test-defRev", }) return k8sClient.Update(ctx, &checkRev) }, 10*time.Second, time.Second).Should(BeNil()) testutil.ReconcileRetry(&r, req) newDefRevName := fmt.Sprintf("%s-v2", tdName) newRevKey := client.ObjectKey{Namespace: namespace, Name: newDefRevName} Expect(k8sClient.Get(ctx, newRevKey, &defRev)).Should(HaveOccurred()) }) }) Context("Test TraitDefinition Controller clean up", func() { It("Test clean up definitionRevision", func() { var revKey client.ObjectKey var defRev v1beta1.DefinitionRevision tdName := "test-clean-up" revisionNum := 1 defKey := client.ObjectKey{Namespace: namespace, Name: tdName} req := reconcile.Request{NamespacedName: defKey} By("create a new TraitDefinition") td := tdWithNoTemplate.DeepCopy() td.Name = tdName td.Spec.Schematic.CUE.Template = fmt.Sprintf(tdTemplate, fmt.Sprintf("test-v%d", revisionNum)) Expect(k8sClient.Create(ctx, td)).Should(BeNil()) By("update TraitDefinition") checkComp := new(v1beta1.TraitDefinition) for i := 0; i < defRevisionLimit+1; i++ { Eventually(func() error { err := k8sClient.Get(ctx, defKey, checkComp) if err != nil { return err } checkComp.Spec.Schematic.CUE.Template = fmt.Sprintf(tdTemplate, fmt.Sprintf("test-v%d", revisionNum)) return k8sClient.Update(ctx, checkComp) }, 10*time.Second, time.Second).Should(BeNil()) testutil.ReconcileRetry(&r, req) revKey = client.ObjectKey{Namespace: namespace, Name: fmt.Sprintf("%s-v%d", tdName, revisionNum)} revisionNum++ var defRev v1beta1.DefinitionRevision Eventually(func() error { return k8sClient.Get(ctx, revKey, &defRev) }, 10*time.Second, time.Second).Should(BeNil()) } By("create new TraitDefinition will remove oldest definitionRevision") Eventually(func() error { err := k8sClient.Get(ctx, defKey, checkComp) if err != nil { return err } checkComp.Spec.Schematic.CUE.Template = fmt.Sprintf(tdTemplate, fmt.Sprintf("test-v%d", revisionNum)) return k8sClient.Update(ctx, checkComp) }, 10*time.Second, time.Second).Should(BeNil()) testutil.ReconcileRetry(&r, req) revKey = client.ObjectKey{Namespace: namespace, Name: fmt.Sprintf("%s-v%d", tdName, revisionNum)} revisionNum++ Eventually(func() error { return k8sClient.Get(ctx, revKey, &defRev) }, 10*time.Second, time.Second).Should(BeNil()) deletedRevision := new(v1beta1.DefinitionRevision) deleteConfigMap := new(v1.ConfigMap) deleteRevKey := types.NamespacedName{Namespace: namespace, Name: tdName + "-v1"} deleteCMKey := types.NamespacedName{Namespace: namespace, Name: tdName + "-v1"} listOpts := []client.ListOption{ client.InNamespace(namespace), client.MatchingLabels{ oam.LabelTraitDefinitionName: tdName, }, } defRevList := new(v1beta1.DefinitionRevisionList) Eventually(func() error { err := k8sClient.List(ctx, defRevList, listOpts...) if err != nil { return err } if len(defRevList.Items) != defRevisionLimit+1 { return fmt.Errorf("error defRevison number wants %d, actually %d", defRevisionLimit+1, len(defRevList.Items)) } err = k8sClient.Get(ctx, deleteRevKey, deletedRevision) if err == nil || !apierrors.IsNotFound(err) { return fmt.Errorf("haven't clean up the oldest revision") } err = k8sClient.Get(ctx, deleteCMKey, deleteConfigMap) if err == nil || !apierrors.IsNotFound(err) { return fmt.Errorf("haven't clean up the oldest configMap") } return nil }, time.Second*30, time.Microsecond*300).Should(BeNil()) By("update app again will continue to delete the oldest revision") Eventually(func() error { err := k8sClient.Get(ctx, defKey, checkComp) if err != nil { return err } checkComp.Spec.Schematic.CUE.Template = fmt.Sprintf(tdTemplate, fmt.Sprintf("test-v%d", revisionNum)) return k8sClient.Update(ctx, checkComp) }, 10*time.Second, time.Second).Should(BeNil()) testutil.ReconcileRetry(&r, req) revKey = client.ObjectKey{Namespace: namespace, Name: fmt.Sprintf("%s-v%d", tdName, revisionNum)} Eventually(func() error { return k8sClient.Get(ctx, revKey, &defRev) }, 10*time.Second, time.Second).Should(BeNil()) deleteRevKey = types.NamespacedName{Namespace: namespace, Name: tdName + "-v2"} deleteCMKey = types.NamespacedName{Namespace: namespace, Name: tdName + "-v2"} Eventually(func() error { err := k8sClient.List(ctx, defRevList, listOpts...) if err != nil { return err } if len(defRevList.Items) != defRevisionLimit+1 { return fmt.Errorf("error defRevison number wants %d, actually %d", defRevisionLimit+1, len(defRevList.Items)) } err = k8sClient.Get(ctx, deleteRevKey, deletedRevision) if err == nil || !apierrors.IsNotFound(err) { return fmt.Errorf("haven't clean up the oldest revision") } err = k8sClient.Get(ctx, deleteCMKey, deleteConfigMap) if err == nil || !apierrors.IsNotFound(err) { return fmt.Errorf("haven't clean up the oldest configMap") } return nil }, time.Second*30, time.Microsecond*300).Should(BeNil()) }) It("Test clean up definitionRevision contains definitionRevision with custom name", func() { var revKey client.ObjectKey var defRev v1beta1.DefinitionRevision revisionNames := []string{"1.3.1", "", "1.3.3", "", "prod"} tdName := "test-td-with-specify-revision" revisionNum := 1 defKey := client.ObjectKey{Namespace: namespace, Name: tdName} req := reconcile.Request{NamespacedName: defKey} By("create a new traitDefinition") td := tdWithNoTemplate.DeepCopy() td.Name = tdName td.Spec.Schematic.CUE.Template = fmt.Sprintf(tdTemplate, fmt.Sprintf("test-v%d", revisionNum)) Expect(k8sClient.Create(ctx, td)).Should(BeNil()) testutil.ReconcileRetry(&r, req) revKey = client.ObjectKey{Namespace: namespace, Name: fmt.Sprintf("%s-v%d", tdName, revisionNum)} Eventually(func() error { return k8sClient.Get(ctx, revKey, &defRev) }, 10*time.Second, time.Second).Should(BeNil()) Expect(defRev.Spec.Revision).Should(Equal(int64(revisionNum))) By("update traitDefinition") checkTrait := new(v1beta1.TraitDefinition) for _, revisionName := range revisionNames { revisionNum++ Eventually(func() error { err := k8sClient.Get(ctx, defKey, checkTrait) if err != nil { return err } checkTrait.SetAnnotations(map[string]string{ oam.AnnotationDefinitionRevisionName: revisionName, }) checkTrait.Spec.Schematic.CUE.Template = fmt.Sprintf(tdTemplate, fmt.Sprintf("test-v%d", revisionNum)) return k8sClient.Update(ctx, checkTrait) }, 10*time.Second, time.Second).Should(BeNil()) Eventually(func() error { testutil.ReconcileOnce(&r, req) newTd := new(v1beta1.TraitDefinition) err := k8sClient.Get(ctx, req.NamespacedName, newTd) if err != nil { return err } if newTd.Status.LatestRevision.Revision != int64(revisionNum) { return fmt.Errorf("fail to update status") } return nil }, 15*time.Second, time.Second) if len(revisionName) == 0 { revKey = client.ObjectKey{Namespace: namespace, Name: fmt.Sprintf("%s-v%d", tdName, revisionNum)} } else { revKey = client.ObjectKey{Namespace: namespace, Name: fmt.Sprintf("%s-v%s", tdName, revisionName)} } By("check the definitionRevision is created by controller") var defRev v1beta1.DefinitionRevision Eventually(func() error { return k8sClient.Get(ctx, revKey, &defRev) }, 10*time.Second, time.Second).Should(BeNil()) Expect(defRev.Spec.Revision).Should(Equal(int64(revisionNum))) } By("create new TraitDefinition will remove oldest definitionRevision") revisionNum++ Eventually(func() error { err := k8sClient.Get(ctx, defKey, checkTrait) if err != nil { return err } checkTrait.SetAnnotations(map[string]string{ oam.AnnotationDefinitionRevisionName: "test", }) checkTrait.Spec.Schematic.CUE.Template = fmt.Sprintf(tdTemplate, "test-vtest") return k8sClient.Update(ctx, checkTrait) }, 10*time.Second, time.Second).Should(BeNil()) Eventually(func() error { testutil.ReconcileOnce(&r, req) newTd := new(v1beta1.TraitDefinition) err := k8sClient.Get(ctx, req.NamespacedName, newTd) if err != nil { return err } if newTd.Status.LatestRevision.Revision != int64(revisionNum) { return fmt.Errorf("fail to update status") } return nil }, 15*time.Second, time.Second) revKey = client.ObjectKey{Namespace: namespace, Name: fmt.Sprintf("%s-v%s", tdName, "test")} Eventually(func() error { return k8sClient.Get(ctx, revKey, &defRev) }, 10*time.Second, time.Second).Should(BeNil()) deletedRevision := new(v1beta1.DefinitionRevision) deleteConfigMap := new(v1.ConfigMap) deleteRevKey := types.NamespacedName{Namespace: namespace, Name: tdName + "-v1"} deleteCMKey := types.NamespacedName{Namespace: namespace, Name: tdName + "-v1"} listOpts := []client.ListOption{ client.InNamespace(namespace), client.MatchingLabels{ oam.LabelTraitDefinitionName: tdName, }, } defRevList := new(v1beta1.DefinitionRevisionList) Eventually(func() error { err := k8sClient.List(ctx, defRevList, listOpts...) if err != nil { return err } if len(defRevList.Items) != defRevisionLimit+1 { return fmt.Errorf("error defRevison number wants %d, actually %d", defRevisionLimit+1, len(defRevList.Items)) } err = k8sClient.Get(ctx, deleteRevKey, deletedRevision) if err == nil || !apierrors.IsNotFound(err) { return fmt.Errorf("haven't clean up the oldest revision") } err = k8sClient.Get(ctx, deleteCMKey, deleteConfigMap) if err == nil || !apierrors.IsNotFound(err) { return fmt.Errorf("haven't clean up the oldest configMap") } return nil }, time.Second*30, time.Microsecond*300).Should(BeNil()) By("update app again will continue to delete the oldest revision") revisionNum++ Eventually(func() error { err := k8sClient.Get(ctx, defKey, checkTrait) if err != nil { return err } checkTrait.SetAnnotations(map[string]string{ oam.AnnotationDefinitionRevisionName: "", }) checkTrait.Spec.Schematic.CUE.Template = fmt.Sprintf(tdTemplate, fmt.Sprintf("test-v%d", revisionNum)) return k8sClient.Update(ctx, checkTrait) }, 10*time.Second, time.Second).Should(BeNil()) Eventually(func() error { testutil.ReconcileOnce(&r, req) newTd := new(v1beta1.TraitDefinition) err := k8sClient.Get(ctx, req.NamespacedName, newTd) if err != nil { return err } if newTd.Status.LatestRevision.Revision != int64(revisionNum) { return fmt.Errorf("fail to update status") } return nil }, 15*time.Second, time.Second) revKey = client.ObjectKey{Namespace: namespace, Name: fmt.Sprintf("%s-v%d", tdName, revisionNum)} Eventually(func() error { return k8sClient.Get(ctx, revKey, &defRev) }, 10*time.Second, time.Second).Should(BeNil()) deleteRevKey = types.NamespacedName{Namespace: namespace, Name: tdName + "-v1.3.1"} deleteCMKey = types.NamespacedName{Namespace: namespace, Name: tdName + "-v1.3.1"} Eventually(func() error { err := k8sClient.List(ctx, defRevList, listOpts...) if err != nil { return err } if len(defRevList.Items) != defRevisionLimit+1 { return fmt.Errorf("error defRevison number wants %d, actually %d", defRevisionLimit+1, len(defRevList.Items)) } err = k8sClient.Get(ctx, deleteRevKey, deletedRevision) if err == nil || !apierrors.IsNotFound(err) { return fmt.Errorf("haven't clean up the oldest revision") } err = k8sClient.Get(ctx, deleteCMKey, deleteConfigMap) if err == nil || !apierrors.IsNotFound(err) { return fmt.Errorf("haven't clean up the oldest configMap") } return nil }, time.Second*30, time.Microsecond*300).Should(BeNil()) }) }) }) var tdTemplate = ` patch: { // +patchKey=name spec: template: spec: containers: [{ name: "%s" image: parameter.image command: parameter.cmd if parameter["volumes"] != _|_ { volumeMounts: [ for v in parameter.volumes { { mountPath: v.path name: v.name } }] } }] } parameter: { // +usage=Specify the image of sidecar container image: string // +usage=Specify the commands run in the sidecar cmd?: [...string] // +usage=Specify the shared volume path volumes?: [...{ name: string path: string }] } ` var tdWithNoTemplate = &v1beta1.TraitDefinition{ TypeMeta: metav1.TypeMeta{ Kind: "TraitDefinition", APIVersion: "core.oam.dev/v1beta1", }, ObjectMeta: metav1.ObjectMeta{ Name: "test-defrev", Namespace: "test-revision", }, Spec: v1beta1.TraitDefinitionSpec{ Schematic: &common.Schematic{ CUE: &common.CUE{}, }, }, }
package data import ( "github.com/google/uuid" ) // Account represents a bank account, its structure follows https://api-docs.form3.tech/api.html#organisation-accounts-resource. // Fake account service does not implement "private_identification" and "relationships". type Account struct { Type RecordType `json:"type"` ID uuid.UUID `json:"id"` OrganisationID uuid.UUID `json:"organisation_id"` Version int `json:"version"` Attributes Attributes `json:"attributes"` }
package main import ( "database/sql" ) func main() { injectionTest("Nottingham") } func injectionTest(city string) { db, err := sql.Open("postgres", "postgresql://test:test@test") if err != nil { // return err } var count int row := db.QueryRow("SELECT COUNT(*) FROM t WHERE city=" + city) //nolint:safesql if err := row.Scan(&count); err != nil { // return err } row = db.QueryRow("SELECT COUNT(*) FROM t WHERE city=?", city) if err := row.Scan(&count); err != nil { // return err } return }
package commands import ( "github.com/cloudfoundry/bosh-bootloader/storage" "github.com/cloudfoundry/bosh-bootloader/terraform" ) type up interface { CheckFastFails([]string, storage.State) error ParseArgs([]string, storage.State) (UpConfig, error) Execute([]string, storage.State) error } type terraformManager interface { ValidateVersion() error GetOutputs(storage.State) (terraform.Outputs, error) Init(storage.State) error Apply(storage.State) (storage.State, error) Destroy(storage.State) (storage.State, error) } type terraformOutputter interface { GetOutputs(storage.State) (terraform.Outputs, error) } type boshManager interface { InitializeDirector(bblState storage.State, terraformOutputs terraform.Outputs) error CreateDirector(bblState storage.State) (storage.State, error) InitializeJumpbox(bblState storage.State, terraformOutputs terraform.Outputs) error CreateJumpbox(bblState storage.State, jumpboxURL string) (storage.State, error) DeleteDirector(bblState storage.State, terraformOutputs terraform.Outputs) error DeleteJumpbox(bblState storage.State, terraformOutputs terraform.Outputs) error GetDirectorDeploymentVars(bblState storage.State, terraformOutputs terraform.Outputs) string GetJumpboxDeploymentVars(bblState storage.State, terraformOutputs terraform.Outputs) string Version() (string, error) } type envIDManager interface { Sync(storage.State, string) (storage.State, error) } type environmentValidator interface { Validate(state storage.State) error } type terraformManagerError interface { Error() string BBLState() (storage.State, error) } type vpcStatusChecker interface { ValidateSafeToDelete(vpcID string, envID string) error } type certificateDeleter interface { Delete(certificateName string) error } type stateValidator interface { Validate() error } type certificateValidator interface { Validate(command, certPath, keyPath, chainPath string) error } type logger interface { Step(string, ...interface{}) Printf(string, ...interface{}) Println(string) Prompt(string) } type stateStore interface { Set(state storage.State) error GetBblDir() (string, error) } type cloudConfigManager interface { Update(state storage.State) error Generate(state storage.State) (string, error) }
package accumulate import ( "reflect" "runtime" "strings" ) func GetFunctionName(i interface{}) string { return runtime.FuncForPC(reflect.ValueOf(i).Pointer()).Name() } func Accumulate(listOfString []string, converter func(string) string) []string { var currentFuncName = GetFunctionName(converter) var funcNameEcho = GetFunctionName(echo) var funcNameUpper = GetFunctionName(strings.ToUpper) if currentFuncName == funcNameEcho { return listOfString } else { for i := 0; i < len(listOfString); i++ { if currentFuncName == funcNameUpper { listOfString[i] = strings.ToUpper(listOfString[i]) } else { listOfString[i] = capitalize(listOfString[i]) } } } return listOfString }
package main import ( "github.com/tidwall/gjson" "io/ioutil" "net/http" "testing" ) func TestGetPrice(t *testing.T) { go startServer(false) resp, _ := http.Get("http://localhost:8080/categories/MLA5726/price") resp_body, _ := ioutil.ReadAll(resp.Body) data := string(resp_body) max, min, sg := gjson.Get(data, "max"), gjson.Get(data, "min"), gjson.Get(data, "suggested") if !max.Exists() || !min.Exists() || !sg.Exists() { t.Error("Not getting correct data") } } func TestGetPriceNoItems(t *testing.T) { go startServer(false) resp, _ := http.Get("http://localhost:8080/categories/sfg4tw/price") if resp.StatusCode != 404 { t.Error("Not error thrown on bad category", resp.StatusCode) } } func BenchmarkPrice(b *testing.B) { b.N = 3 for i := 0; i < b.N; i++ { http.Get("http://localhost:8080/categories/MLA5726/price") } }
package main import ( "sync" "gopkg.in/cheggaaa/pb.v1" ) type ProgressBar struct { //totalPb *pb.ProgressBar okPb *pb.ProgressBar errorPb *pb.ProgressBar pool *pb.Pool } func NewProgressBar() *ProgressBar { //totalPb := makeProgressBar(options.FilePathTotalLines, "TOTAL") okPb := makeProgressBar(options.FilePathTotalLines, "OK") errorPb := makeProgressBar(options.FilePathTotalLines, "ERROR") return &ProgressBar{ okPb, errorPb, nil, } } func makeProgressBar(total int, prefix string) *pb.ProgressBar { progressBar := pb.New(total) progressBar.Prefix(prefix) progressBar.SetMaxWidth(120) progressBar.SetRefreshRate(1000) progressBar.ShowElapsedTime = true progressBar.ShowTimeLeft = false return progressBar } func (p *ProgressBar) IncrementOk() { p.okPb.Add(1) } func (p *ProgressBar) IncrementError() { p.errorPb.Add(1) } func (p *ProgressBar) Start() { pool, err := pb.StartPool(p.okPb, p.errorPb) if err != nil { panic(err) } p.pool = pool p.okPb.Start() } func (p *ProgressBar) Stop() { wg := new(sync.WaitGroup) for _, bar := range []*pb.ProgressBar{p.okPb, p.errorPb} { wg.Add(1) go func(cb *pb.ProgressBar) { cb.Finish() wg.Done() }(bar) } wg.Wait() // close pool _ = p.pool.Stop() }
package main import "fmt" func help2() { fmt.Println("helper function 2 called") }
package main import ( "fmt" "time" ) func say() { time.Sleep(100 * time.Millisecond) fmt.Println("Hello world!") } func main() { go say() fmt.Println("Goodbye world! Or?") time.Sleep(200 * time.Millisecond) }
package sqle import ( "context" "fmt" ) // MySQL extends sqle.Std with MySQL specific functions type MySQL struct { Std *Std } // UnsafeExists checks whether the statement defined by the `query` and `args` // would return a result. // // This method IS NOT SAFE AGAINST SQL-INJECTION. Use it only with trusted // input! func (s *MySQL) UnsafeExists(ctx context.Context, query string, args ...interface{}) (exists bool, err error) { query = fmt.Sprintf("SELECT EXISTS (%s)", query) err = s.Std.Select(ctx, query, args, []interface{}{&exists}) return } // UnsafeCount counts the rows for a single column in a specified table. // // This method IS NOT SAFE AGAINST SQL-INJECTION. Use it only with trusted // input! func (s *MySQL) UnsafeCount(ctx context.Context, table, column string) (count int64, err error) { query := fmt.Sprintf("SELECT COUNT(%s) FROM %s", column, table) err = s.Std.Select(ctx, query, []interface{}{}, []interface{}{&count}) return }